【问题标题】:TripleDES encryption in OpenSSL and decryption using C# [duplicate]OpenSSL 中的 TripleDES 加密和使用 C# 的解密 [重复]
【发布时间】:2016-12-04 15:37:48
【问题描述】:

我已使用以下命令在 Openssl 中加密了一个包含“Hola mundo”的文件。然后,我想用 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,它是高级加密标准,不难使用,更安全。
  • 是的,但这次我必须使用3DES,我无法改变。
  • 啊,是的,安全是次要问题。

标签: c# encryption openssl x509certificate tripledes


【解决方案1】:

OpenSSL 在您的示例中没有使用证书作为证书,它只是使用文件的内容作为密码。然后,它使用EVP_BytesToKey 将该密码转换为适合您的 3DES 操作的密钥/IV,并使用 MD5 作为摘要,因为您没有指定一个。

由于它只是将文件作为字节读取,因此将其从 DER 更改为 PEM 编码,或者带有额外空格的 PEM 编码将更改您的加密输出。

如果您希望在此处使用证书的公钥时执行某些操作,那么您的 openssl 命令不正确。

【讨论】:

  • 扩展@Barton 的评论“如果您希望在此处使用证书的公钥时执行某些操作,那么您的 openssl 命令不正确”,您应该调查 PFX 和 PKCS12。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多