我用下面的命令在Openssl中加密了一個包含「Hola mundo」的文件。然後,我想用C#解密這個文件。OpenSSL中的TripleDES加密和使用C#解密#
enc -des-ede -nosalt -in ArchivoNormal.txt -pass file:MiCertificado.cer -out ArchivoEncryptadoTDEOpenSSL.txt
1)爲了得到MiCertificado.cer
private byte[] GenerateKey()
{
X509Certificate2 cer = new X509Certificate2();
cer.Import("D:\\MiCertificado.cer");
TripleDESCryptoServiceProvider desCrypto = (TripleDESCryptoServiceProvider)TripleDESCryptoServiceProvider.Create();
byte[] results = cer.GetPublicKey();
MD5 md5 = MD5.Create();
int preKeyLength = results.Length;
byte[] prekey = null;
prekey = new byte[preKeyLength];
Buffer.BlockCopy(results, 0, prekey, 0, results.Length);
byte[] key = md5.ComputeHash(prekey);
md5.Clear();
md5 = null;
return key;
}
2)的公開密鑰以便解密加密文件
private void DecryptFile(string source, string destination, byte[] bkey)
{
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();
TDES.Mode = CipherMode.ECB;
TDES.Padding = PaddingMode.PKCS7;
TDES.KeySize = 192;
TDES.BlockSize = 64;
TDES.Key = bkey;
FileStream fsread = new FileStream(source, FileMode.Open, FileAccess.Read);
ICryptoTransform desdecrypt = TDES.CreateDecryptor();
CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
StreamWriter fsDecrypted = new StreamWriter(destination);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}
它返回一個錯誤「DATOS Incorrectos 「
不要使用3DES,使用AES,它是高級加密標準,不難使用,更安全。 – zaph
確實如此,但這次我必須使用3DES,我無法改變這一點。 – EduardoUstarez
啊是的,安全是次要的問題。 – zaph