C# 是否可以使用Base64获取加密字符串中的冒号
我使用以下方法加密密码,稍后将其保存在字符串中,并用冒号分隔,如下所示: 用户名:MyEncryptedString 我的问题是,我的方法是否可能返回包含冒号的字符串C# 是否可以使用Base64获取加密字符串中的冒号,c#,encryption,encoding,C#,Encryption,Encoding,我使用以下方法加密密码,稍后将其保存在字符串中,并用冒号分隔,如下所示: 用户名:MyEncryptedString 我的问题是,我的方法是否可能返回包含冒号的字符串 public static string EncryptString(string password, string sharedSecret) { if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password")
public static string EncryptString(string password, string sharedSecret) {
if (string.IsNullOrEmpty(password))
throw new ArgumentNullException("password");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try {
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, Salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream()) {
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) {
//Write all data to the stream.
swEncrypt.Write(password);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
} finally {
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
现代密码产生的二进制输出应该与随机噪声无法区分。如果您将此二进制输出解释为文本(ASCII、UTF-8等),如果密文足够长,您可能会在其中看到一个
:
。但你也可以在较短的密文中看到它,但不一定在每一个密文中都会看到。关键是,输出是二进制的,而不是“字符串”
可以对二进制输出进行编码以获得字符串。如果使用Base 64或Hex,则无法获得
:
,因为这不在他们的字母表中。如果您决定使用Base 85编码,那么您可能会得到一个:
,具体取决于特定的字母表(例如)。您是Base64编码,因此Rijndael做什么并不重要,Base64编码做什么很重要(提示:Base64没有冒号),谢谢。我已经编辑了这个问题,这样会更好:)@DavidG我知道,但我不想把我的答案局限于OP的问题。我希望它是一般性的。否则,我会投反对票,继续前进。