none
Decrypt problem RRS feed

  • Question

  • Hello all,

    I have an issue with encyption and decryption, when I encrypt a password it does it very well but when I try to decrypt I get error message "Length of the data to decrypt is invalid"

    This is the function to encrypt the password:
    
    Public Function Encrypt(str As String) As String
            Dim EncrptKey As String = "2013;[pnuLIT)WebCodeExpert"
            Dim byKey As Byte() = {}
            Dim IV As Byte() = {18, 52, 86, 120, 144, 171, _
             205, 239}
            byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8))
            Dim des As New DESCryptoServiceProvider()
            Dim inputByteArray As Byte() = Encoding.UTF8.GetBytes(str)
            Dim ms As New MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Return Convert.ToBase64String(ms.ToArray())
        End Function


    This is the code that I´m using to decrypt but it is when I get the error mentioned above.
    
    Public Function Decrypt(str As String) As String
            str = str.Replace(" ", "+")
            Dim DecryptKey As String = "2013;[pnuLIT)WebCodeExpert"
            Dim byKey As Byte() = {}
            Dim IV As Byte() = {18, 52, 86, 120, 144, 171, _
             205, 239}
            Dim inputByteArray As Byte() = New Byte(str.Length - 1) {}
    
            byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8))
            Dim des As New DESCryptoServiceProvider()
            inputByteArray = Convert.FromBase64String(str.Replace(" ", "+"))
            Dim ms As New MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
            Return encoding.GetString(ms.ToArray())
        End Function

    Does anybody have any idea what exactly is going on? Any help will be very much appreciated.


    Ivannovish



    • Edited by Ivannovish Thursday, July 13, 2017 1:55 AM
    Thursday, July 13, 2017 1:53 AM

All replies

  • Ivan,

    This is a better alternative:

    https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/strings/walkthrough-encrypting-and-decrypting-strings


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, July 13, 2017 2:42 AM
  • Give an example of the string that cannot be decrypted after encryption.

    Replacing “ ” with “+” is probably not needed.

    Thursday, July 13, 2017 5:07 AM
  • Hi lvannovish,

    Why do you need to replace space with +?

    inputByteArray = Convert.FromBase64String(str.Replace(" ", "+"))

    If the Base64 string contains space replace it with nothing.

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, July 13, 2017 6:22 AM
    Moderator
  • Ivan,

    You might want to try the following. Drop the following class into your program:

    Code For Class

    Imports System.Security.Cryptography Public NotInheritable Class Simple3Des Implements IDisposable Private TripleDes As New TripleDESCryptoServiceProvider Public Sub Dispose() Implements IDisposable.Dispose If TripleDes IsNot Nothing Then TripleDes.Dispose() TripleDes = Nothing End If End Sub Public Sub New(ByVal key As String) ' Initialize the crypto provider. TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8) TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8) End Sub Public Function EncryptData(ByVal plaintext As String) _ As String ' Convert the plaintext string to a byte array. Dim plaintextBytes() As Byte = _ System.Text.Encoding.Unicode.GetBytes(plaintext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the encoder to write to the stream. Dim encStream As New CryptoStream(ms, _ TripleDes.CreateEncryptor(), _ System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. encStream.Write(plaintextBytes, 0, plaintextBytes.Length) encStream.FlushFinalBlock() ' Convert the encrypted stream to a printable string. Return Convert.ToBase64String(ms.ToArray) End Function Public Function DecryptData(ByVal encryptedtext As String) _ As String ' Convert the encrypted text string to a byte array. Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the decoder to write to the stream. Dim decStream As New CryptoStream(ms, _ TripleDes.CreateDecryptor(), _ System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. decStream.Write(encryptedBytes, 0, encryptedBytes.Length) decStream.FlushFinalBlock() ' Convert the plaintext stream to a string. Return System.Text.Encoding.Unicode.GetString(ms.ToArray) End Function Private Function TruncateHash(ByVal key As String, _ ByVal length As Integer) _ As Byte() Dim sha1 As New SHA1CryptoServiceProvider ' Hash the key. Dim keyBytes() As Byte = _ System.Text.Encoding.Unicode.GetBytes(key) Dim hash() As Byte = sha1.ComputeHash(keyBytes) ' Truncate or pad the hash. ReDim Preserve hash(length - 1) Return hash End Function End Class


    I tested it with the following

    Test Code (Form1)

    Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private Sub _ Form1_Load(sender As System.Object, _ e As System.EventArgs) _ Handles MyBase.Load Const EncryptKey As String = _ "2013;[pnuLIT)WebCodeExpert" Const textToEncrypt As String = _ "This is a secret message" Dim encrypted As String = _ GetEncryptedText(textToEncrypt, EncryptKey) If Not String.IsNullOrWhiteSpace(encrypted) Then MessageBox.Show(encrypted, "Encrypted Text") Dim decrypted As String = _ GetDecryptedText(encrypted, EncryptKey) If Not String.IsNullOrWhiteSpace(decrypted) Then MessageBox.Show(decrypted, "Decrypted Text") End If End If Stop End Sub Private Function _ GetEncryptedText(ByVal textToEncrypt As String, _ ByVal encryptionKey As String) As String Dim retVal As String = Nothing If Not String.IsNullOrWhiteSpace(textToEncrypt) AndAlso _ Not String.IsNullOrWhiteSpace(encryptionKey) Then Using s3d As New Simple3Des(encryptionKey) retVal = s3d.EncryptData(textToEncrypt) End Using End If Return retVal End Function Private Function _ GetDecryptedText(ByVal textToDecrypt As String, _ ByVal encryptionKey As String) As String Dim retVal As String = Nothing If Not String.IsNullOrWhiteSpace(textToDecrypt) AndAlso _ Not String.IsNullOrWhiteSpace(encryptionKey) Then Using s3d As New Simple3Des(encryptionKey) retVal = s3d.DecryptData(textToDecrypt) End Using End If Return retVal End Function End Class


    I hope that helps.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, July 13, 2017 11:46 AM
  • I have copied and pasted the code into a project and after 20+ phrases to encrypt and decrypt, I gave up, I was not able to get the decrypt to fail even once. As was asked, is there a specific phrase that fails ?

    I added this and tried another few dozen times

        Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
            'r as new random declared at form level
            Dim phrase As String = ""
            For index As Integer = 0 To r.Next(20, 60)
                phrase &= Chr(r.Next(32, 126))
            Next
            TextBox1.Text = phrase
        End Sub
    Still no fails

    Thursday, July 13, 2017 2:10 PM
  • I will try some of your recommendations above and thank you for your time on this matter.

    Mostly this happens when the encryption on a textbox is too long.

    For example, when I pass the information from a datagridview to textboxes and when I try to decrypt it on the textbox using a checkbox is when I get the error and specially happen when the encryption words are too long, example "fd15fd5sdf1215.sfd=" if it is shorter this issue does not happen.

    Thank you for all your help and I will do more tests when I get home today.

    Best wishes to all,

    Ivan U.


    Ivannovish


    • Edited by Ivannovish Thursday, July 13, 2017 8:25 PM
    Thursday, July 13, 2017 8:25 PM
  • I will try some of your recommendations above and thank you for your time on this matter.

    Mostly this happens when the encryption on a textbox is too long.

    For example, when I pass the information from a datagridview to textboxes and when I try to decrypt it on the textbox using a checkbox is when I get the error and specially happen when the encryption words are too long, example "fd15fd5sdf1215.sfd=" if it is shorter this issue does not happen.

    Thank you for all your help and I will do more tests when I get home today.

    Best wishes to all,

    Ivan U.


    Ivannovish


    Using Frank Smith's example, I tried your phrase "fd15fd5sdf1215.sfd=", no problems. I also typed a lot of random characters several times, again no issues.

    Friday, July 14, 2017 1:25 AM
  • Here is where Im getting the error

    This the Cell that Im sending to the textbox where Im getting the error, once i click the line i get the error above.

    This the Cell that Im sending to the textbox where Im getting the error

    This is the code Im using to send the info from the datagrid to the textboxes.


    Ivannovish

    Friday, July 14, 2017 5:39 AM
  • Hi lvannovish,

    I try you code and it works fine.

     Private Sub Form6_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Const textToEncrypt As String =
                "This is a secret message"
    
            Dim encrypted As String =
                Encrypt(textToEncrypt)
    
            If Not String.IsNullOrWhiteSpace(encrypted) Then
                MessageBox.Show(encrypted, "Encrypted Text")
    
                Dim decrypted As String =
                    Decrypt(encrypted)
    
                If Not String.IsNullOrWhiteSpace(decrypted) Then
                    MessageBox.Show(decrypted, "Decrypted Text")
                End If
            End If
    
            Stop
    
        End Sub
        Public Function Encrypt(str As String) As String
            Dim EncrptKey As String = "2013;[pnuLIT)WebCodeExpert"
            Dim byKey As Byte() = {}
            Dim IV As Byte() = {18, 52, 86, 120, 144, 171,
             205, 239}
            byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8))
            Dim des As New DESCryptoServiceProvider()
            Dim inputByteArray As Byte() = Encoding.UTF8.GetBytes(str)
            Dim ms As New MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Return Convert.ToBase64String(ms.ToArray())
        End Function
        Public Function Decrypt(str As String) As String
            str = str.Replace(" ", "+")
            Dim DecryptKey As String = "2013;[pnuLIT)WebCodeExpert"
            Dim byKey As Byte() = {}
            Dim IV As Byte() = {18, 52, 86, 120, 144, 171,
             205, 239}
            Dim inputByteArray As Byte() = New Byte(str.Length - 1) {}
    
            byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8))
            Dim des As New DESCryptoServiceProvider()
            inputByteArray = Convert.FromBase64String(str.Replace(" ", "+"))
            Dim ms As New MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
            Return encoding.GetString(ms.ToArray())
        End Function

    I have no errors in the process.

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Proposed as answer by Ivanoskie Thursday, August 24, 2017 7:59 PM
    Wednesday, July 19, 2017 9:20 AM
    Moderator