I am encrypting text using Rfc2898DeriveBytes
in C#
Following is my code
private static string Encrypt(string clearText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
I want to restrict '/' and '\' from appearing in the encrypted text. How can I achieve this?
Tool to decrypt / encrypt with Tom-Tom code that uses diagonal bars (slash and anti-slash) similar to Morse or Chinese code.
Type Ctrl + Shift + X on your keyboard to encrypt the selected text.
This is untested, but I think it should work.
var encryptedText = Encrypt("MY SECRET MESSAGE");
var encodedText = Convert.ToBase64String(encryptedText).Replace('/', '*');
var decodedText = Convert.FromBase64String(encodedText.Replace('*', '/'));
var descriptedText = Decrypt(decodedText);
Convert.ToBase64String
converts the input string to base64 characters only:
The base-64 digits in ascending order from zero are the uppercase characters "A" to "Z", the lowercase characters "a" to "z", the numerals "0" to "9", and the symbols "+" and "/". The valueless character, "=", is used for trailing padding.
The obvious issue is the forward slash, so you can replace it with whatever character you want that's not also used in the base64 encoding. Just remember to convert back when you need to decrypt.
As owlstead points out in his comment it may be best to conform to some type of standard. RFC 4648 defines a base64 encoding that meets your needs by substituting +
with -
and /
by _
. I didn't immediately see a way to do this built into .NET, so I'll provide some sample methods:
public static string ToBase64UrlString(string text)
{
return Convert.ToBase64String(text)
.Replace('+', '-').Replace('/', '_');
}
public static string FromBase64UrlString(string text)
{
return Convert.FromBase64String(
text.Replace('-', '+').Replace('_', '/'))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With