Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. int index( char c ) {
  2. for ( size_t ii = 0; ii < AVAILABLE_CHARS.size( ); ii++ ) {
  3. if ( AVAILABLE_CHARS [ ii ] == c ) {
  4. // std::cout << ii << " " << c << std::endl;
  5. return ii;
  6. }
  7. }
  8. return -1;
  9. }
  10.  
  11. std::string extend_key( std::string& msg, std::string& key ) {
  12. //generating new key
  13. int msgLen = msg.size( );
  14. std::string newKey( msgLen, 'x' );
  15. int keyLen = key.size( ), i, j;
  16. for ( i = 0, j = 0; i < msgLen; ++i, ++j ) {
  17. if ( j == keyLen )
  18. j = 0;
  19.  
  20. newKey [ i ] = key [ j ];
  21. }
  22. newKey [ i ] = '\0';
  23. return newKey;
  24. }
  25.  
  26. std::string encrypt_vigenere( std::string& msg, std::string& key ) {
  27. int msgLen = msg.size( ), keyLen = key.size( ), i;
  28. std::string encryptedMsg( msgLen, 'x' );
  29. // char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];
  30.  
  31. std::string newKey = extend_key( msg, key );
  32.  
  33. //encryption
  34. for ( i = 0; i < msgLen; ++i ) {
  35. // std::cout << msg[i] << " " << isalnum(msg[i]) << std::endl;
  36. if ( isalnum( msg [ i ] ) || msg [ i ] == ' ' ) {
  37. encryptedMsg [ i ] = AVAILABLE_CHARS [ ( ( index( msg [ i ] ) + index( newKey [ i ] ) ) % AVAILABLE_CHARS.size( ) ) ];
  38. }
  39. else {
  40. encryptedMsg [ i ] = msg [ i ];
  41. }
  42. }
  43.  
  44. encryptedMsg [ i ] = '\0';
  45. return encryptedMsg;
  46. }
  47.  
  48. std::string decrypt_vigenere( std::string& encryptedMsg, std::string& newKey ) {
  49. // decryption
  50. int msgLen = encryptedMsg.size( );
  51. std::string decryptedMsg( msgLen, 'x' );
  52. int i;
  53. for ( i = 0; i < msgLen; ++i ) {
  54. if ( isalnum( encryptedMsg [ i ] ) || encryptedMsg [ i ] == ' ' ) {
  55. decryptedMsg [ i ] = AVAILABLE_CHARS [ ( ( ( index( encryptedMsg [ i ] ) - index( newKey [ i ] ) ) + AVAILABLE_CHARS.size( ) ) % AVAILABLE_CHARS.size( ) ) ];
  56. }
  57. else {
  58. decryptedMsg [ i ] = encryptedMsg [ i ];
  59. }
  60. }
  61. decryptedMsg [ i ] = '\0';
  62. return decryptedMsg;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement