locked
RSA Encryption using Public Key from Certificate Store RRS feed

  • Question

  • I am able to retrieve a public key from the Local Machine/Personal Store as follows:

         Dim SvrPubKeyCert As X509Certificate2 = Nothing
            Dim SvrPubKeyStore As New X509Store(StoreName.My, StoreLocation.LocalMachine)
    
            SvrPubKeyStore.Open(OpenFlags.ReadOnly)
    
            Try
                Dim results As X509Certificate2Collection = SvrPubKeyStore.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, "C=GB, CN=My Server Cert", False)
                If results.Count = 0 Then
                    Throw New Exception("Unable to find certificate!")
                Else
                    SvrPubKeyCert = results(0)
                End If
            Finally
                SvrPubKeyStore.Close()
            End Try

    How can I now use the public key which is contained within SvrPubKeyCert in conjunction with RsaCryptoServiceProvider to actually perform the encryption?

    Thanks

    John


    Cheers, John

    Sunday, August 16, 2015 9:06 PM

Answers

  • I worked out how to do this eventually:

            Dim SvrPubKeyCert As X509Certificate2 = Nothing
            Dim SvrPubKeyStore As New X509Store(StoreName.My, StoreLocation.LocalMachine)
            Dim ClearBytes() As Byte = ASCIIEncoding.ASCII.GetBytes(ClearLicCode)
    
            SvrPubKeyStore.Open(OpenFlags.ReadOnly)
    
            Try
                Dim results As X509Certificate2Collection = SvrPubKeyStore.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, "C=GB, CN=My Server Cert", False)
                If results.Count = 0 Then
                    Throw New Exception("Unable to find certificate!")
                Else
                    SvrPubKeyCert = results(0)
                End If
            Finally
                SvrPubKeyStore.Close()
            End Try
    
            Dim RsaEncrypt As RSACryptoServiceProvider = CType(SvrPubKeyCert.PublicKey.Key, RSACryptoServiceProvider)
            EncryptLicenseCode = RsaEncrypt.Encrypt(ClearBytes, False)


    Cheers, John


    • Edited by j_dublevay Sunday, August 16, 2015 9:55 PM
    • Marked as answer by j_dublevay Sunday, August 16, 2015 9:55 PM
    Sunday, August 16, 2015 9:55 PM