0
奔來從my last TripleDES-related question以下的,這裏是我的TripleDes的包裝代碼,用於加密和解密的整數:我TripleDes的包裝不起作用
public static class Crypto {
private static Byte[] _fixedIv = new Byte[] { /* 8 random bytes, const */ };
private static TripleDES _tripleDes;
private static Byte[] _key;
static Crypto() {
_tripleDes = TripleDES.Create();
_tripleDes.Mode = CipherMode.CFB;
String key = ConfigurationManager.AppSettings["cryptoKeyId"];
_key = Convert.FromBase64String(key);
}
/// <summary>Encrypts the specified integer using the configuration-stored key.</summary>
public static String EncryptID(Int32 id) {
Byte[] input = new Byte[8]; // 64-bit block size
Byte[] inputLo = BitConverter.GetBytes(id);
for(int i=0;i<inputLo.Length;i++) input[i] = inputLo[i];
ICryptoTransform tr = _tripleDes.CreateEncryptor(_key, _fixedIv);
Byte[] output = new Byte[8];
tr.TransformBlock(input, 0, input.Length, output, 0);
return Convert.ToBase64String(output);
}
/// <summary>Decrypts the specified string (storing an integer) using the configuration-stored key.</summary>
public static Int32 DecryptID(String s) {
Byte[] ciphertext = Convert.FromBase64String(s);
ICryptoTransform tr = _tripleDes.CreateDecryptor(_key, _fixedIv);
Byte[] output = new Byte[8];
tr.TransformBlock(ciphertext, 0, ciphertext.Length, output, 0);
Byte[] outputLo = new Byte[4] { output[0], output[1], output[2], output[3] };
return BitConverter.ToInt32(outputLo, 0);
}
}
當我運行它,我得到的每個輸入確定的結果到EncryptID
,但每撥打DecryptID
都會返回零。我進入代碼並說「輸出」數組的內容全部爲零(並且tr.TransformBlock
返回零)。有誰知道我做錯了什麼?
我打過電話tr.TransformFinalBlock
,但我有一個例外:
'tr.TransformFinalBlock(ciphertext, 0, ciphertext.Length)' threw an exception of type System.Security.Cryptography.CryptographicException' base {System.SystemException}: {"Bad Data.\r\n"}