gpt4 book ai didi

.net - 通用字符串加密

转载 作者:行者123 更新时间:2023-12-04 18:17:20 25 4
gpt4 key购买 nike

我正在寻找.NET中的常规字符串加密类。 (不要与“SecureString”类混淆。)

我已经开始提出自己的类,但是认为必须有一个.NET类,该类已经允许您使用任何加密服务提供程序加密/解密任何编码的字符串。

Public Class SecureString

Private key() As Byte
Private iv() As Byte
Private m_SecureString As String

Public ReadOnly Property Encrypted() As String
Get
Return m_SecureString
End Get
End Property

Public ReadOnly Property Decrypted() As String
Get
Return Decrypt(m_SecureString)
End Get
End Property

Public Sub New(ByVal StringToSecure As String)
If StringToSecure Is Nothing Then StringToSecure = ""
m_SecureString = Encrypt(StringToSecure)
End Sub

Private Function Encrypt(ByVal StringToEncrypt As String) As String

Dim result As String = ""
Dim bytes() As Byte = Text.Encoding.UTF8.GetBytes(StringToEncrypt)

Using provider As New AesCryptoServiceProvider()

With provider
.Mode = CipherMode.CBC
.GenerateKey()
.GenerateIV()
key = .Key
iv = .IV
End With

Using ms As New IO.MemoryStream
Using cs As New CryptoStream(ms, provider.CreateEncryptor(), CryptoStreamMode.Write)
cs.Write(bytes, 0, bytes.Length)
cs.FlushFinalBlock()
End Using
result = Convert.ToBase64String(ms.ToArray())
End Using

End Using

Return result

End Function

Private Function Decrypt(ByVal StringToDecrypt As String) As String

Dim result As String = ""
Dim bytes() As Byte = Convert.FromBase64String(StringToDecrypt)

Using provider As New AesCryptoServiceProvider()

Using ms As New IO.MemoryStream
Using cs As New CryptoStream(ms, provider.CreateDecryptor(key, iv), CryptoStreamMode.Write)
cs.Write(bytes, 0, bytes.Length)
cs.FlushFinalBlock()
End Using
result = Text.Encoding.UTF8.GetString(ms.ToArray())
End Using

End Using

Return result

End Function

End Class

最佳答案

通常,用于对称加密的AES算法是对字符串进行通用加密的方法。但是,恐怕.NET BCL提供基本的加密/解密类和功能不会进一步简化您的工作。

您可以找到一个很好的示例,说明如何使用this page上的加密类专门用于字符串加密。它似乎非常完整且确实受到好评-您甚至可能会发现无需任何进一步修改就可以使用它。注意:Rijndael与AES是相同的算法。 (从技术上讲,前者是指算法的真实名称,而后者是指高级加密标准。)

关于.net - 通用字符串加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/900610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com