这是我的仿射加密和解密代码。
我有char
个26个字符的数组。
ax + b % 26
与解密公式
不匹配a - inverse(ciphertext[c]-b) % 26
例如,当a=3
和b=5
时,我加密r
。 r
在字符数组中的位置是17
加密公式:
((3*17+5) %26) = (56%26) = 4
数组中4
位置的字符为e
。当我解密密文时,3
的反向值为9
。所以,Math.abs(3(4-5)%26)=3
不正确。
private static String affinecipher(String plainText) {
String encrypt = "";
int value = 0;
int location=0;
String text=plainText.toUpperCase();
Scanner inputData = new Scanner(System.in);
System.out.print("Enter a:");
a = inputData.nextInt();
System.out.print("Enter b:");
b = inputData.nextInt();
for(int p = 0; p < text.length(); p++){
for(int q =0 ; q<letter.length; q++){
if(text.charAt(p)==letter[q]){
// checking each plaintext character position to letter array position.
// if match found returning the letter position
location=q;
}
}
value= (((a*location)+b) % m);
// value of a multiplied by letter position adding to b and taking the mod.
// adding the string with value position from letter
encrypt = encrypt +letter[value];
}
return encrypt;
}
//decryption
private static String decryptAffineCipher(String encryptText){
String decrypt=" ";int location=0;
//calculating the inverse value
a %= 26;
for(int x = 1; x < 26; x++) {
if((a*x) % 26 == 1) {
inverse=x;
}
}
for (int p = 0; p < encryptText.length(); p++){
for(int q =0 ; q<letter.length; q++){
//finding the location of cipher character
if(encryptText.charAt(p)==letter[q]){
location=q;
}
}
//decryption formula a-inverse(c-b)%26
int step1=Math.abs(location-b);
int step2=inverse* step1;
int value=step2 %26;
//char letter[26] that stores value from A to Z
decrypt = decrypt +letter[value];
}
return decrypt;
}