兩個簡單的方法來加密,並與鏈接的頁面解密兼容:
public static byte[] HexToBytes(string str, string separator = " ")
{
if (str == null)
{
throw new ArgumentNullException();
}
if (separator == null)
{
separator = string.Empty;
}
if (str == string.Empty)
{
return new byte[0];
}
int stride = 2 + separator.Length;
if ((str.Length + separator.Length) % stride != 0)
{
throw new FormatException();
}
var bytes = new byte[(str.Length + separator.Length)/stride];
for (int i = 0, j = 0; i < str.Length; i += stride)
{
bytes[j] = byte.Parse(str.Substring(i, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
j++;
// There is no separator at the end!
if (j != bytes.Length && separator != string.Empty)
{
if (string.CompareOrdinal(str, i + 2, separator, 0, separator.Length) != 0)
{
throw new FormatException();
}
}
}
return bytes;
}
public static string BytesToHex(byte[] bytes, string separator = " ")
{
if (bytes == null)
{
throw new ArgumentNullException();
}
if (separator == null)
{
separator = string.Empty;
}
if (bytes.Length == 0)
{
return string.Empty;
}
var sb = new StringBuilder((bytes.Length * (2 + separator.Length)) - 1);
for (int i = 0; i < bytes.Length; i++)
{
if (i != 0)
{
sb.Append(separator);
}
sb.Append(bytes[i].ToString("x2"));
}
return sb.ToString();
}
public static byte[] SimpleEncrypt(SymmetricAlgorithm algorithm, CipherMode cipherMode, byte[] key, byte[] iv, byte[] bytes)
{
algorithm.Mode = cipherMode;
algorithm.Padding = PaddingMode.Zeros;
algorithm.Key = key;
algorithm.IV = iv;
using (var encryptor = algorithm.CreateEncryptor())
{
return encryptor.TransformFinalBlock(bytes, 0, bytes.Length);
}
}
public static byte[] SimpleDecrypt(SymmetricAlgorithm algorithm, CipherMode cipherMode, byte[] key, byte[] iv, byte[] bytes)
{
algorithm.Mode = cipherMode;
algorithm.Padding = PaddingMode.Zeros;
algorithm.Key = key;
algorithm.IV = iv;
using (var encryptor = algorithm.CreateDecryptor())
{
return encryptor.TransformFinalBlock(bytes, 0, bytes.Length);
}
}
這樣使用它:
string text = "xxxyyy";
string key = "da 39 a3 ee 5e 6b 4b 0d 32 55 bf ef 95 60 18 90";
string iv = "f8 01 8b 76 7c db 80 9c ed 66 fd 63 e8 41 d6 04";
var encrypted = BytesToHex(
SimpleEncrypt(
new RijndaelManaged(),
CipherMode.CBC,
HexToBytes(key),
HexToBytes(iv),
Encoding.UTF8.GetBytes(text)));
var decrypted = Encoding.UTF8.GetString(
SimpleDecrypt(
new RijndaelManaged(),
CipherMode.CBC,
HexToBytes(key),
HexToBytes(iv),
HexToBytes(encrypted))).TrimEnd('\0');
注意,該頁面不好f或二進制數據,因爲它使用Padding.Zeros
。問題是,這些字節組成的明文:
00 01 02 03 04 05 06 07
轉化爲
00 01 02 03 04 05 06 07 00 00 00 00 00 00 00 00
加密之前
,因爲它是填充到16個字符。這個操作不能逆轉。您使用的PaddingMode.PKCS7
更好,因爲它可以顛倒,但與該頁面不兼容!如果您使用字符串進行加密,這不是問題,因爲您可以執行TrimEnd('\0')
並刪除多餘的\0
。你可以通過一個不小於16的整數的小型壓縮文件來檢查它,通過頁面對它進行加密(「輸入類型」選擇文件),然後按下加密,然後按下載爲二進制文件。然後按瀏覽,選擇剛剛下載的文件,按解密,按下載爲二進制文件。文件大小將與原始文件不同,但您仍然可以使用zip打開它。
你的意思是'IV = new byte [16]'和'KeySize = 256'? –
是先生,它的值必須全爲零 – Amit
是的,字節數組的默認值全爲零:http://stackoverflow.com/questions/22506274/in-c-sharp-what-is-the-default-創建新字節數組時的字節數 –