dimanche 23 avril 2017

Encryption in Web service not giving the same result compared to the one on the main project

I am trying to pass an encrypted string from my web service to my main project but when I am trying to perform decryption, it returns "Invalid length for a Base-64 char array or string." because the result of the encryption in my main project is not the same with the one in my web service but I'm just using the same encryption.

Sample ("SessionExpired"):

Web Service encryption -> tDaxnTVCaLOxWSIYVZLO5lxJm%2bX1Vg1CcEPXFb1DBLk%3d

Main Project Encryption -> tDaxnTVCaLOxWSIYVZLO5lxJm%252bX1Vg1CcEPXFb1DBLk%253d

Encryption and Decryption Code

    Public Function password_encrypt(clearText As String) As String
        Dim EncryptionKey As String = "MAKV2SPBNI99212"
        Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText)
        Using encryptor As Aes = Aes.Create()
            Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D,
             &H65, &H64, &H76, &H65, &H64, &H65,
             &H76})
            encryptor.Key = pdb.GetBytes(32)
            encryptor.IV = pdb.GetBytes(16)
            Using ms As New MemoryStream()
                Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
                    cs.Write(clearBytes, 0, clearBytes.Length)
                    cs.Close()
                End Using
                clearText = Convert.ToBase64String(ms.ToArray())
            End Using
        End Using
        Return clearText
    End Function

    Public Function password_decrypt(cipherText As String) As String
        If cipherText <> Nothing Then
            Dim EncryptionKey As String = "MAKV2SPBNI99212"
            Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText)
            Using encryptor As Aes = Aes.Create()
                Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D,
             &H65, &H64, &H76, &H65, &H64, &H65,
             &H76})
                encryptor.Key = pdb.GetBytes(32)
                encryptor.IV = pdb.GetBytes(16)
                Using ms As New MemoryStream()
                    Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)
                        cs.Write(cipherBytes, 0, cipherBytes.Length)
                        cs.Close()
                    End Using
                    cipherText = Encoding.Unicode.GetString(ms.ToArray())
                End Using
            End Using
        End If
        Return cipherText
    End Function




Aucun commentaire:

Enregistrer un commentaire