Advertisement
Guest User

Untitled

a guest
Oct 20th, 2014
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <cassert>
  2. #include "AffineCipher.h"
  3.  
  4. // #decrypt()
  5. int AffineCipher::decrypt
  6. (
  7.  const vector<byte>& cipher_text,
  8.  const vector<byte>&  key,
  9.  vector<byte>& plain_text)
  10. {
  11.  
  12. if(multInverse(key[0])==0 || (int)key[1]>25){
  13.     cout<<"wrong key"<<endl;
  14.     return 0;
  15.  
  16. }
  17.  
  18. for(vector<byte>::const_iterator it=cipher_text.begin(); it != cipher_text.end();++it){
  19.     plain_text.push_back(multInverse(key[0])*((*it)-key[1])%26);
  20. }
  21. return plain_text.size();
  22.  
  23. } // decrypt()
  24.  
  25.  
  26. // #encrypt()
  27. int AffineCipher::encrypt
  28. (
  29.  const vector<byte>& plain_text,
  30.  const vector<byte>& key,
  31.  vector<byte>& cipher_text
  32. )
  33.  
  34. {
  35. if(multInverse(key[0])==0 || (int)key[1]>25){
  36.     cout<<"wrong key"<<endl;
  37.     return 0;
  38.  
  39. }
  40.  
  41. for(vector<byte>::const_iterator it=plain_text.begin(); it != plain_text.end();++it){
  42.  
  43.     cipher_text.push_back((key[0]*(*it)+key[1]) % 26);
  44. }
  45.  
  46. return cipher_text.size();
  47.  
  48.         //ax+b mod 26
  49.  
  50. } // encrypt()
  51.  
  52.  
  53. // #multInverse()
  54. int AffineCipher::multInverse(byte a) const {
  55.   if (a<26) {
  56.     return inverse_table[a];
  57.   } // if
  58.   else {
  59.     return 0;
  60.   } // else
  61. } // multInverse()
  62.  
  63.  
  64. // #inverse_table
  65. const byte AffineCipher::inverse_table[26] = {
  66.   0,  // 0
  67.   1,  // 1
  68.   0,  // 2
  69.   9,  // 3
  70.   0,  // 4
  71.   21, // 5
  72.   0,  // 6
  73.   15, // 7
  74.   0,  // 8
  75.   3,  // 9
  76.   0,  // 10
  77.   19, // 11
  78.   0,  // 12
  79.   0,  // 13
  80.   0,  // 14
  81.   7,  // 15
  82.   0,  // 16
  83.   23, // 17
  84.   0,  // 18
  85.   11, // 19
  86.   0,  // 20
  87.   5,  // 21
  88.   0,  // 22
  89.   17, // 23
  90.   0,  // 24
  91.   25  // 25
  92. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement