1

I've encrypted a file that contains "Hola mundo" in Openssl with the command below. Then, I want to decrypt this file using C#.

enc -des-ede -nosalt -in ArchivoNormal.txt -pass file:MiCertificado.cer -out ArchivoEncryptadoTDEOpenSSL.txt

1) In order to get the public key from 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) In order to decrypt the encrypted file

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();
}

It returns an error "Datos Incorrectos"

enter image description here

jww
  • 97,681
  • 90
  • 411
  • 885
EduardoUstarez
  • 603
  • 11
  • 22

1 Answers1

1

OpenSSL isn't using the certificate as a certificate in your example, it's just using the contents of the file as a password. It then turns that password into an appropriate key/IV for your 3DES operation using EVP_BytesToKey, with MD5 as the digest since you didn't specify one.

Since it's just reading the file as bytes changing it from DER to PEM encoding, or PEM encoding with extra whitespace will change your encrypted output.

If you're expecting to do something when the public key of the certificate here, then your openssl command isn't right.

bartonjs
  • 30,352
  • 2
  • 71
  • 111
  • To expand on @Barton's comment *"If you're expecting to do something when the public key of the certificate here, then your openssl command isn't right"*, you should investigate PFX and PKCS12. – jww Jul 30 '16 at 02:51