none
Encrypt User.Config file RRS feed

  • Question

  • Hello,

    I need to encrypt User.Config located in "C:\Users\UserName\AppData\Local\AppName\Appname.exe\1.0.0.0\User.Config"

    and also the app.exe.config which locate in Debug folder

    i use some value in my.settings which hold important data and by default the application's setting stored in app.exe.config and the user's setting stored in C:\Users\UserName\AppData\Local\AppName\Appname.exe\1.0.0.0\User.Config

    I'm using a class which help me to encrypt and decrypt the user's passwords that stored in SQL DB

    Imports System.Security.Cryptography
    Public NotInheritable Class Simple3Des
        Private TripleDes As New TripleDESCryptoServiceProvider
        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
        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
    
    End Class
    

    can i use this in some way to encrypt the User.Config and app.exe.config files?

    Thursday, August 1, 2019 10:31 PM

Answers

  • Hi

    You really do not want to encrypt either of those files. What you might consider is to encrypt the values in My.Settings.

    Here is some code that may help. This is a stand alone example, needs controls as shown below and Form1 code and Public Class Simple3Des code too. The example just uses random strings to show encrypted and the decrypted values (Button for each)

    ' Form1 with ListBox1 (Start list)
    ' and ListBox2 (Encrypted/Decrypted)
    ' Button1 (Encrypt) and 
    ' Button2 (Decrypt)
    Option Strict On
    Option Explicit On
    Public Class Form1
      '-----------------------------
      ' THIS is what needs protecting!!!
      Dim key As String = "EncypherKey"
      Dim wrapper As New Simple3Des(key)
      '-----------------------------
    
      Dim PlainText As New List(Of String)
      Dim Encoded As New List(Of String)
      Dim Decoded As New List(Of String)
      Dim lengths As New List(Of Integer)
      Dim r As New Random
      Dim alpha As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
      Dim Numeric As String = "1234567890"
      Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' some random test data
        Dim all As String = alpha & Numeric & alpha.ToLower
        Dim len As Integer = 11
        For i As Integer = 0 To 11111
          Dim start As Integer = r.Next(0, all.Length - len + 1)
          Dim entry As String = all.Substring(start, len)
          PlainText.Add(entry)
          ListBox1.Items.Add(entry)
        Next
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' encode and measure 11111 strings
        For Each s As String In PlainText
          Dim en As String = wrapper.EncryptData(s)
          lengths.Add(en.Length)
          Encoded.Add(en)
        Next
        ListBox2.DataSource = Encoded
      End Sub
      Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' decode all
        For Each s As String In Encoded
          Decoded.Add(wrapper.DecryptData(s))
        Next
        ListBox2.DataSource = Decoded
      End Sub
    End Class
    ' from https://msdn.microsoft.com/en-us/library/ms172831.aspx
    
    Option Strict On
    Option Explicit On
    Imports System.Security.Cryptography
    Public Class Simple3Des
        Private TripleDes As New TripleDESCryptoServiceProvider
        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 = Text.Encoding.Unicode.GetBytes(plaintext)
            ' Create the stream.
            Dim ms As New IO.MemoryStream
            ' Create the encoder to write to the stream.
            Dim encStream As New CryptoStream(ms, TripleDes.CreateEncryptor(), 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 IO.MemoryStream
            ' Create the decoder to write to the stream.
            Dim decStream As New CryptoStream(ms, TripleDes.CreateDecryptor(), 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 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 =
                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
    



    Regards Les, Livingston, Scotland

    • Marked as answer by AbanoubZak Thursday, August 1, 2019 11:45 PM
    Thursday, August 1, 2019 10:58 PM

All replies

  • Hi

    You really do not want to encrypt either of those files. What you might consider is to encrypt the values in My.Settings.

    Here is some code that may help. This is a stand alone example, needs controls as shown below and Form1 code and Public Class Simple3Des code too. The example just uses random strings to show encrypted and the decrypted values (Button for each)

    ' Form1 with ListBox1 (Start list)
    ' and ListBox2 (Encrypted/Decrypted)
    ' Button1 (Encrypt) and 
    ' Button2 (Decrypt)
    Option Strict On
    Option Explicit On
    Public Class Form1
      '-----------------------------
      ' THIS is what needs protecting!!!
      Dim key As String = "EncypherKey"
      Dim wrapper As New Simple3Des(key)
      '-----------------------------
    
      Dim PlainText As New List(Of String)
      Dim Encoded As New List(Of String)
      Dim Decoded As New List(Of String)
      Dim lengths As New List(Of Integer)
      Dim r As New Random
      Dim alpha As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
      Dim Numeric As String = "1234567890"
      Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' some random test data
        Dim all As String = alpha & Numeric & alpha.ToLower
        Dim len As Integer = 11
        For i As Integer = 0 To 11111
          Dim start As Integer = r.Next(0, all.Length - len + 1)
          Dim entry As String = all.Substring(start, len)
          PlainText.Add(entry)
          ListBox1.Items.Add(entry)
        Next
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' encode and measure 11111 strings
        For Each s As String In PlainText
          Dim en As String = wrapper.EncryptData(s)
          lengths.Add(en.Length)
          Encoded.Add(en)
        Next
        ListBox2.DataSource = Encoded
      End Sub
      Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' decode all
        For Each s As String In Encoded
          Decoded.Add(wrapper.DecryptData(s))
        Next
        ListBox2.DataSource = Decoded
      End Sub
    End Class
    ' from https://msdn.microsoft.com/en-us/library/ms172831.aspx
    
    Option Strict On
    Option Explicit On
    Imports System.Security.Cryptography
    Public Class Simple3Des
        Private TripleDes As New TripleDESCryptoServiceProvider
        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 = Text.Encoding.Unicode.GetBytes(plaintext)
            ' Create the stream.
            Dim ms As New IO.MemoryStream
            ' Create the encoder to write to the stream.
            Dim encStream As New CryptoStream(ms, TripleDes.CreateEncryptor(), 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 IO.MemoryStream
            ' Create the decoder to write to the stream.
            Dim decStream As New CryptoStream(ms, TripleDes.CreateDecryptor(), 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 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 =
                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
    



    Regards Les, Livingston, Scotland

    • Marked as answer by AbanoubZak Thursday, August 1, 2019 11:45 PM
    Thursday, August 1, 2019 10:58 PM
  • Hi

    You really do not want to encrypt either of those files. What you might consider is to encrypt the values in My.Settings.

    This two lines actually made the image clear in my head, thanks
    Thursday, August 1, 2019 11:45 PM
  • Hi

    Glad you solved the problem.

    Did that other code re: barcode printing work?


    Regards Les, Livingston, Scotland

    Thursday, August 1, 2019 11:56 PM
  • Hi

    Glad you solved the problem.

    Did that other code re: barcode printing work?


    Regards Les, Livingston, Scotland

    the way you provided was including barcode dll Library i think, I'm trying to use only algorithm with this class then apply a true type font to the output

    Imports System.Text.RegularExpressions
    
    Module EAN13Mod
    
        Public Barcode13Digits As String
    
        Public Function EAN13(ByVal text As String) As String
    
            Dim i As Int32
            Dim first As Int32
            Dim checkDigit As Int32 = 0
            Dim EAN13Barcode As String = ""
            Dim tableA As Boolean
    
            Dim m As Boolean = Regex.IsMatch(text, "^\d{12}$")
    
            If (m) Then
    
                For i = 1 To (12 - 1) Step 2
                    System.Diagnostics.Debug.WriteLine(text.Substring(i, 1))
                    checkDigit += Convert.ToInt32(text.Substring(i, 1))
                Next
    
                checkDigit *= 3
                For i = 0 To (12 - 1) Step 2
                    checkDigit += Convert.ToInt32(text.Substring(i, 1))
                Next
    
                text &= (10 - checkDigit Mod 10) Mod 10
                Barcode13Digits = text.ToString()
                EAN13Barcode = text.Substring(0, 1) + Convert.ToChar(65 + Convert.ToInt32(text.Substring(1, 1)))
                first = Convert.ToInt32(text.Substring(0, 1))
                For i = 2 To 6
                    tableA = False
                    Select Case i
                        Case Is = 2
                            If (first >= 0 And first <= 3) Then tableA = True
                        Case Is = 3
                            If (first = 0 Or first = 4 Or first = 7 Or first = 8) Then tableA = True
                        Case Is = 4
                            If (first = 0 Or first = 1 Or first = 4 Or first = 5 Or first = 9) Then tableA = True
                        Case Is = 5
                            If (first = 0 Or first = 2 Or first = 5 Or first = 6 Or first = 7) Then tableA = True
                        Case Is = 6
                            If (first = 0 Or first = 3 Or first = 6 Or first = 8 Or first = 9) Then tableA = True
                    End Select
                    If (tableA) Then
                        EAN13Barcode &= Convert.ToChar(65 + Convert.ToInt32(text.Substring(i, 1)))
                    Else
                        EAN13Barcode &= Convert.ToChar(75 + Convert.ToInt32(text.Substring(i, 1)))
                    End If
                Next
    
                EAN13Barcode &= Convert.ToChar("*")
                For i = 7 To 12
                    EAN13Barcode += Convert.ToChar(97 + Convert.ToInt32(text.Substring(i, 1)))
                Next
                EAN13Barcode += Convert.ToChar("+“)
    
            End If
    
            Return EAN13Barcode
    
        End Function
    
    
    
    
    End Module

    unfortunately considering using DLL instead will change about half of my work so i wont be able to apply it

    btw you can check your code by simply use mobile app for Barcode OR QR scanner and you can test it easily from the screen directly, just display the code on textbox or label and scan it with your phone and compare the numbers on your mobile with the number you used as barcode.


    • Edited by AbanoubZak Friday, August 2, 2019 1:15 AM
    Friday, August 2, 2019 1:13 AM

  • btw you can check your code by simply use mobile app for Barcode OR QR scanner and you can test it easily from the screen directly, just display the code on textbox or label and scan it with your phone and compare the numbers on your mobile with the number you used as barcode.


    Hi

    Thanks for info. However, I do not own a mobile phone - just an old landline phone.

    There is example code HERE that doesn't use a Library, only a true type font.


    Regards Les, Livingston, Scotland


    • Edited by leshay Friday, August 2, 2019 10:35 AM
    Friday, August 2, 2019 10:30 AM
  • The code it self will work for the Barcode using code128 font with any text between two(*) will do the job perfectly However, i'm not sure about the printer side as i tried that drawing code before but the quality of the image was not good enough for the scanner to recognize it.
    Friday, August 2, 2019 5:59 PM
  • Hi

    As I mentioned I do not own a printer. However, using the XPS printer for Preview and for Print to file, both do have very high resolution (I can see that from the quality of high xooming factor - no sign of jagged edges anywhere). So, I would say the quality of a paper printout should be high.

    In as much as I can only make an educated guess at the quality of the paper printout, you, having a printer and don't actualy try the code and make a printout are guessing from other code that it will be poor quality.

    The ONLY way to be sure is that you try the code and actually make a print out to see.


    Regards Les, Livingston, Scotland

    Friday, August 2, 2019 6:09 PM

  • The ONLY way to be sure is that you try the code and actually make a print out to see.



    I agree with you,I will try the printing code and submit the result in the Forum.
    • Edited by AbanoubZak Friday, August 2, 2019 8:44 PM
    Friday, August 2, 2019 8:41 PM