What's the best way to encrypt short strings in .NET?

前端 未结 6 1981
醉酒成梦
醉酒成梦 2020-12-06 02:56

My boss wants me to encrypt some information used during data transfer. The individual strings to be encrypted are between eight and twenty characters long. A single passwor

6条回答
  •  不思量自难忘°
    2020-12-06 03:33

    Here is encrypt & decrypt function with des3 encryption

    ''' 
    ''' Encrypts a memory string (i.e. variable).
    ''' 
    ''' String to be encrypted.
    ''' Encryption key.
    ''' Encryption initialization vector.
    ''' Encrypted string.
    Public Shared Function Encrypt(ByVal data As String, ByVal key As String, ByVal iv As String) As String
        Dim bdata As Byte() = Encoding.ASCII.GetBytes(data)
        Dim bkey As Byte() = HexToBytes(key)
        Dim biv As Byte() = HexToBytes(iv)
    
        Dim stream As MemoryStream = New MemoryStream
        Dim encStream As CryptoStream = New CryptoStream(stream, des3.CreateEncryptor(bkey, biv), CryptoStreamMode.Write)
    
        encStream.Write(bdata, 0, bdata.Length)
        encStream.FlushFinalBlock()
        encStream.Close()
    
        Return BytesToHex(stream.ToArray())
    End Function
    
    ''' 
    ''' Decrypts a memory string (i.e. variable).
    ''' 
    ''' String to be decrypted.
    ''' Original encryption key.
    ''' Original initialization vector.
    ''' Decrypted string.
    Public Shared Function Decrypt(ByVal data As String, ByVal key As String, ByVal iv As String) As String
        Dim bdata As Byte() = HexToBytes(data)
        Dim bkey As Byte() = HexToBytes(key)
        Dim biv As Byte() = HexToBytes(iv)
    
        Dim stream As MemoryStream = New MemoryStream
        Dim encStream As CryptoStream = New CryptoStream(stream, des3.CreateDecryptor(bkey, biv), CryptoStreamMode.Write)
    
        encStream.Write(bdata, 0, bdata.Length)
        encStream.FlushFinalBlock()
        encStream.Close()
    
        Return Encoding.ASCII.GetString(stream.ToArray())
    End Function
    

提交回复
热议问题