2012-02-01 5 views
2

문자열을 위해 잘 작동하는 코드입니다 :AES 암호화/여기 해독

Public Function AESEncrypt(ByVal PlainText As String, ByVal Password As String, ByVal salt As String) 
    Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5 
    Dim PasswordIterations As String = 2 
    Dim InitialVector As String = "CanEncryption123" 'This should be a string of 16 ASCII characters. 
    Dim KeySize As Integer = 256 'Can be 128, 192, or 256. 

    If (String.IsNullOrEmpty(PlainText)) Then 
     Return "" 
     Exit Function 
    End If 
    Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector) 
    Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt) 
    Dim PlainTextBytes As Byte() = Encoding.UTF8.GetBytes(PlainText) 
    Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations) 
    Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize/8) 
    Dim SymmetricKey As RijndaelManaged = New RijndaelManaged() 
    SymmetricKey.Mode = CipherMode.CBC 

    Dim CipherTextBytes As Byte() = Nothing 
    Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes) 
     Using MemStream As New MemoryStream() 
      Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write) 
       CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length) 
       CryptoStream.FlushFinalBlock() 
       CipherTextBytes = MemStream.ToArray() 
       MemStream.Close() 
       CryptoStream.Close() 
      End Using 
     End Using 
    End Using 
    SymmetricKey.Clear() 
    Return Convert.ToBase64String(CipherTextBytes) 
End Function 
Public Function AESDecrypt(ByVal CipherText As String, ByVal password As String, ByVal salt As String) As String 
    Dim HashAlgorithm As String = "SHA1" 
    Dim PasswordIterations As String = 2 
    Dim InitialVector As String = "CanEncryption123" 
    Dim KeySize As Integer = 256 

    If (String.IsNullOrEmpty(CipherText)) Then 
     Return "" 
    End If 
    Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector) 
    Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt) 
    Dim CipherTextBytes As Byte() = Convert.FromBase64String(CipherText) 
    Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(password, SaltValueBytes, HashAlgorithm, PasswordIterations) 
    Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize/8) 
    Dim SymmetricKey As RijndaelManaged = New RijndaelManaged() 
    SymmetricKey.Mode = CipherMode.CBC 
    Dim PlainTextBytes As Byte() = New Byte(CipherTextBytes.Length - 1) {} 

    Dim ByteCount As Integer = 0 

    Using Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes) 
     Using MemStream As MemoryStream = New MemoryStream(CipherTextBytes) 
      Using CryptoStream As CryptoStream = New CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read) 
       ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length) 
       MemStream.Close() 
       CryptoStream.Close() 
      End Using 
     End Using 
    End Using 
    SymmetricKey.Clear() 
    Return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount) 
End Function 

것은 내가/암호화 바이트 배열이 아닌 문자열을 해독하는 데 이러한 기능을 수정에 도움을 가질 수 있습니다. 또한 함수가 문자열이 아닌 암호화 된/암호 해독 된 바이트 배열을 반환하도록합니다.

감사

답변

0

가장 간단한 방법은 그냥 바이트 배열을 문자열로 변환하여 AESEncrypt 기능을 암호화하는 래퍼 함수를 ​​사용하는 것입니다, 그리고 바이트 배열로 다시 문자열로 변환합니다. VB.net here에 대한 변환 함수를 찾을 수 있습니다.

편집 추가 : 내가 잘못 생각한 것 같습니다. VB String은 유니 코드 형식이며이 변환 함수는 UTF8 바이트 배열로 /에서 변환합니다. 어떤 것이 필요하지 않은가 ...

+0

그 방법은 문자열이 아닌 바이트 배열을 받아들이는 함수를 수정하는 것만 큼 효과적일까요? –

+0

효율적으로? 하지만 오버 헤드가 무거울 것이라고는 생각하지 않습니다. 효과적일까요? 예. – TonyK

+0

변환 함수를 사용하여 바이트 배열을 문자열로 변환하거나 그 반대로 변환합니다. 어떤 이유로, 암호화 된 바이트 배열 (파일에서)을 해독하려고 시도하면 원본 파일과 동일하지 않습니다. 이러한 변환 루틴을 사용하는 데 제한이 있습니까? –

1

Dim ByteCount As Integer = 0부터 SymmetricKey.Clear()까지 모든 것을 모두 복사하여 모든 문자열을 제거하십시오. 그 후에 함수에 대한 인수 만 정의하면됩니다. 내가 문자열 AES 암호화/암호 해독이가 (구글에 있음) 사용하고

+0

바이트 배열의 암호화 기능은 어떻습니까? :) –

1

:

Imports System.Security.Cryptography 

Namespace TextCrypters 

    Public Class AESCrypter 

     Public Shared pass As String = "password" 

     Public Shared Function AES_Encrypt(ByVal input As String) As String 
      Dim AES As New System.Security.Cryptography.RijndaelManaged 
      Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider 
      Dim encrypted As String = "" 
      Try 
       Dim hash(31) As Byte 
       Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass)) 
       Array.Copy(temp, 0, hash, 0, 16) 
       Array.Copy(temp, 0, hash, 15, 16) 
       AES.Key = hash 
       AES.Mode = CipherMode.ECB 
       Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor 
       Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input) 
       encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)) 
       Return encrypted 
      Catch ex As Exception 
       Return Nothing 
      End Try 

     End Function 

     Public Shared Function AES_Decrypt(ByVal input As String) As String 
      Dim AES As New System.Security.Cryptography.RijndaelManaged 
      Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider 
      Dim decrypted As String = "" 
      Try 
       Dim hash(31) As Byte 
       Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass)) 
       Array.Copy(temp, 0, hash, 0, 16) 
       Array.Copy(temp, 0, hash, 15, 16) 
       AES.Key = hash 
       AES.Mode = CipherMode.ECB 
       Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor 
       Dim Buffer As Byte() = Convert.FromBase64String(input) 
       decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length)) 
       Return decrypted 
      Catch ex As Exception 
       Return Nothing 
      End Try 

     End Function 

    End Class 

End Namespace 

그것을 사용하려면 그냥이 작업을 수행합니다

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    TextBox2.Text = AESCrypter.AES_Encrypt(TextBox1.Text) 
End Sub 

Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 
    TextBox4.Text = AESCrypter.AES_Decrypt(TextBox3.Text) 
End Sub 
+0

코드가 "작동"할 수는 있지만 안전하지는 않습니다 (ECB 모드). ASCII가 아닌 문자가 포함 된 입력이 손상됩니다. – CodesInChaos

0
Public Function AESEncrypt(ByVal PlainBytes As Byte, ByVal Password As String, ByVal salt As String) 
Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5 
Dim PasswordIterations As String = 2 
Dim InitialVector As String = "CanEncryption123" 'This should be a string of 16 ASCII characters. 
Dim KeySize As Integer = 256 'Can be 128, 192, or 256. 

Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector) 
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt) 
Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations) 
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize/8) 
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged() 
SymmetricKey.Mode = CipherMode.CBC 

Dim CipherTextBytes As Byte() = Nothing 
Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes) 
    Using MemStream As New MemoryStream() 
     Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write) 
      CryptoStream.Write(PlainBytes, 0, PlainBytes.Length) 
      CryptoStream.FlushFinalBlock() 
      CipherTextBytes = MemStream.ToArray() 
      MemStream.Close() 
      CryptoStream.Close() 
     End Using 
    End Using 
End Using 
SymmetricKey.Clear() 
Return Convert.ToBase64String(CipherTextBytes) 
End Function 
Public Function AESDecrypt(ByVal CipherBytes As Byte, ByVal password As String, ByVal salt As String) As String 
Dim HashAlgorithm As String = "SHA1" 
Dim PasswordIterations As String = 2 
Dim InitialVector As String = "CanEncryption123" 
Dim KeySize As Integer = 256 

If (String.IsNullOrEmpty(CipherText)) Then 
    Return "" 
End If 
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector) 
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt) 
Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(password, SaltValueBytes, HashAlgorithm, PasswordIterations) 
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize/8) 
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged() 
SymmetricKey.Mode = CipherMode.CBC 
Dim PlainTextBytes As Byte() = New Byte(CipherBytes.Length - 1) {} 

Dim ByteCount As Integer = 0 

Using Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes) 
    Using MemStream As MemoryStream = New MemoryStream(CipherBytes) 
     Using CryptoStream As CryptoStream = New CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read) 
      ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length) 
      MemStream.Close() 
      CryptoStream.Close() 
     End Using 
    End Using 
End Using 
SymmetricKey.Clear() 
Return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount) 
End Function 

당신이 실제로 사용하는 코드 입력 문자열을 바이트 배열로 변환합니다. 이 코드는 바이트 배열을 허용합니다.

관련 문제