views:

590

answers:

2

So I'm encrypting a string using the .net DESCryptoServiceProvider

Is it possible to restrict the character set of the encrypted string so that it doesnt contain specific character ranges?

For example / or \?

+1  A: 

No, but you can encode it in base64 encoding. So it won't contain any non-textual characters.

byte[] encryptedStream = ..
string encryptedString = Convert.ToBase64String(encryptedStream );
Alex Reitbort
+1  A: 

Is the idea that you want to go from a plaintext string to an encrypted string? If so, use an encoding supporting the full range of Unicode to convert from the plaintext to binary data, and base64 to convert from the encrypted binary to "safe" encrypted text.

So the steps of the pipeline are:

Encryption

  • Convert plaintext (string) to plaintext (bytes) - e.g.

    byte[] plainBinary = Encoding.UTF8.GetBytes(plainText);
    
  • Encrypt in the normal way with DESCryptoServiceProvider (plainBinary to encryptedBinary)

  • Convert encrypted binary to encrypted text:

    string encryptedText = Convert.ToBase64String(encryptedBinary);
    

Decryption:

  • Convert encrypted text to encrypted binary:

    byte[] encryptedBinary = Convert.FromBase64String(encryptedText);
    
  • Decrypt in the normal way (encryptedBinary to plainBinary)

  • Convert plain binary to plain text:

    string plainText = Encoding.UTF8.GetString(plainBinary);
    

Alternatively, you can pipe the data using a StreamWriter (for the text to binary conversion), a CryptoStream (for the DES encryption) and a ToBase64Transform leaving just a conversion (using Encoding.ASCII, for example) of the encrypted-and-base64-encoded data at the end. You'd then reverse the process using a FromBase64Transform instead.

If base64 isn't enough of a restriction on the characters created, you could always write your own base64-like transformation - anything that takes arbitrary bytes and produces text which can be decoded back to those bytes, using only the permitted characters, should be fine.

Jon Skeet