Quantcast
Channel: Web Forms
Viewing all articles
Browse latest Browse all 23244

How to Encrypt and decrypt text file connection string

$
0
0
Imports System
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography

Namespace APress.ProAspNet.Utility
    Public NotInheritable Class AsymmetricEncryptionUtility
        Private Sub New()
        End Sub
        Public Shared Function GenerateKey(ByVal targetFile As String) As String
            Dim Algorithm As New RSACryptoServiceProvider()

            ' Save the private key
            Dim CompleteKey As String = Algorithm.ToXmlString(True)
            Dim KeyBytes As Byte() = Encoding.UTF8.GetBytes(CompleteKey)

            KeyBytes = ProtectedData.Protect(KeyBytes, Nothing, DataProtectionScope.LocalMachine)

            Using fs As New FileStream(targetFile, FileMode.Create)
                fs.Write(KeyBytes, 0, KeyBytes.Length)
            End Using

            ' Return the public key
            Return Algorithm.ToXmlString(False)
        End Function

        Private Shared Sub ReadKey(ByVal algorithm As RSACryptoServiceProvider, ByVal keyFile As String)
            Dim KeyBytes As Byte()

            Using fs As New FileStream(keyFile, FileMode.Open)
                KeyBytes = New Byte(fs.Length - 1) {}
                fs.Read(KeyBytes, 0, CInt(fs.Length))
            End Using

            KeyBytes = ProtectedData.Unprotect(KeyBytes, Nothing, DataProtectionScope.LocalMachine)

            algorithm.FromXmlString(Encoding.UTF8.GetString(KeyBytes))
        End Sub

        Public Shared Function EncryptData(ByVal data As String, ByVal publicKey As String) As Byte()
            ' Create the algorithm based on the key
            Dim Algorithm As New RSACryptoServiceProvider()
            Algorithm.FromXmlString(publicKey)

            ' Now encrypt the data
            Return Algorithm.Encrypt(Encoding.UTF8.GetBytes(data), True)
        End Function

        Public Shared Function DecryptData(ByVal data As Byte(), ByVal keyFile As String) As String
            Dim Algorithm As New RSACryptoServiceProvider()
            ReadKey(Algorithm, keyFile)

            Dim ClearData As Byte() = Algorithm.Decrypt(data, True)
            Return Convert.ToString(Encoding.UTF8.GetString(ClearData))
        End Function
    End Class
End Namespace

my imports :

Imports System
imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.Win32
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Imports Microsoft.VisualBasic

SHOW Error In :

 KeyBytes=ProtectedData.Protect(KeyBytes,Nothing,DataProtectionScope.LocalMachine)

Protecteddata undefined -> show Errorline 




Viewing all articles
Browse latest Browse all 23244

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>