Академический Документы
Профессиональный Документы
Культура Документы
1. Concepts
2. Algorithm
3. Java code
4. Output
5. references
Introduction
The Affine cipher is a special case of the more general monoalphabetic
substitution cipher.
The cipher is less secure than a substitution cipher as it is vulnerable to
all of the attacks that work against substitution ciphers, in addition to
other attacks. The cipher's primary weakness comes from the fact that
if the cryptanalyst can discover (by means of frequency analysis, brute
force, guessing or otherwise) the plaintext of two ciphertext characters,
then the key can be obtained by solving a simultaneous equation [1].
The Algorithm
The 'key' for the Affine cipher consists of 2 numbers, we'll call
them a and b. The following discussion assumes the use of a 26
character alphabet (m = 26). a should be chosen to be relatively prime
to m (i.e.a should have no factors in common with m). For example 15
and 26 have no factors in common, so 15 is an acceptable value for a,
however 12 and 26 have factors in common (e.g. 2) so 12 cannot be
used for a value of a. When encrypting, we first convert all the letters
to numbers ('a'=0, 'b'=1, ..., 'z'=25). The ciphertext letter c, for any given
letter p is (remember p is the number representing a letter):
since 'w' = 22, 'd' is transformed into 'w' using the values a=5 and b= 7.
If we continue with all the other letters we would have:
'wbgbuwyqbbhtynhkkzgyqbrhtykb'
Now to decode, the inverse of 5 modulo 26 is 21, i.e. 5*21 = 1 (mod
26). The decoding function is
'defendtheeastwallofthecastle'
Encryption
Decryption
1.
2. package com.sanfoundry.setandstring;
3.
4. import java.util.Scanner;
5.
6. public class AffineCipher
7. {
8. public static String encryptionMessage(String Msg)
9. {
10. String CTxt = "";
11. int a = 3;
12. int b = 6;
13. for (int i = 0; i < Msg.length(); i++)
14. {
15. CTxt = CTxt + (char) ((((a * Msg.charAt(i)) + b) % 26) + 65);
16. }
17. return CTxt;
18. }
19.
20. public static String decryptionMessage(String CTxt)
21. {
22. String Msg = "";
23. int a = 3;
24. int b = 6;
25. int a_inv = 0;
26. int flag = 0;
27. for (int i = 0; i < 26; i++)
28. {
29. flag = (a * i) % 26;
30. if (flag == 1)
31. {
32. a_inv = i;
33. System.out.println(i);
34. }
35. }
36. for (int i = 0; i < CTxt.length(); i++)
37. {
38. Msg = Msg + (char) (((a_inv * ((CTxt.charAt(i) - b)) % 26)) + 65);
39. }
40. return Msg;
41. }
42.
43. public static void main(String[] args)
44. {
45. Scanner sc = new Scanner(System.in);
46. System.out.println("Enter the message: ");
47. String message = sc.next();
48. System.out.println("Message is :" + message);
49. System.out.println("Encrypted Message is : "
50. + encryptionMessage(message));
51. System.out.println("Decrypted Message is: "
52. + decryptionMessage(encryptionMessage(message)));
53. sc.close();
54. }
55.}
Output:
$ javac AffineCipher.java
$ java AffineCipher