daily pastebin goal
9%
SHARE
TWEET

Untitled

a guest Jan 20th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $ cat bob_crypt.cpp
  2. #include <iostream>
  3. #include <string>
  4.  
  5. std::string to_hex(uint32_t n){
  6.     std::string output = "";
  7.     for(uint32_t i=0;i<32;i+=4){
  8.         uint32_t a = (n >> (28 - i)) & 0xf;
  9.         char c;
  10.         if(a >= 10) c = 'a' + (a%10);
  11.         else c = '0' + a;
  12.         output.push_back(c);
  13.     }
  14.     return output;
  15. }
  16.  
  17. uint32_t char_to_int(char c){
  18.     if(c >='0' && c<='9') return c -'0';
  19.     else return c - 'a' + 10;
  20. }
  21.  
  22. std::string str_to_hex(std::string str){
  23.     std::string output = "";
  24.     for(int i=0;i<str.length(); i+=4){
  25.         output+= to_hex((str[i]<<24) | (str[i+1]<<16) | (str[i+2]<<8) | str[i+3]);
  26.     }
  27.     return output;
  28. }
  29.  
  30. std::string from_hex(std::string str){
  31.     std::string output = "";
  32.     for(int i=0;i<str.length(); i+=2){
  33.         char c = (char_to_int(str[i]) << 4) | char_to_int(str[i+1]);
  34.         output.push_back(c);
  35.     }
  36.     return output;
  37. }
  38.  
  39. std::string encrypt(std::string message, std::string key){
  40.     if(key.length() != 16) throw("Bad Key Size");
  41.     while(message.length()%4 != 0) message.push_back('0');
  42.     std::string output = "";
  43.     for(uint32_t i = 0; i<message.length(); i+=4){
  44.         uint32_t a = 0;
  45.         uint32_t b = 0;
  46.         for(uint32_t j = 0; j<4; j++){
  47.             a |= uint32_t(message[i+j]) << ((3-j) *8);
  48.             b |= uint32_t(key[i%16+j]) << ((3-j) *8);
  49.       //printf("%d\n%d\n\n", a, b);
  50.         }
  51.         output+= to_hex(a ^ b);
  52.     }
  53.  
  54.     return output;
  55.  
  56. }
  57.  
  58. std::string decrypt(std::string message, std::string key){
  59.     if(message.length() % 8) throw("Bad Message Size");
  60.     return from_hex(encrypt(from_hex(message), key));
  61. }
  62.  
  63. int main(int argc, char ** argv){
  64.     if(argc != 4){
  65.         std::cout << "incorrect number of args\n";
  66.         std::cout << "Usage: bob_crypt [enc|dec] <message> <key>\n";
  67.         return 0;
  68.     }
  69.  
  70.     std::string cmd = std::string(argv[1]);
  71.     std::string message = std::string(argv[2]);
  72.     std::string key = std::string(argv[3]);
  73.  
  74.     if(cmd == "enc"){
  75.         std::cout << encrypt(message, key) << std::endl;
  76.     }
  77.     else{
  78.         std::cout << decrypt(message, key) << std::endl;
  79.     }
  80.  
  81.     return 0;
  82. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top