Import Public RSA Key From Certificate

后端 未结 3 1955
情歌与酒
情歌与酒 2021-01-28 13:08

Our customer has their public RSA key stored in a certificate.

We need this key hardcoded in our WinRT app, so we can encrypt client-side. However, we\'re having issues

3条回答
  •  情歌与酒
    2021-01-28 13:25

    For those banging his head as how you can use a public key stored in a certificate in a WinRT app, let me ease your pain: You can't, at least not directly.

    The AsymmetricKeyAlgorithmProvider.ImportPublicKey function takes an IBuffer and a CryptographicPublicKeyBlobType, the keyBlob (IBuffer) parameter it's the public key of the certificate, not the full certificate, only its public key.

    But you can't get the public key of the certificate with out parsing it first, here is where the problem lies, there is no way to parse the certificate on WinRT, given that the most used class for this task, X509Certificate, is not available, nor is its namespace, and the facilities for certificates are only to be used on web services connections.

    The only way to workaround this will be by implementing a certificate parser, or porting such functionality from an open source project, like Bouncy Castle. So, if you know one, please leave it in the comments.

    By the way, to export the public key from the certificate (in plain .NET) in a format that can be used in a WinRT app, use this:

    X509Certificate2 Certificate;
    ....
    byte[] CertificatePublicKey = Certificate.PublicKey.EncodedKeyValue.RawData;
    

    Then in the WinRT app use this:

    AsymmetricKeyAlgorithmProvider algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha1);
    IBuffer KeyBuffer = CryptographicBuffer.DecodeFromBase64String(CertificatePublicKeyContent);
    CryptographicKey key = algorithm.ImportPublicKey(KeyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
    

    Note that i encoded the public key in base 64 first, but you may use raw binary data instead (the CryptographicBuffer class has more methods for this purpose).

提交回复
热议问题