How can I encrypt, decrypt and sign using .pfx certificate?

白昼怎懂夜的黑 提交于 2019-12-06 00:34:32

You can open the PFX in .NET, like the following:

var path = <YOUR PFX FILE PATH>;
var password = <YOUR PASSWORD>;

var collection = new X509Certificate2Collection();

collection.Import(path, password, X509KeyStorageFlags.PersistKeySet);

Then, enumerate over the X509Certificate2Collection. Once you have a certificate (assuming there is a single certificate), then:

var certificate = collection[0];

To encrypt data, you can use:

var publicKey = certificate.PublicKey.Key as RSACryptoServiceProvider;

var encryptedData = publicKey.Encrypt(<yourdata>, false);

Here, i didn't use OAEP for encryption, but you can use it by setting the fOAEP to true for the second parameter.

To decrypt data, you can use:

var privateKey = certificate.PrivateKey as RSACryptoServiceProvider;

var data = privateKey.Decrypt(encryptedData, false);

A certificate in the PFX may not have a corresponding private key, so you can use the following property to check if the private key exists before accessing the PrivateKey property

if (!certificate.HasPrivateKey)
    throw new Exception("The certificate does not have a private key");

If you have encrypted with OAEP, then you have to decrypt with fOAEP set to true.

To sign data, you can use:

var signature = privateKey.SignData(<yourdata>, "SHA1");

To verify the signature, you can use:

var isValid = publicKey.VerifyData(<yourdata>, "SHA1", signature);

Here i used SHA1 which is not considered strong. You can use other hashing algorithms like SHA256 which are stronger.

Finally, if you're message is a small string, then the previous procedure is fine. However, if you're encrypting large data, then i suggest that you use symmetric encryption and then encrypt the symmetric key with the public key. (See X509Certificate2 Class for full example.)

Starting in .NET 4.6, the dependency on the *CryptoServiceProvider types has been reduced:

private static byte[] SignArbitrarily(byte[] data, X509Certificate2 cert)
{
    Debug.Assert(data != null);
    Debug.Assert(cert != null);
    Debug.Assert(cert.HasPrivateKey);

    // .NET 4.6(.0):
    using (RSA rsa = cert.GetRSAPrivateKey())
    {
        if (rsa != null)
        {
            // You need to explicitly pick a hash/digest algorithm and padding for RSA,
            // these are just some example choices.
            return rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        }
    }

    // .NET 4.6.1:
    using (ECDsa ecdsa = cert.GetECDsaPrivateKey())
    {
        if (ecdsa != null)
        {
            // ECDSA signatures need to explicitly choose a hash algorithm, but there
            // are no padding choices (unlike RSA).
            return ecdsa.SignData(data, HashAlgorithmName.SHA256);
        }
    }

    // .NET 4.6.2 (currently in preview):
    using (DSA dsa = cert.GetDSAPrivateKey())
    {
        if (dsa != null)
        {
            // FIPS 186-1 (legacy) DSA does not have an option for the hash algorithm,
            //   SHA-1 was the only option.
            // FIPS 186-3 (current) DSA allows any of SHA-1, SHA-2-224, SHA-2-256,
            //   SHA-2-384, and SHA-2-512 (.NET does not support SHA-2-224).
            //   KeySize < 1024 is FIPS-186-1 mode, > 1024 is 186-3, and == 1024 can
            //   be either (depending on the hardware/software provider).
            // So, SHA-1 is being used in this example as the "most flexible",
            //   but may not currently be considered "secure".
            return dsa.SignData(data, HashAlgorithmName.SHA1);
        }
    }

    throw new InvalidOperationException("No algorithm handler");
}

// Uses the same choices as SignArbitrarily.
private static bool VerifyArbitrarily(byte[] data, byte[] signature, X509Certificate2 cert)
{
    Debug.Assert(data != null);
    Debug.Assert(signature != null);
    Debug.Assert(cert != null);

    using (RSA rsa = cert.GetRSAPublicKey())
    {
        if (rsa != null)
        {
            return rsa.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        }
    }

    using (ECDsa ecdsa = cert.GetECDsaPublicKey())
    {
        if (ecdsa != null)
        {
            return ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA256);
        }
    }

    using (DSA dsa = cert.GetDSAPublicKey())
    {
        if (dsa != null)
        {
            return dsa.VerifyData(data, signature, HashAlgorithmName.SHA1);
        }
    }

    throw new InvalidOperationException("No algorithm handler");
}

For asymmetric encrypt/decrypt, RSA is the only algorithm, and a padding mode is required. The new RSAEncryptionPadding.OaepSHA1 is the same as fOAEP: true in RSACryptoServiceProvider. Newer OAEPs are supported by .NET, but not by all underlying providers.

rsaPublic.Encrypt(data, RSAEncryptionPadding.OaepSHA1);
rsaPrivate.Decrypt(encryptedData, RSAEncryptionPadding.OaepSHA1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!