#include #include #include #include using namespace std; void swap ( unsigned char* S, unsigned char* B ){ char temp = *S; *S = *B; *B = temp; } unsigned char* KeyInit ( char* key, int key_length ){ unsigned char* s = ( unsigned char* ) calloc ( 256, sizeof ( unsigned char ) ); for ( int k = 0; k < 256; k++ ) { s[k] = k; } int j = 0; for ( int i = 0; i < 256; i++ ) { j = ( j + s[i] + key[i % key_length] ) % 256; swap ( s[i], s[j] ); } return s; } void RandomGen ( unsigned char* S, int len, unsigned char* w ){ int i = 0; int j = 0; for ( int k = 0; k < len; k++ ){ i = ( i + 1 ) % 256; j = ( j + S[i] ) % 256; swap ( S[i], S[j] ); w[k] = ( S[( S[i] + S[j] ) % 256] ); } } void Encrypt ( char* S, int len, unsigned char* w, unsigned char* X ){ for ( int k = 0; k < len; k++ ) X[k] = S[k] ^ w[k]; } int main () { char key[] = "Secret"; /*ifstream file; file.open ( "message.txt", ios::binary ); if ( !file ){ perror ( "file not found" ); return 1; }*/ FILE* fin = NULL; fpos_t length = 0; fin = fopen ( "message.txt", "rb" ); if ( !fin ){ perror ( "file not found" ); return 1; } fseek ( fin, 0, SEEK_END ); fgetpos ( fin, &length ); char* message = ( char* ) calloc ( length, sizeof ( char ) ); rewind ( fin ); for ( int i = 0; i < length; i++ ) fscanf ( fin, "%c", &message[i] ); fclose ( fin ); unsigned char* w = ( unsigned char* ) calloc ( length, sizeof ( unsigned char ) ); unsigned char* S = KeyInit ( key, ( sizeof ( key ) / sizeof ( char ) ) - 1 ); RandomGen ( S, length, w ); unsigned char* X = ( unsigned char* ) calloc ( length, sizeof ( unsigned char ) ); Encrypt ( message, length, w, X ); FILE* fout = NULL; fout = fopen ( "result.txt", "w" ); if ( !fout ){ perror ( "file not found" ); return 2; } for ( size_t i = 0; i < length; i++ ) //fputc ((int)i, fout ); //fwrite ( (int)5, sizeof ( char ), length, fout ) ; fprintf ( fout, "%02x", X[i] ); //printf ( "%02x\n", X[i] ); fclose ( fout ); return 0; }