Hi,
I want to encrypt my web config when i deploy it to server so that the username and password of database is secured. I've tried some of the encryption and it did'nt work. here is my code.
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration
Imports System.Security.Cryptography
Imports System.IO
Public Class EnDec
'namespace MassClosing
'{
Private Const PREFIX As String = "^ENC^"
'private static byte[] _salt = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings.Get("EncryptionKey"));
Private Shared _salt As Byte() = Encoding.ASCII.GetBytes("13375sT33l0r4n93)")
Public Function GetPassword(ByVal configAppSettingsKey As String) As String
Dim retVal As String = String.Empty
'bool isEncrypted = false;
Dim keyValue As String = ConfigurationManager.AppSettings.[Get](configAppSettingsKey)
Dim encryptedPassword As String = String.Empty
Dim decryptedPassword As String = String.Empty
If keyValue.StartsWith(PREFIX) Then
'isEncrypted = true;
'decrypt the password
decryptedPassword = DecryptStringAES(keyValue.Replace(PREFIX, ""), ConfigurationManager.AppSettings.[Get]("EncryptionKey"))
retVal = decryptedPassword
Else
'if encrypted
'not encrypted
'isEncrypted = false;
'encrypt the password
encryptedPassword = PREFIX & EncryptStringAES(keyValue, ConfigurationManager.AppSettings.[Get]("EncryptionKey"))
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
config.AppSettings.Settings(configAppSettingsKey).Value = encryptedPassword
'config.Save(ConfigurationSaveMode.Modified);
config.Save()
ConfigurationManager.RefreshSection("appSettings")
'ConfigurationManager.AppSettings.Set(configAppSettingsKey, encryptedPassword);
retVal = keyValue
End If
'else not encrypted
Return retVal
End Function
'GetPassword
Public Function EncryptStringAES(ByVal plainText As String, ByVal encryptionKey As String) As String
If String.IsNullOrEmpty(plainText) Then
Throw New ArgumentNullException("plainText")
End If
If String.IsNullOrEmpty(encryptionKey) Then
Throw New ArgumentNullException("encryptionKey")
End If
Dim outStr As String = Nothing
' Encrypted string to return
Dim aesAlg As RijndaelManaged = Nothing
' RijndaelManaged object used to encrypt the data.
Try
' generate the key from the shared secret and the salt
Dim key As New Rfc2898DeriveBytes(encryptionKey, _salt)
' Create a RijndaelManaged object
aesAlg = New RijndaelManaged()
aesAlg.Key = key.GetBytes(aesAlg.KeySize \ 8)
' Create a decrytor to perform the stream transform.
Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)
' Create the streams used for encryption.
Using msEncrypt As New MemoryStream()
' prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, 4)
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length)
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
End Using
outStr = Convert.ToBase64String(msEncrypt.ToArray())
End Using
Finally
' Clear the RijndaelManaged object.
If aesAlg IsNot Nothing Then
aesAlg.Clear()
End If
End Try
' Return the encrypted bytes from the memory stream.
Return outStr
End Function
'EncryptStringAES
Public Function DecryptStringAES(ByVal cipherText As String, ByVal encryptionKey As String) As String
If String.IsNullOrEmpty(cipherText) Then
Throw New ArgumentNullException("cipherText")
End If
If String.IsNullOrEmpty(encryptionKey) Then
Throw New ArgumentNullException("encryptionKey")
End If
' Declare the RijndaelManaged object
' used to decrypt the data.
Dim aesAlg As RijndaelManaged = Nothing
' Declare the string used to hold
' the decrypted text.
Dim plaintext As String = Nothing
Try
' generate the key from the shared secret and the salt
Dim key As New Rfc2898DeriveBytes(encryptionKey, _salt)
' Create the streams used for decryption.
Dim bytes As Byte() = Convert.FromBase64String(cipherText)
Using msDecrypt As New MemoryStream(bytes)
' Create a RijndaelManaged object
' with the specified key and IV.
aesAlg = New RijndaelManaged()
aesAlg.Key = key.GetBytes(aesAlg.KeySize \ 8)
' Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt)
' Create a decrytor to perform the stream transform.
Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)
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
Finally
' Clear the RijndaelManaged object.
If aesAlg IsNot Nothing Then
aesAlg.Clear()
End If
End Try
Return plaintext
End Function
'DecryptStringAES
Private Shared Function ReadByteArray(ByVal s As Stream) As Byte()
Dim rawLength As Byte() = New Byte(4 - 1) {}
If s.Read(rawLength, 0, rawLength.Length) <> rawLength.Length Then
Throw New SystemException("Stream did not contain properly formatted byte array")
End If
Dim buffer As Byte() = New Byte(BitConverter.ToInt32(rawLength, 0) - 1) {}
If s.Read(buffer, 0, buffer.Length) <> buffer.Length Then
Throw New SystemException("Did not read byte array properly")
End If
Return buffer
End Function
'ReadByteArray
End Class
'class
Imports System.Configuration
Imports System.IO
Imports System.Data.OracleClient
Public Class iSIMSDAL
Public Sub ConnectDB(ByRef OraConn As OracleConnection)
Try
Dim strDB As String
Dim EncDec As New EnDec
Dim strPwd As String
Try
strPwd = EncDec.GetPassword("OraPassword")
Catch ex As Exception
LogFile(Format(Date.Now, "MMddyyyyHHmmss") & "GetPassword ERROR: " & ex.ToString)
End Try
strDB = ConfigurationManager.AppSettings("OraConn")
OraConn.ConnectionString = strDB
OraConn.Open()
Catch ex As Exception
LogFile(Format(Date.Now, "MMddyyyyHHmmss") & "<ConnectDB> ERROR: " & ex.ToString)
End Try
End Sub
Public Sub DisconnectDB(ByRef OraConn As OracleConnection)
Try
OraConn.Close()
OraConn.Dispose()
Catch ex As Exception
LogFile(Format(Date.Now, "MMddyyyyHHmmss") & "<DisconnectDB> ERROR: " & ex.ToString)
Finally
OraConn = Nothing
End Try
End Sub
Public Function LogFile(ByVal sValue As String) As String
Try
Dim file_name As String = ConfigurationManager.AppSettings("AppPath") & "Logs\LogRep_" & Format(Date.Now, "MMddyyyy") & ".txt"
Dim stream_writer As New StreamWriter(file_name, True)
stream_writer.WriteLine(sValue)
stream_writer.Close()
Catch ex As Exception
End Try
Return Nothing
End Function
End Class
thanks in advance.