我需要加密和解密字符串值,例如电子邮件地址和数值,但加密后的字符串中不应包含'/',因为我在URL中使用它并使用'/'来获取分隔符一些价值观。
我目前正在使用以下方法:
string passPhrase = "Pas5pr@se"; // can be any string
string saltValue = "s@1tValue"; // can be any string
string hashAlgorithm = "SHA1"; // can be "MD5"
int passwordIterations = 2; // can be any number
string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
int keySize = 256; // can be 192 or 128
public string Encrypt(string plainText)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase,saltValueBytes,hashAlgorithm,passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,encryptor,CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
return cipherText;
}
答案 0 :(得分:11)
如果您只是为了传递URL,我建议您生成任何加密的字符串(无论是否有/
),并执行:
var sanitized = HttpUtility.UrlEncode(encryptedString);
如您所见,/
变为%2f
。然后你可以简单地做:
var encryptedString = HttpUtility.UrlDecode(sanitized)
你将再次获得相同的字符串。
修改: HttpUtility
位于System.Web
汇编中。
答案 1 :(得分:4)
加密本身只输出字节,而不是字符。所以这个问题与加密/解密完全无关。您的实际问题是将任意字节转换为可在URL中使用的字符串。我建议使用URL安全Base64而不是普通的Base64。
这些/
字符由您应用于密文的Base64编码生成。 Base64使用ASCII字母和数字(总共62个),加上/
和+
,最后是=
作为填充。
填充是没用的,所以我会剥掉它。
然后将/
替换为_
,将+
替换为-
。这称为 URL安全Base64 或 base64url 。它在RFC4648中描述。
public static string Base64UrlEncode(byte[] bytes)
{
return Convert.ToBase64String(bytes).Replace("=", "").Replace('+', '-').Replace('/', '_');
}
public static byte[] Base64UrlDecode(string s)
{
s = s.Replace('-', '+').Replace('_', '/');
string padding = new String('=', 3 - (s.Length + 3) % 4);
s += padding;
return Convert.FromBase64String(s);
}
答案 2 :(得分:2)
Convert.ToBase64String
使用字母,数字,+
和/
,因此您只需将/
切换为其他不是字母,数字或+
的内容}:
编码:
// ...
string cipherText = Convert.ToBase64String(cipherTextBytes);
string ctWithoutSlashes = cipherText.Replace("/", "-");
解码
string cipherText = ctWithoutSlashes.Replace("-", "/");
// ...