我一直在努力解密一些通过SSL在Unix机器上加密的数据,我不断得到填充错误,并且不确定我错过了什么。
加密文件是一个简单的文本文件,只是说" Hello World"。
unix中使用的加密命令是:
openssl enc -base64 -aes-256-cbc -k 12345678901234567890123456789012 -in test.txt -out cbc64.txt
我有两种方法可以用来解密:
private static CipherMode sCipherMode = CipherMode.CBC;
private static PaddingMode sPaddingMode = PaddingMode.PKCS7;
private const int HigKeyLen = 32;
private const int HigKeySiz = 256;
public static string decrypt(string text, //the text to be decrypt
int cipherindex// the strength of the original encryption
)
{
byte[] plainText = null;
try
{
string tempText = Regex.Replace(text, @"\n", "");
//get the cipher strength--from cipherindex
CipherKey Key = CipherKey.getCipherKey(cipherindex);
//build and init the Decryptor
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = sCipherMode;
rijndaelCipher.Padding = sPaddingMode;
rijndaelCipher.KeySize = Key.Size;
rijndaelCipher.BlockSize = Key.Size;
byte[] encryptedData = Convert.FromBase64String(tempText);
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(pass);
byte[] keyBytes = new byte[Key.Len];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
{
len = keyBytes.Length;
}
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
}
catch (Exception e)
{
// test code, do nothing
}
return System.Text.Encoding.UTF8.GetString(plainText);
}
这会返回以下错误:填充无效,无法删除。
第二种方法:
public static string Decryptor(string TextToDecrypt)
{
byte[] EncryptedBytes = Convert.FromBase64String(Regex.Replace(TextToDecrypt, @"\n", ""));
//Setup the AES provider for decrypting.
AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider();
//aesProvider.Key = System.Text.Encoding.ASCII.GetBytes(strKey);
//aesProvider.IV = System.Text.Encoding.ASCII.GetBytes(strIV);
aesProvider.BlockSize = 128;
aesProvider.KeySize = 256;
//My key and iv that i have used in openssl
aesProvider.Key = System.Text.Encoding.UTF8.GetBytes(pass);
aesProvider.IV = System.Text.Encoding.UTF8.GetBytes(pass);
aesProvider.Padding = PaddingMode.PKCS7;
aesProvider.Mode = CipherMode.CBC;
ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor(aesProvider.Key, aesProvider.IV);
byte[] DecryptedBytes = cryptoTransform.TransformFinalBlock(EncryptedBytes, 0, EncryptedBytes.Length);
return System.Text.Encoding.ASCII.GetString(DecryptedBytes);
}
由于密码不是块大小的正确长度,第二种方法会产生问题。
我做错了什么?
答案 0 :(得分:1)
你openssl命令错了,我认为它应该是:
<https-listener name="default-ssl" socket-binding="https" security-realm="HTTPSRealm" />
阅读你的代码我看到你做了一些错误的假设:
尝试将openssl enc -base64 -aes-256-cbc -k 12345678901234567890123456789012 -in test.txt -out cbc64.txt
参数添加到openssl enc命令中,它将显示salt和派生密钥以及iv
所以我们来解决这个问题: