Including Encryption / Decryption within CSLA

Including Encryption / Decryption within CSLA

Old forum URL: forums.lhotka.net/forums/t/9780.aspx


AKaplan posted on Thursday, November 18, 2010

I'm trying to include this RSA Encryption Class within the CSLA BusinessBase GetProperty and SetProperty. I'm having a hard time rewriting the encrypt / decrypt methods to accept the generic P type values for parameters. Can anyone point me in the right direction of where to start?

My problem lies where newValue is of a generic P type and it needs to go into a String parameter.

Below is example of what I'm trying to do.

Protected Function GetProperty(ByVal propertyInfo As IPropertyInfo, Optional ByVal extendedproperty As Boolean = False, Optional ByVal decrypt As Boolean = False) As Object

            Dim result As Object = Nothing

            If _bypassPropertyChecks OrElse CanReadProperty(propertyInfo.Name, False) Then

                Dim info = FieldManager.GetFieldData(propertyInfo)

                If info IsNot Nothing Then

                    result = info.Value

                End If

            Else

                result = propertyInfo.DefaultValue

            End If

            If extendedproperty = True Then

                result = ExtendedAttribute.GetExtendedAttribute(FieldManager.GetFieldData(propertyInfo).Name)

            End If

            If decrypt = True Then

                Dim data = Convert.FromBase64String(CStr(result))

                Dim AEU As New AsymmetricEncryptionUtility

                result = AEU.Decrypt(data, ConfigurationManager.AppSettings("RSA.AsymmetricalKey"))

            End If

            Return result

        End Function

 

Protected Sub SetProperty(Of P)(ByVal propertyInfo As PropertyInfo(Of P), ByVal newValue As P, ByVal noAccess As Security.NoAccessBehavior, Optional ByVal extendedProperty As Boolean = False, Optional ByVal encrypt As Boolean = False)

 

            If _bypassPropertyChecks OrElse CanWriteProperty(propertyInfo.Name, noAccess = Security.NoAccessBehavior.ThrowException) Then

                Try

                    Dim oldValue As P = Nothing

                    Dim fieldData = FieldManager.GetFieldData(propertyInfo)

                    If fieldData Is Nothing Then

                        oldValue = propertyInfo.DefaultValue

                        fieldData = FieldManager.LoadFieldData(Of P)(propertyInfo, oldValue)

 

                    Else

                        Dim fd = TryCast(fieldData, FieldManager.IFieldData(Of P))

                        If fd IsNot Nothing Then

                            oldValue = fd.Value

 

                        Else

                            oldValue = DirectCast(fieldData.Value, P)

                        End If

                    End If

 

                    If GetType(P) Is GetType(String) AndAlso newValue Is Nothing Then

                        newValue = CoerceValue(Of P)(GetType(String), Nothing, String.Empty)

                    End If

                    If extendedProperty = True Then

                        ExtendedAttribute.SetExtendedAttribute(propertyInfo.Name, newValue.ToString)

                    End If

                    If encrypt = True Then

                        Dim key = ConfigurationManager.AppSettings("RSA.SymmetricalKey")

                        Dim AEU As New AsymmetricEncryptionUtility

                        newValue = AEU.Encrypt(newValue.ToString, key)

                        LoadPropertyValue(Of P)(propertyInfo, oldValue, newValue, Not _bypassPropertyChecks)

                    End If

                    LoadPropertyValue(Of P)(propertyInfo, oldValue, newValue, Not _bypassPropertyChecks)

 

                Catch ex As Exception

                    Throw New PropertyLoadException(String.Format(My.Resources.PropertyLoadException, propertyInfo.Name, ex.Message))

                End Try

            End If

        End Sub

 

Public Function Encrypt(ByVal data As String, Optional ByVal key As String = Nothing) As String

            PublicKeyPath = key

            If data Is Nothing Then

                Return String.Empty

            End If

            If rsaPublic Is Nothing Then

                rsaPublic = New RSACryptoServiceProvider

            End If

            rsaPublic.FromXmlString(GetTextFileAsString(m_publicKeyPath))

            Dim keySizeInBytes As Integer = CInt(rsaPublic.KeySize / 8)

            Dim blockSize As Integer = keySizeInBytes - 11

            Dim iterations As Integer = 0

            If data.Length Mod blockSize <> 0 Then

                iterations = CInt((CInt(data.Length) / blockSize) + 1)

            Else

                iterations = CInt(CInt(data.Length) / blockSize)

            End If

            Dim allEncryptedBytes As Byte() = New Byte(iterations * keySizeInBytes - 1) {}

            Dim dataToEncryptAsChars As Char() = data.ToCharArray()

            Dim index As Integer = 0

            Dim counter As Integer = 0

            While counter < iterations

                Dim doneSoFar As Integer = counter * blockSize

                Dim endIndex As Integer = 0

                'if 1st iteration and data smaller than block 

                If counter = 0 AndAlso dataToEncryptAsChars.Length < blockSize Then

                    endIndex = dataToEncryptAsChars.Length

                Else

                    'final block 

                    If counter = iterations - 1 Then

                        endIndex = dataToEncryptAsChars.Length Mod blockSize

                    Else

                        endIndex = blockSize

                    End If

                End If

                Dim buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(dataToEncryptAsChars, index, endIndex)

                Dim encryptedBytes As Byte() = rsaPublic.Encrypt(buffer, False)

                Array.Copy(encryptedBytes, 0, allEncryptedBytes, counter * keySizeInBytes, keySizeInBytes)

                index += blockSize

                counter += 1

            End While

            Return Convert.ToBase64String(allEncryptedBytes)

        End Function

 

Public Function Decrypt(ByVal data As Byte(), Optional ByVal key As String = Nothing) As String

            PrivateKeyPath = key

            If rsaPrivate Is Nothing Then

                rsaPrivate = New RSACryptoServiceProvider

            End If

            rsaPrivate.FromXmlString(GetTextFileAsString(m_privateKeyPath))

            Dim KeySizeInBytes As Integer = CInt(rsaPublic.KeySize / 8)

            Dim blockSize As Integer = KeySizeInBytes - 11

            Dim iterations As Integer = 0

            Dim datatoDecryptBuffer As Byte() = data

            If datatoDecryptBuffer.Length Mod KeySizeInBytes <> 0 Then

                Throw New ApplicationException("Malformed data to decrypt")

            End If

            iterations = CInt(datatoDecryptBuffer.Length / KeySizeInBytes)

            Dim counter As Integer = 0

            Dim q As New Queue

            While counter < iterations

 

                Dim donesofar As Integer = counter * KeySizeInBytes

                Dim buffer As Byte() = New Byte(KeySizeInBytes - 1) {}

                Array.Copy(datatoDecryptBuffer, counter * KeySizeInBytes, buffer, 0, KeySizeInBytes)

                Dim decryptedbytes As Byte() = rsaPrivate.Decrypt(buffer, False)

                q.Enqueue(decryptedbytes)

                counter += 1

            End While

 

            Dim bytecount As Integer = 0

            For Each b As Byte() In q

                bytecount += b.Length

            Next b

 

            Dim alldecryptedbytes As Byte() = New Byte(bytecount - 1) {}

            counter = 0

            For Each b As Byte() In q

                If counter = iterations - 1 Then

                    Array.Copy(b, 0, alldecryptedbytes, alldecryptedbytes.Length - b.Length, b.Length)

                Else

                    Array.Copy(b, 0, alldecryptedbytes, counter * blockSize, blockSize)

                End If

                counter += 1

 

            Next b

            Return ASCIIEncoding.ASCII.GetString(alldecryptedbytes)

        End Function

Copyright (c) Marimer LLC