I have some encrypting (and decrypting) functions that take any int
value and return also any int
value (it uses some xor operations with large prime numbers under the hood):
public interface IIntEncryption {
public int Encrypt(int value);
public int Decrypt(int encryptedValue);
}
Now I want to use it to encrypt string. My idea is to take each char from the string, convert it to int, encrypt with the function above and then convert back to char. The problem is that not every int value is valid character value afaik. So casting int to char won't work. So I am thinking that I will need to convert int to two valid characters somehow and then when decrypting convert each pair of two characters. So basically I am looking for following functions:
public interface IStringEncryption {
public string Encrypt(string str, IIntEncryption intEncryption);
public string Decrypt(string encryptedStr, IIntEncryption intEncryption);
}
I tried many ways but I can't figure out how to encrypt/decrypt array if integers into string representation. Finally I want it to be base64 encoded string.
CodePudding user response:
I have some encrypting (and decrypting) functions that take any int value and return also any int value (it uses some xor operations with large prime numbers under the hood):
This is fine, assuming you are only doing this for fun/education. It is generally frowned upon creating your own encryption algorithms or implementations for anything where security is needed.
My idea is to take each char from the string, convert it to int, encrypt with the function above and then convert back to char
This would not be fine, or at least a very cumbersome way to do it. As you surmised you could fit two utf16 characters in a 32-bit int. But you will still have the same problem converting to a string again, since not all 16 bit values are valid utf16 characters.
A better solution would be to convert your string to a byte-array using some kind of encoding. You can then convert pairs of 4 bytes to int32s, encrypt, convert back to a byte array, and use something like base64 to convert the bytes back to a string.
This might sound a bit complicated, and it is. So most real implementations just work with byte-arrays directly, typically splitting them into some larger chunk-size internally.