读书人

RSA算法用toxmlstring生成的密钥对会加

发布时间: 2013-09-12 22:07:00 作者: rapoo

RSA算法用toxmlstring生成的密钥对能加密不能解密

    Public Function RSAtextEncrypting(ByVal publickey As String, ByVal sourcestr As String) As String
Dim finfo As FileInfo = New FileInfo(publickey)
Dim buf() As Byte = New Byte(finfo.Length) {}
Dim fs As FileStream = File.OpenRead(publickey)
fs.Read(buf, 0, buf.Length)
fs.Close()
Dim xstr As String = (New ASCIIEncoding()).GetString(buf)
Dim rsa As New RSACryptoServiceProvider
rsa.FromXmlString(xstr)
Dim inbuf() As Byte = New Byte(Encoding.Unicode.GetBytes(sourcestr).Length) {}
inbuf = Encoding.Unicode.GetBytes(sourcestr)

Dim outbuf() As Byte

outbuf = rsa.Encrypt(inbuf, true)
Return Replace(BitConverter.ToString(inbuf), "-", "")
End Function

Public Function RSAtextDecrypting(ByVal privatekey As String, ByVal sourcestr As String) As String
Dim finfo As FileInfo = New FileInfo(privatekey)
Dim buf() As Byte = New Byte(finfo.Length) {}
Dim fs As FileStream = File.OpenRead(privatekey)
fs.Read(buf, 0, buf.Length)
fs.Close()
Dim xstr As String = (New ASCIIEncoding()).GetString(buf)
Dim rsa As New RSACryptoServiceProvider
rsa.FromXmlString(xstr)
Dim inbuf() As Byte = New Byte(getbytex(sourcestr).Length) {}
inbuf = getbytex(sourcestr)



Dim outbuf() As Byte

outbuf = rsa.Decrypt(inbuf, True)
Return Encoding.Unicode.GetString(outbuf)
End Function


这就是核心的代码了,只为加密两句话,但是加密完再解密就提示对 OAEP 填充进行解码时出错。
调用代码是这样
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(RSAtextEncrypting("C:\Users\abc\Documents\PGPbak\Pgpbak\ab(onlypublic).txt", "nkl"))
RSAtextDecrypting("C:\Users\abc\Documents\PGPbak\Pgpbak\ab(onlypublic).txt", RSAtextEncrypting("C:\Users\abc\Documents\PGPbak\Pgpbak\ab(onlypublic).txt", "nkl"))
End Sub
vb.net加密
[解决办法]
检查 getbytex() 是否正确还原了 BitConverter.ToString() 的结果。

读书人网 >VB Dotnet

热点推荐