Sage Pay Forms V3.00 AES-128 Encryption VB.Net

782 views Asked by At

I thought I would post this as I did not find an off-the-shelf solution for the AES encryption needed for the V3.00 upgrade.

The SagePay C# solution example for some reason did not have have an encryption/decryption code example in it as far as I could see.

I cobbled together the code from existing posts and the RijndaelManaged Class VB example (https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1)....

Imports System.Security.Cryptography

Public Shared Function AESEncryption(ByVal strCrypt As String) As String
        Dim keyAndIvBytes As [Byte]() = UTF8Encoding.UTF8.GetBytes(strEncryptionPassword)

        ' Create a new instance of the RijndaelManaged 
        ' class.  This generates a new key and initialization  
        ' vector (IV). 
        Using AES As New RijndaelManaged()
            ' Set the mode, padding and block size for the key
            AES.Padding = PaddingMode.PKCS7
            AES.Mode = CipherMode.CBC
            AES.KeySize = 128
            AES.BlockSize = 128

            ' Encrypt the string to an array of bytes. 
            Dim encrypted As Byte() = EncryptStringToBytes(strCrypt, keyAndIvBytes, keyAndIvBytes)

            AESEncryption = "@" & BitConverter.ToString(encrypted).Replace("-", "").ToUpper
        End Using
    End Function
    Public Shared Function AESDecryption(ByVal strCrypt As String) As String
        Dim keyAndIvBytes As [Byte]() = UTF8Encoding.UTF8.GetBytes(strEncryptionPassword)

        ' Create a new instance of the RijndaelManaged 
        ' class.  This generates a new key and initialization  
        ' vector (IV). 
        Using AES As New RijndaelManaged()
            ' Set the mode, padding and block size for the key
            AES.Padding = PaddingMode.PKCS7
            AES.Mode = CipherMode.CBC
            AES.KeySize = 128
            AES.BlockSize = 128

            Dim encryptedData As Byte() = StringToByteArray(strCrypt.Remove(0, 1))

            Dim roundtrip As String = DecryptStringFromBytes(encryptedData, keyAndIvBytes, keyAndIvBytes)

            AESDecryption = roundtrip
        End Using
    End Function
    Shared Function byteArrayToHexString(ByVal ba As Byte()) As String
        Return BitConverter.ToString(ba).Replace("-", "")
    End Function
    Shared Function StringToByteArray(ByVal hex As String) As Byte()
        Return Enumerable.Range(0, hex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(hex.Substring(x, 2), 16)).ToArray()
    End Function
    Shared Function EncryptStringToBytes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
        ' Check arguments. 
        If plainText Is Nothing OrElse plainText.Length <= 0 Then
            Throw New ArgumentNullException("plainText")
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException("IV")
        End If
        Dim encrypted() As Byte
        ' Create an RijndaelManaged object 
        ' with the specified key and IV. 
        Using AES As New RijndaelManaged()
            AES.Padding = PaddingMode.PKCS7
            AES.Mode = CipherMode.CBC
            AES.KeySize = 128
            AES.BlockSize = 128

            AES.Key = Key
            AES.IV = IV

            ' Create a decrytor to perform the stream transform. 
            Dim encryptor As ICryptoTransform = AES.CreateEncryptor(AES.Key, AES.IV)
            ' Create the streams used for encryption. 
            Using msEncrypt As New MemoryStream()
                Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
                    Using swEncrypt As New StreamWriter(csEncrypt)

                        'Write all data to the stream.
                        swEncrypt.Write(plainText)
                    End Using
                    encrypted = msEncrypt.ToArray()
                End Using
            End Using
        End Using

        ' Return the encrypted bytes from the memory stream. 
        Return encrypted

    End Function 'EncryptStringToBytes

    Shared Function DecryptStringFromBytes(ByVal cipherText() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String

        ' Check arguments. 
        If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
            Throw New ArgumentNullException("cipherText")
        End If
        If Key Is Nothing OrElse Key.Length <= 0 Then
            Throw New ArgumentNullException("Key")
        End If
        If IV Is Nothing OrElse IV.Length <= 0 Then
            Throw New ArgumentNullException("IV")
        End If
        ' Declare the string used to hold 
        ' the decrypted text. 
        Dim plaintext As String = Nothing

        ' Create an RijndaelManaged object 
        ' with the specified key and IV. 
        Using AES As New RijndaelManaged
            AES.Padding = PaddingMode.PKCS7
            AES.Mode = CipherMode.CBC
            AES.KeySize = 128
            AES.BlockSize = 128

            'AES.Key = Key
            'AES.IV = IV

            ' Create a decrytor to perform the stream transform. 
            Dim decryptor As ICryptoTransform = AES.CreateDecryptor(Key, IV)

            ' Create the streams used for decryption. 
            Using msDecrypt As New MemoryStream(cipherText)

                Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)

                    Using srDecrypt As New StreamReader(csDecrypt)


                        ' Read the decrypted bytes from the decrypting stream 
                        ' and place them in a string.
                        plaintext = srDecrypt.ReadToEnd()
                    End Using
                End Using
            End Using
        End Using

        Return plaintext

    End Function

Hopefully this will be of use especially as there is only 6 weeks left to migrate to V3.00 and all the V2 options are switched off.

2

There are 2 answers

0
alan1o On

Maybe I'm being silly here but if you reference the SagePay.IntegrationKit.DotNet dll you should have access to their Crytography class.

At least thats what I've done; added the .dll as a reference, imported it as the top of the file then used Cryptography.DecodeAndDecrypt & Cryptography.EncryptAndEncode.

0
Bryn Hill On

c# AES Decryption

Is a great thread for SagePay C# AES encryption needed for the V3.00 upgrade.