如何在RSA vb.net中生成公钥和私钥

时间:2017-02-21 08:29:30

标签: mysql .net vb.net cryptography rsa

如何在RSA vb.net中为客户端服务器程序生成公钥和私钥我使用此代码但在网络中运行时无法正常工作

Imports System.Security.Cryptography
Imports System.Text

' class to allow the use of RSA encryption
Public NotInheritable Class RSA
    Private RSA As RSACryptoServiceProvider

    Sub New(ByVal publicKey As String)
        ' Initialize the crypto provider.
        RSA = New RSACryptoServiceProvider(2048)
        If publicKey <> "" Then
            RSA.FromXmlString(publicKey)
        End If
    End Sub

    Public Function getPublicKey()
        ' retreave the genarated public key
        Dim publicStr As String = RSA.ToXmlString(False)
        Return publicStr
    End Function

    Public Function getPrivateKey()
        ' retreave the genarated private key
        Dim privateStr As String = RSA.ToXmlString(True)
        Return privateStr
    End Function

    Public Function EncryptData(ByVal plainText As String, ByVal publicKey As String)
        ' encrypt plaintext to encrypted byte array
        Try
            RSA.FromXmlString(publicKey)
            Dim encoder As New UTF8Encoding
            Dim textbytes As Byte()
            textbytes = encoder.GetBytes(plainText)
            Dim encryptedBytes As Byte() = RSA.Encrypt(textbytes, False)
            Return encryptedBytes
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Return ""
    End Function

    Public Function DecryptData(ByVal encryptedBytes As Byte(), ByVal privateKey As String)
        ' function to decrypt byte array to plaintext
        Try
            RSA.FromXmlString(privateKey)
            Dim encoder As New UTF8Encoding
            Dim plainBytes As Byte() = RSA.Decrypt(encryptedBytes, False)
            Dim plainText As String = encoder.GetString(plainBytes)
            Return plainText
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Return ""
    End Function

End Class

0 个答案:

没有答案