Creating repo

This commit is contained in:
Jorge Burgos 2025-01-28 15:08:50 -05:00
commit 7020042aa0
29 changed files with 2018 additions and 0 deletions

View File

@ -0,0 +1,9 @@
Namespace Encryptors
Public Interface IPasswordEncryptionMethod
Function Encode(ByVal username As String, ByVal anOrgPin As String, ByVal aNewPassword As String, ByVal aUserGUID As Guid, aSalt As String) As String
End Interface
End Namespace

View File

@ -0,0 +1,49 @@
Imports System.Configuration
Imports Strata.Configuration.Client.Models.Jazz
Namespace Encryptors
Public Class UberEncryptionMethod
Implements IPasswordEncryptionMethod
Friend Sub New()
End Sub
#Region " Methods "
Public Shared Function GetUberMonet(ByVal anOrgPin As String) As String
Return GetUberMonet(Date.Today, anOrgPin, ConfigurationManager.AppSettings(NameOf(StrataJazzOptions.UberMonetKey)))
End Function
Private Shared Function GetUberMonet(ByVal aDate As Date, ByVal anOrgPIN As String, ByVal aKey As String) As String
Dim ha As New EncryptionUtils.Hasher(EncryptionUtils.Hasher.Provider.SHA1)
Dim lsHashBefore As String
Dim lsResult As String
lsHashBefore = Format(aDate, "dd-MM-yyyy") & "-" & anOrgPIN & "-" & aKey
Dim d As New EncryptionUtils.Data(lsHashBefore)
Dim dResult As EncryptionUtils.Data = ha.Calculate(d)
lsResult = Left(dResult.Hex, 6)
ha = Nothing
Return lsResult
End Function
#End Region
#Region " IPasswordEncryptionMethod "
Private Function Encode(ByVal username As String, ByVal anOrgPin As String, ByVal aNewPassword As String, ByVal aUserGUID As System.Guid, aSalt As String) As String Implements IPasswordEncryptionMethod.Encode
Return GetUberMonet(anOrgPin)
End Function
#End Region
End Class
End Namespace

View File

@ -0,0 +1,47 @@
Imports System.Configuration
Imports System.Security.Cryptography
Imports System.Text
Imports Strata.Configuration.Client.Models.Jazz
Namespace Encryptors
Public Class UserGUIDEncryptionMethod
Implements IPasswordEncryptionMethod
#Region " Declarations "
Private Const NUMBER_ITERATIONS As Integer = 100000
#End Region
#Region " Methods "
Public Function Encode(ByVal username As String, ByVal anOrgPin As String, ByVal aNewPassword As String, ByVal aUserGUID As System.Guid, aSalt As String) As String Implements IPasswordEncryptionMethod.Encode
Dim salt As String = aUserGUID.ToString & ConfigurationManager.AppSettings(NameOf(StrataJazzOptions.UserGuidEncryptionKey))
Dim result As String = GetHashedValue(aNewPassword, salt)
For i As Integer = 1 To NUMBER_ITERATIONS
result = GetHashedValue(result)
Next
Return result
End Function
Private Shared Function GetHashedValue(ByVal aValue As String) As String
'Create an instance of the sha encrypter
Using hasher As New SHA1Managed
Return Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(aValue)))
End Using
End Function
Private Shared Function GetHashedValue(ByVal aValue As String, ByVal aSalt As String) As String
Return GetHashedValue(aValue & aSalt)
End Function
#End Region
End Class
End Namespace

View File

@ -0,0 +1,34 @@
Imports System.Configuration
Imports System.Security.Cryptography
Imports System.Text
Imports Strata.Configuration.Client.Models.Jazz
Namespace Encryptors
Public Class UserSaltEncryptionMethod
Implements IPasswordEncryptionMethod
#Region " Declarations "
Private Const NUMBER_ITERATIONS As Integer = 100000
#End Region
#Region " Methods "
Public Function Encode(ByVal username As String, ByVal anOrgPin As String, ByVal aNewPassword As String, ByVal aUserGUID As System.Guid, aSalt As String) As String Implements IPasswordEncryptionMethod.Encode
Dim saltAndPepper As String = aSalt & ConfigurationManager.AppSettings(NameOf(StrataJazzOptions.UserSaltEncryptionKey))
Using deriveBytes As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(aNewPassword, Encoding.UTF8.GetBytes(saltAndPepper), NUMBER_ITERATIONS)
Dim password As Byte() = deriveBytes.GetBytes(24)
Return Convert.ToBase64String(password)
End Using
End Function
#End Region
End Class
End Namespace

View File

@ -0,0 +1,6 @@
Friend Class InternalConstants
'WARNING: This should always match the value in Strata.Base.Constants.XConstants.APPLICATION_VERSION
Public Const APPLICATION_VERSION As String = "2025.11"
End Class

View File

@ -0,0 +1,13 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>false</MySubMain>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<ApplicationType>1</ApplicationType>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>

View File

@ -0,0 +1,36 @@
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("Strata.Biz.Internal")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Strata Decision Technology, LLC")>
<Assembly: AssemblyProduct("Strata.Biz.Internal")>
<Assembly: AssemblyCopyright("© 2006-2012 Strata Decision Technology, LLC")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("dfd98904-a580-4549-90ea-95c9a5504029")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion(Strata.Base.Constants.XConstants.APPLICATION_VERSION)>
<Assembly: AssemblyVersion(InternalConstants.APPLICATION_VERSION)>
<Assembly: AssemblyFileVersion(InternalConstants.APPLICATION_VERSION)>

View File

@ -0,0 +1,63 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Imports System
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Strata.Base.Internal.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,82 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.12.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
<Global.System.Configuration.ApplicationScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("Development")> _
Public ReadOnly Property Environment() As String
Get
Return CType(Me("Environment"),String)
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.Strata.Base.Internal.My.MySettings
Get
Return Global.Strata.Base.Internal.My.MySettings.Default
End Get
End Property
End Module
End Namespace

View File

@ -0,0 +1,9 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="My" GeneratedClassName="MySettings" UseMySettingsClassName="true">
<Profiles />
<Settings>
<Setting Name="Environment" Type="System.String" Scope="Application">
<Value Profile="(Default)">Development</Value>
</Setting>
</Settings>
</SettingsFile>

View File

@ -0,0 +1,719 @@
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Namespace EncryptionUtils
#Region " Hash "
''' <summary>
''' Hash functions are fundamental to modern cryptography. These functions map binary
''' strings of an arbitrary length to small binary strings of a fixed length, known as
''' hash values. A cryptographic hash function has the property that it is computationally
''' infeasible to find two distinct inputs that hash to the same value. Hash functions
''' are commonly used with digital signatures and for data integrity.
''' </summary>
Friend Class Hasher
''' <summary>
''' Type of hash; some are security oriented, others are fast and simple
''' </summary>
Friend Enum Provider
''' <summary>
''' Secure Hashing Algorithm provider, SHA-1 variant, 160-bit
''' </summary>
SHA1
''' <summary>
''' Secure Hashing Algorithm provider, SHA-2 variant, 256-bit
''' </summary>
SHA256
''' <summary>
''' Secure Hashing Algorithm provider, SHA-2 variant, 384-bit
''' </summary>
SHA384
''' <summary>
''' Secure Hashing Algorithm provider, SHA-2 variant, 512-bit
''' </summary>
SHA512
''' <summary>
''' Message Digest algorithm 5, 128-bit
''' </summary>
MD5
End Enum
Private _Hash As HashAlgorithm
Private _HashValue As New Data
Private Sub New()
End Sub
''' <summary>
''' Instantiate a new hash of the specified type
''' </summary>
Friend Sub New(ByVal p As Provider)
Select Case p
Case Provider.MD5
_Hash = New MD5CryptoServiceProvider
Case Provider.SHA1
_Hash = New SHA1Managed
Case Provider.SHA256
_Hash = New SHA256Managed
Case Provider.SHA384
_Hash = New SHA384Managed
Case Provider.SHA512
_Hash = New SHA512Managed
End Select
End Sub
''' <summary>
''' Returns the previously calculated hash
''' </summary>
Friend ReadOnly Property Value() As Data
Get
Return _HashValue
End Get
End Property
''' <summary>
''' Calculates hash on a stream of arbitrary length
''' </summary>
Friend Function Calculate(ByRef s As System.IO.Stream) As Data
_HashValue.Bytes = _Hash.ComputeHash(s)
Return _HashValue
End Function
''' <summary>
''' Calculates hash for fixed length <see cref="Data"/>
''' </summary>
Friend Function Calculate(ByVal d As Data) As Data
Return CalculatePrivate(d.Bytes)
End Function
''' <summary>
''' Calculates hash for a string with a prefixed salt value.
''' A "salt" is random data prefixed to every hashed value to prevent
''' common dictionary attacks.
''' </summary>
Friend Function Calculate(ByVal d As Data, ByVal salt As Data) As Data
Dim nb(d.Bytes.Length + salt.Bytes.Length - 1) As Byte
salt.Bytes.CopyTo(nb, 0)
d.Bytes.CopyTo(nb, salt.Bytes.Length)
Return CalculatePrivate(nb)
End Function
''' <summary>
''' Calculates hash for an array of bytes
''' </summary>
Private Function CalculatePrivate(ByVal b() As Byte) As Data
_HashValue.Bytes = _Hash.ComputeHash(b)
Return _HashValue
End Function
End Class
#End Region
#Region " Symmetric "
''' <summary>
''' Symmetric encryption uses a single key to encrypt and decrypt.
''' Both parties (encryptor and decryptor) must share the same secret key.
''' </summary>
Friend Class SymmetricEncryptor
Private Const _DefaultIntializationVector As String = "%1Az=-@qT"
Private Const _BufferSize As Integer = 2048
Friend Enum Provider
''' <summary>
''' The Data Encryption Standard provider supports a 64 bit key only
''' </summary>
DES
''' <summary>
''' The Rivest Cipher 2 provider supports keys ranging from 40 to 128 bits, default is 128 bits
''' </summary>
RC2
''' <summary>
''' The Rijndael (also known as AES) provider supports keys of 128, 192, or 256 bits with a default of 256 bits
''' </summary>
Rijndael
''' <summary>
''' The TripleDES provider (also known as 3DES) supports keys of 128 or 192 bits with a default of 192 bits
''' </summary>
TripleDES
End Enum
Private _data As Data
Private _key As Data
Private _iv As Data
Private _crypto As SymmetricAlgorithm
Private _EncryptedBytes As Byte()
Private _UseDefaultInitializationVector As Boolean
Private Sub New()
End Sub
''' <summary>
''' Instantiates a new symmetric encryption object using the specified provider.
''' </summary>
Friend Sub New(ByVal provider As Provider, Optional ByVal useDefaultInitializationVector As Boolean = True)
Select Case provider
Case Provider.DES
_crypto = New DESCryptoServiceProvider
Case Provider.RC2
_crypto = New RC2CryptoServiceProvider
Case Provider.Rijndael
_crypto = New RijndaelManaged
Case Provider.TripleDES
_crypto = New TripleDESCryptoServiceProvider
End Select
'-- make sure key and IV are always set, no matter what
Me.Key = RandomKey()
If useDefaultInitializationVector Then
Me.IntializationVector = New Data(_DefaultIntializationVector)
Else
Me.IntializationVector = RandomInitializationVector()
End If
End Sub
''' <summary>
''' Key size in bytes. We use the default key size for any given provider; if you
''' want to force a specific key size, set this property
''' </summary>
Friend Property KeySizeBytes() As Integer
Get
Return _crypto.KeySize \ 8
End Get
Set(ByVal Value As Integer)
_crypto.KeySize = Value * 8
_key.MaxBytes = Value
End Set
End Property
''' <summary>
''' Key size in bits. We use the default key size for any given provider; if you
''' want to force a specific key size, set this property
''' </summary>
Friend Property KeySizeBits() As Integer
Get
Return _crypto.KeySize
End Get
Set(ByVal Value As Integer)
_crypto.KeySize = Value
_key.MaxBits = Value
End Set
End Property
''' <summary>
''' The key used to encrypt/decrypt data
''' </summary>
Friend Property Key() As Data
Get
Return _key
End Get
Set(ByVal Value As Data)
_key = Value
_key.MaxBytes = _crypto.LegalKeySizes(0).MaxSize \ 8
_key.MinBytes = _crypto.LegalKeySizes(0).MinSize \ 8
_key.StepBytes = _crypto.LegalKeySizes(0).SkipSize \ 8
End Set
End Property
''' <summary>
''' Using the default Cipher Block Chaining (CBC) mode, all data blocks are processed using
''' the value derived from the previous block; the first data block has no previous data block
''' to use, so it needs an InitializationVector to feed the first block
''' </summary>
Friend Property IntializationVector() As Data
Get
Return _iv
End Get
Set(ByVal Value As Data)
_iv = Value
_iv.MaxBytes = _crypto.BlockSize \ 8
_iv.MinBytes = _crypto.BlockSize \ 8
End Set
End Property
''' <summary>
''' generates a random Initialization Vector, if one was not provided
''' </summary>
Friend Function RandomInitializationVector() As Data
_crypto.GenerateIV()
Dim d As New Data(_crypto.IV)
Return d
End Function
''' <summary>
''' generates a random Key, if one was not provided
''' </summary>
Friend Function RandomKey() As Data
_crypto.GenerateKey()
Dim d As New Data(_crypto.Key)
Return d
End Function
''' <summary>
''' Ensures that _crypto object has valid Key and IV
''' prior to any attempt to encrypt/decrypt anything
''' </summary>
Private Sub ValidateKeyAndIv(ByVal isEncrypting As Boolean)
If _key.IsEmpty Then
If isEncrypting Then
_key = RandomKey()
Else
Throw New CryptographicException("No key was provided for the decryption operation!")
End If
End If
If _iv.IsEmpty Then
If isEncrypting Then
_iv = RandomInitializationVector()
Else
Throw New CryptographicException("No initialization vector was provided for the decryption operation!")
End If
End If
_crypto.Key = _key.Bytes
_crypto.IV = _iv.Bytes
End Sub
''' <summary>
''' Encrypts the specified Data using provided key
''' </summary>
Friend Function Encrypt(ByVal d As Data, ByVal key As Data) As Data
Me.Key = key
Return Encrypt(d)
End Function
''' <summary>
''' Encrypts the specified Data using preset key and preset initialization vector
''' </summary>
Friend Function Encrypt(ByVal d As Data) As Data
Dim ms As New IO.MemoryStream
ValidateKeyAndIv(True)
Dim cs As New CryptoStream(ms, _crypto.CreateEncryptor(), CryptoStreamMode.Write)
cs.Write(d.Bytes, 0, d.Bytes.Length)
cs.Close()
ms.Close()
Return New Data(ms.ToArray)
End Function
''' <summary>
''' Encrypts the stream to memory using provided key and provided initialization vector
''' </summary>
Friend Function Encrypt(ByVal s As Stream, ByVal key As Data, ByVal iv As Data) As Data
Me.IntializationVector = iv
Me.Key = key
Return Encrypt(s)
End Function
''' <summary>
''' Encrypts the stream to memory using specified key
''' </summary>
Friend Function Encrypt(ByVal s As Stream, ByVal key As Data) As Data
Me.Key = key
Return Encrypt(s)
End Function
''' <summary>
''' Encrypts the specified stream to memory using preset key and preset initialization vector
''' </summary>
Friend Function Encrypt(ByVal s As Stream) As Data
Dim ms As New IO.MemoryStream
Dim b(_BufferSize) As Byte
Dim i As Integer
ValidateKeyAndIv(True)
Dim cs As New CryptoStream(ms, _crypto.CreateEncryptor(), CryptoStreamMode.Write)
i = s.Read(b, 0, _BufferSize)
Do While i > 0
cs.Write(b, 0, i)
i = s.Read(b, 0, _BufferSize)
Loop
cs.Close()
ms.Close()
Return New Data(ms.ToArray)
End Function
''' <summary>
''' Decrypts the specified data using provided key and preset initialization vector
''' </summary>
Friend Function Decrypt(ByVal encryptedData As Data, ByVal key As Data) As Data
Me.Key = key
Return Decrypt(encryptedData)
End Function
''' <summary>
''' Decrypts the specified stream using provided key and preset initialization vector
''' </summary>
Friend Function Decrypt(ByVal encryptedStream As Stream, ByVal key As Data) As Data
Me.Key = key
Return Decrypt(encryptedStream)
End Function
''' <summary>
''' Decrypts the specified stream using preset key and preset initialization vector
''' </summary>
Friend Function Decrypt(ByVal encryptedStream As Stream) As Data
Dim ms As New System.IO.MemoryStream
Dim b(_BufferSize) As Byte
ValidateKeyAndIv(False)
Dim cs As New CryptoStream(encryptedStream,
_crypto.CreateDecryptor(), CryptoStreamMode.Read)
Dim i As Integer
i = cs.Read(b, 0, _BufferSize)
Do While i > 0
ms.Write(b, 0, i)
i = cs.Read(b, 0, _BufferSize)
Loop
cs.Close()
ms.Close()
Return New Data(ms.ToArray)
End Function
''' <summary>
''' Decrypts the specified data using preset key and preset initialization vector
''' </summary>
Friend Function Decrypt(ByVal encryptedData As Data) As Data
Dim ms As New System.IO.MemoryStream(encryptedData.Bytes, 0, encryptedData.Bytes.Length)
Dim b() As Byte = New Byte(encryptedData.Bytes.Length - 1) {}
ValidateKeyAndIv(False)
Dim cs As New CryptoStream(ms, _crypto.CreateDecryptor(), CryptoStreamMode.Read)
Try
cs.Read(b, 0, encryptedData.Bytes.Length - 1)
Catch ex As CryptographicException
Throw New CryptographicException("Unable to decrypt data. The provided key may be invalid.", ex)
Finally
cs.Close()
End Try
Return New Data(b)
End Function
End Class
#End Region
#Region " Data "
''' <summary>
''' represents Hex, Byte, Base64, or String data to encrypt/decrypt;
''' use the .Text property to set/get a string representation
''' use the .Hex property to set/get a string-based Hexadecimal representation
''' use the .Base64 to set/get a string-based Base64 representation
''' </summary>
Friend Class Data
Private _b As Byte() = Nothing
Private _MaxBytes As Integer = 0
Private _MinBytes As Integer = 0
Private _StepBytes As Integer = 0
''' <summary>
''' Determines the default text encoding across ALL Data instances
''' </summary>
Friend Shared DefaultEncoding As Text.Encoding = System.Text.Encoding.GetEncoding("Windows-1252")
''' <summary>
''' Determines the default text encoding for this Data instance
''' </summary>
Friend Encoding As Text.Encoding = DefaultEncoding
''' <summary>
''' Creates new, empty encryption data
''' </summary>
Friend Sub New()
End Sub
''' <summary>
''' Creates new encryption data with the specified byte array
''' </summary>
Friend Sub New(ByVal b As Byte())
_b = b
End Sub
''' <summary>
''' Creates new encryption data with the specified string;
''' will be converted to byte array using default encoding
''' </summary>
Friend Sub New(ByVal s As String)
Me.Text = s
End Sub
''' <summary>
''' Creates new encryption data using the specified string and the
''' specified encoding to convert the string to a byte array.
''' </summary>
Friend Sub New(ByVal s As String, ByVal encoding As System.Text.Encoding)
Me.Encoding = encoding
Me.Text = s
End Sub
''' <summary>
''' returns true if no data is present
''' </summary>
Friend ReadOnly Property IsEmpty() As Boolean
Get
If _b Is Nothing Then
Return True
End If
If _b.Length = 0 Then
Return True
End If
Return False
End Get
End Property
''' <summary>
''' allowed step interval, in bytes, for this data; if 0, no limit
''' </summary>
Friend Property StepBytes() As Integer
Get
Return _StepBytes
End Get
Set(ByVal Value As Integer)
_StepBytes = Value
End Set
End Property
''' <summary>
''' allowed step interval, in bits, for this data; if 0, no limit
''' </summary>
Friend Property StepBits() As Integer
Get
Return _StepBytes * 8
End Get
Set(ByVal Value As Integer)
_StepBytes = Value \ 8
End Set
End Property
''' <summary>
''' minimum number of bytes allowed for this data; if 0, no limit
''' </summary>
Friend Property MinBytes() As Integer
Get
Return _MinBytes
End Get
Set(ByVal Value As Integer)
_MinBytes = Value
End Set
End Property
''' <summary>
''' minimum number of bits allowed for this data; if 0, no limit
''' </summary>
Friend Property MinBits() As Integer
Get
Return _MinBytes * 8
End Get
Set(ByVal Value As Integer)
_MinBytes = Value \ 8
End Set
End Property
''' <summary>
''' maximum number of bytes allowed for this data; if 0, no limit
''' </summary>
Friend Property MaxBytes() As Integer
Get
Return _MaxBytes
End Get
Set(ByVal Value As Integer)
_MaxBytes = Value
End Set
End Property
''' <summary>
''' maximum number of bits allowed for this data; if 0, no limit
''' </summary>
Friend Property MaxBits() As Integer
Get
Return _MaxBytes * 8
End Get
Set(ByVal Value As Integer)
_MaxBytes = Value \ 8
End Set
End Property
''' <summary>
''' Returns the byte representation of the data;
''' This will be padded to MinBytes and trimmed to MaxBytes as necessary!
''' </summary>
Friend Property Bytes() As Byte()
Get
If _MaxBytes > 0 Then
If _b.Length > _MaxBytes Then
Dim b(_MaxBytes - 1) As Byte
Array.Copy(_b, b, b.Length)
_b = b
End If
End If
If _MinBytes > 0 Then
If _b.Length < _MinBytes Then
Dim b(_MinBytes - 1) As Byte
Array.Copy(_b, b, _b.Length)
_b = b
End If
End If
Return _b
End Get
Set(ByVal Value As Byte())
_b = Value
End Set
End Property
''' <summary>
''' Sets or returns text representation of bytes using the default text encoding
''' </summary>
Friend Property Text() As String
Get
If _b Is Nothing Then
Return ""
Else
'-- need to handle nulls here; oddly, C# will happily convert
'-- nulls into the string whereas VB stops converting at the
'-- first null!
Dim i As Integer = Array.IndexOf(_b, CType(0, Byte))
If i >= 0 Then
Return Me.Encoding.GetString(_b, 0, i)
Else
Return Me.Encoding.GetString(_b)
End If
End If
End Get
Set(ByVal Value As String)
_b = Me.Encoding.GetBytes(Value)
End Set
End Property
''' <summary>
''' Sets or returns Hex string representation of this data
''' </summary>
Friend Property Hex() As String
Get
Return Utils.ToHex(_b)
End Get
Set(ByVal Value As String)
_b = Utils.FromHex(Value)
End Set
End Property
''' <summary>
''' Sets or returns Base64 string representation of this data
''' </summary>
Friend Property Base64() As String
Get
Return Utils.ToBase64(_b)
End Get
Set(ByVal Value As String)
_b = Utils.FromBase64(Value)
End Set
End Property
''' <summary>
''' Returns text representation of bytes using the default text encoding
''' </summary>
Friend Shadows Function ToString() As String
Return Me.Text
End Function
''' <summary>
''' returns Base64 string representation of this data
''' </summary>
Friend Function ToBase64() As String
Return Me.Base64
End Function
''' <summary>
''' returns Hex string representation of this data
''' </summary>
Friend Function ToHex() As String
Return Me.Hex
End Function
End Class
#End Region
#Region " Utils "
''' <summary>
''' Friend class for shared utility methods used by multiple Encryption classes
''' </summary>
Friend Class Utils
''' <summary>
''' converts an array of bytes to a string Hex representation
''' </summary>
Friend Shared Function ToHex(ByVal ba() As Byte) As String
If ba Is Nothing OrElse ba.Length = 0 Then
Return ""
End If
Const HexFormat As String = "{0:X2}"
Dim sb As New StringBuilder
For Each b As Byte In ba
sb.Append(String.Format(HexFormat, b))
Next
Return sb.ToString
End Function
''' <summary>
''' converts from a string Hex representation to an array of bytes
''' </summary>
Friend Shared Function FromHex(ByVal hexEncoded As String) As Byte()
If hexEncoded Is Nothing OrElse hexEncoded.Length = 0 Then
Return Nothing
End If
Try
Dim l As Integer = Convert.ToInt32(hexEncoded.Length / 2)
Dim b(l - 1) As Byte
For i As Integer = 0 To l - 1
b(i) = Convert.ToByte(hexEncoded.Substring(i * 2, 2), 16)
Next
Return b
Catch ex As Exception
Throw New System.FormatException("The provided string does not appear to be Hex encoded:" &
Environment.NewLine & hexEncoded & Environment.NewLine, ex)
End Try
End Function
''' <summary>
''' converts from a string Base64 representation to an array of bytes
''' </summary>
Friend Shared Function FromBase64(ByVal base64Encoded As String) As Byte()
If base64Encoded Is Nothing OrElse base64Encoded.Length = 0 Then
Return Nothing
End If
Try
Return Convert.FromBase64String(base64Encoded)
Catch ex As System.FormatException
Throw New System.FormatException("The provided string does not appear to be Base64 encoded:" &
Environment.NewLine & base64Encoded & Environment.NewLine, ex)
End Try
End Function
''' <summary>
''' converts from an array of bytes to a string Base64 representation
''' </summary>
Friend Shared Function ToBase64(ByVal b() As Byte) As String
If b Is Nothing OrElse b.Length = 0 Then
Return ""
End If
Return Convert.ToBase64String(b)
End Function
End Class
#End Region
End Namespace

View File

@ -0,0 +1,28 @@
Public Class SecurityUtils
#Region " Declarations "
Private Const ENCRYPTION_KEY_SUFFIX As String = "SDT"
#End Region
#Region " Methods "
Public Shared Function EncryptValue(value As String, key As String) As String
Dim encryption As New EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.Rijndael)
Return encryption.Encrypt(New EncryptionUtils.Data(value), New EncryptionUtils.Data(key & ENCRYPTION_KEY_SUFFIX)).ToBase64
End Function
Public Shared Function DecryptValue(encryptedValue As String, key As String) As String
Dim encryption As New EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.Rijndael)
' note EncryptValue returns Base64 string so we need to initialized encryptedData as Base64
Dim encryptedData As EncryptionUtils.Data = New EncryptionUtils.Data()
encryptedData.Base64 = encryptedValue
Return encryption.Decrypt(encryptedData, New EncryptionUtils.Data(key & ENCRYPTION_KEY_SUFFIX)).Text
End Function
#End Region
End Class

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="SonarQube - StrataJazz Sonar way" ToolsVersion="15.0">
<Include Path="..\..\.sonarlint\stratajazzvb.ruleset" Action="Default" />
</RuleSet>

View File

@ -0,0 +1,156 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{1B977903-2BD8-4D33-B9DD-88AAC972CD71}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>Strata.Base.Internal</RootNamespace>
<AssemblyName>Strata.Base.Internal</AssemblyName>
<MyType>Windows</MyType>
<SccProjectName>
</SccProjectName>
<SccLocalPath>
</SccLocalPath>
<SccAuxPath>
</SccAuxPath>
<SccProvider>
</SccProvider>
<OptionStrict>On</OptionStrict>
<SignAssembly>false</SignAssembly>
<AssemblyOriginatorKeyFile>
</AssemblyOriginatorKeyFile>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>Strata.Base.Internal.xml</DocumentationFile>
<NoWarn>42353,42354,42355</NoWarn>
<WarningsAsErrors>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036</WarningsAsErrors>
<RunCodeAnalysis>false</RunCodeAnalysis>
<CodeAnalysisRules>-Microsoft.Design#CA1012;-Microsoft.Design#CA2210;-Microsoft.Design#CA1040;-Microsoft.Design#CA1005;-Microsoft.Design#CA1020;-Microsoft.Design#CA1021;-Microsoft.Design#CA1010;-Microsoft.Design#CA1011;-Microsoft.Design#CA1009;-Microsoft.Design#CA1050;-Microsoft.Design#CA1026;-Microsoft.Design#CA1019;-Microsoft.Design#CA1031;-Microsoft.Design#CA1047;-Microsoft.Design#CA1000;-Microsoft.Design#CA1048;-Microsoft.Design#CA1051;-Microsoft.Design#CA1002;-Microsoft.Design#CA1061;-Microsoft.Design#CA1006;-Microsoft.Design#CA1046;-Microsoft.Design#CA1045;-Microsoft.Design#CA1065;-Microsoft.Design#CA1038;-Microsoft.Design#CA1008;-Microsoft.Design#CA1028;-Microsoft.Design#CA1064;-Microsoft.Design#CA1004;-Microsoft.Design#CA1035;-Microsoft.Design#CA1063;-Microsoft.Design#CA1032;-Microsoft.Design#CA1023;-Microsoft.Design#CA1033;-Microsoft.Design#CA1039;-Microsoft.Design#CA1016;-Microsoft.Design#CA1014;-Microsoft.Design#CA1017;-Microsoft.Design#CA1018;-Microsoft.Design#CA1027;-Microsoft.Design#CA1059;-Microsoft.Design#CA1060;-Microsoft.Design#CA1034;-Microsoft.Design#CA1013;-Microsoft.Design#CA1036;-Microsoft.Design#CA1044;-Microsoft.Design#CA1041;-Microsoft.Design#CA1025;-Microsoft.Design#CA1052;-Microsoft.Design#CA1053;-Microsoft.Design#CA1057;-Microsoft.Design#CA1058;-Microsoft.Design#CA1001;-Microsoft.Design#CA1049;-Microsoft.Design#CA1054;-Microsoft.Design#CA1056;-Microsoft.Design#CA1055;-Microsoft.Design#CA1030;-Microsoft.Design#CA1003;-Microsoft.Design#CA1007;-Microsoft.Design#CA1043;-Microsoft.Design#CA1024;-Microsoft.Globalization#CA1301;-Microsoft.Globalization#CA1302;-Microsoft.Globalization#CA1308;-Microsoft.Globalization#CA1306;-Microsoft.Globalization#CA1304;-Microsoft.Globalization#CA1305;-Microsoft.Globalization#CA2101;-Microsoft.Globalization#CA1300;-Microsoft.Globalization#CA1307;-Microsoft.Globalization#CA1309;-Microsoft.Interoperability#CA1403;-Microsoft.Interoperability#CA1406;-Microsoft.Interoperability#CA1413;-Microsoft.Interoperability#CA1402;-Microsoft.Interoperability#CA1407;-Microsoft.Interoperability#CA1404;-Microsoft.Interoperability#CA1410;-Microsoft.Interoperability#CA1411;-Microsoft.Interoperability#CA1405;-Microsoft.Interoperability#CA1409;-Microsoft.Interoperability#CA1415;-Microsoft.Interoperability#CA1408;-Microsoft.Interoperability#CA1414;-Microsoft.Interoperability#CA1412;-Microsoft.Interoperability#CA1400;-Microsoft.Interoperability#CA1401;-Microsoft.Maintainability#CA1506;-Microsoft.Maintainability#CA1502;-Microsoft.Maintainability#CA1501;-Microsoft.Maintainability#CA1505;-Microsoft.Maintainability#CA1504;-Microsoft.Maintainability#CA1500;-Microsoft.Mobility#CA1600;-Microsoft.Mobility#CA1601;-Microsoft.Naming#CA1702;-Microsoft.Naming#CA1700;-Microsoft.Naming#CA1712;-Microsoft.Naming#CA1713;-Microsoft.Naming#CA1714;-Microsoft.Naming#CA1709;-Microsoft.Naming#CA1704;-Microsoft.Naming#CA1708;-Microsoft.Naming#CA1715;-Microsoft.Naming#CA1710;-Microsoft.Naming#CA1720;-Microsoft.Naming#CA1707;-Microsoft.Naming#CA1722;-Microsoft.Naming#CA1711;-Microsoft.Naming#CA1716;-Microsoft.Naming#CA1717;-Microsoft.Naming#CA1725;-Microsoft.Naming#CA1719;-Microsoft.Naming#CA1721;-Microsoft.Naming#CA1701;-Microsoft.Naming#CA1703;-Microsoft.Naming#CA1724;-Microsoft.Naming#CA1726;-Microsoft.Performance#CA1809;-Microsoft.Performance#CA1811;-Microsoft.Performance#CA1813;-Microsoft.Performance#CA1816;-Microsoft.Performance#CA1800;-Microsoft.Performance#CA1805;-Microsoft.Performance#CA1810;-Microsoft.Performance#CA1824;-Microsoft.Performance#CA1822;-Microsoft.Performance#CA1814;-Microsoft.Performance#CA1819;-Microsoft.Performance#CA1821;-Microsoft.Performance#CA1820;-Microsoft.Performance#CA1802;-Microsoft.Portability#CA1901;-Microsoft.Portability#CA1900;-Microsoft.Reliability#CA2001;-Microsoft.Reliability#CA2002;-Microsoft.Reliability#CA2003;-Microsoft.Reliability#CA2004;-Microsoft.Reliability#CA2006;-Microsoft.Security#CA2116;-Microsoft.Security#CA2117;-Microsoft.Security#CA2105;-Microsoft.Security#CA2115;-Microsoft.Security#CA2102;-Microsoft.Security#CA2104;-Microsoft.Security#CA2122;-Microsoft.Secu
rity#CA2114;-Microsoft.Security#CA2123;-Microsoft.Security#CA2111;-Microsoft.Security#CA2108;-Microsoft.Security#CA2107;-Microsoft.Security#CA2103;-Microsoft.Security#CA2118;-Microsoft.Security#CA2109;-Microsoft.Security#CA2119;-Microsoft.Security#CA2106;-Microsoft.Security#CA2112;-Microsoft.Security#CA2120;-Microsoft.Security#CA2121;-Microsoft.Security#CA2126;-Microsoft.Security#CA2124;-Microsoft.Security#CA2127;-Microsoft.Security#CA2128;-Microsoft.Security#CA2129;-Microsoft.Usage#CA2243;-Microsoft.Usage#CA2236;-Microsoft.Usage#CA2227;-Microsoft.Usage#CA2213;-Microsoft.Usage#CA2216;-Microsoft.Usage#CA2214;-Microsoft.Usage#CA2222;-Microsoft.Usage#CA1806;-Microsoft.Usage#CA2217;-Microsoft.Usage#CA2212;-Microsoft.Usage#CA2219;-Microsoft.Usage#CA2201;-Microsoft.Usage#CA2228;-Microsoft.Usage#CA2221;-Microsoft.Usage#CA2220;-Microsoft.Usage#CA2240;-Microsoft.Usage#CA2229;-Microsoft.Usage#CA2238;-Microsoft.Usage#CA2207;-Microsoft.Usage#CA2208;-Microsoft.Usage#CA2235;-Microsoft.Usage#CA2237;-Microsoft.Usage#CA2232;-Microsoft.Usage#CA2223;-Microsoft.Usage#CA2211;-Microsoft.Usage#CA2233;-Microsoft.Usage#CA2225;-Microsoft.Usage#CA2226;-Microsoft.Usage#CA2231;-Microsoft.Usage#CA2224;-Microsoft.Usage#CA2218;-Microsoft.Usage#CA2234;-Microsoft.Usage#CA2239;-Microsoft.Usage#CA2200;-Microsoft.Usage#CA1801;-Microsoft.Usage#CA2242;-Microsoft.Usage#CA2205;-Microsoft.Usage#CA2230</CodeAnalysisRules>
<Prefer32Bit>false</Prefer32Bit>
<CodeAnalysisRuleSet>Strata.Base.Internal.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>Strata.Base.Internal.xml</DocumentationFile>
<NoWarn>42353,42354,42355</NoWarn>
<WarningsAsErrors>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036</WarningsAsErrors>
<Prefer32Bit>false</Prefer32Bit>
<CodeAnalysisRuleSet>Strata.Base.Internal.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseDeploy|AnyCPU'">
<DefineTrace>true</DefineTrace>
<OutputPath>bin\ReleaseDeploy\</OutputPath>
<DocumentationFile>Strata.Base.Internal.xml</DocumentationFile>
<Optimize>true</Optimize>
<NoWarn>42353,42354,42355</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<WarningsAsErrors>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036</WarningsAsErrors>
<Prefer32Bit>false</Prefer32Bit>
<CodeAnalysisRuleSet>Strata.Base.Internal.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Diagnostics" />
</ItemGroup>
<ItemGroup>
<Compile Include="Encryptors\IPasswordEncryptionMethod.vb" />
<Compile Include="Encryptors\UberEncryptionMethod.vb" />
<Compile Include="Encryptors\UserSaltEncryptionMethod.vb" />
<Compile Include="InternalConstants.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="Security\Encryption.vb" />
<Compile Include="Security\SecurityUtils.vb" />
<Compile Include="Encryptors\UserGUIDEncryptionMethod.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
<None Include="Strata.Base.Internal.ruleset" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="..\..\.sonarlint\stratajazz\VB\SonarLint.xml">
<Link>SonarLint.xml</Link>
</AdditionalFiles>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Strata.Configuration.Client">
<Version>8.44.0</Version>
</PackageReference>
<PackageReference Include="Strata.Jazz.Client">
<Version>0.0.9</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="Strata.Base.Internal.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</sectionGroup>
</configSections>
<appSettings>
<add key="Environment" value="Development"/>
</appSettings>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information"/>
</switches>
<sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
<applicationSettings>
<Strata.Base.Internal.My.MySettings>
<setting name="Environment" serializeAs="String">
<value>Development</value>
</setting>
</Strata.Base.Internal.My.MySettings>
</applicationSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/></startup></configuration>

View File

@ -0,0 +1,7 @@
' <autogenerated/>
Option Strict Off
Option Explicit On
Imports System
Imports System.Reflection
<Assembly: Global.System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.7.1", FrameworkDisplayName:="")>

View File

@ -0,0 +1,7 @@
' <autogenerated/>
Option Strict Off
Option Explicit On
Imports System
Imports System.Reflection
<Assembly: Global.System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.8", FrameworkDisplayName:=".NET Framework 4.8")>

View File

@ -0,0 +1,76 @@
{
"format": 1,
"restore": {
"D:\\Develop\\Repos\\st-monolith\\Code\\Strata.Base.Internal\\Strata.Base.Internal.vbproj": {}
},
"projects": {
"D:\\Develop\\Repos\\st-monolith\\Code\\Strata.Base.Internal\\Strata.Base.Internal.vbproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "D:\\Develop\\Repos\\st-monolith\\Code\\Strata.Base.Internal\\Strata.Base.Internal.vbproj",
"projectName": "Strata.Base.Internal",
"projectPath": "D:\\Develop\\Repos\\st-monolith\\Code\\Strata.Base.Internal\\Strata.Base.Internal.vbproj",
"packagesPath": "D:\\Users\\jorge.burgos\\.nuget\\packages\\",
"outputPath": "D:\\Develop\\Repos\\st-monolith\\Code\\Strata.Base.Internal\\obj\\",
"projectStyle": "PackageReference",
"skipContentFileWrite": true,
"UsingMicrosoftNETSdk": false,
"fallbackFolders": [
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"
],
"configFilePaths": [
"D:\\Develop\\Repos\\st-monolith\\NuGet.Config",
"D:\\Users\\jorge.burgos\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
],
"originalTargetFrameworks": [
"net48"
],
"sources": {
"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
"https://api.nuget.org/v3/index.json": {},
"https://proget.sdt.local/nuget/nuget/v3/index.json": {}
},
"frameworks": {
"net48": {
"projectReferences": {}
}
},
"restoreAuditProperties": {
"enableAudit": "true",
"auditLevel": "low",
"auditMode": "direct"
}
},
"frameworks": {
"net48": {
"dependencies": {
"Strata.Configuration.Client": {
"target": "Package",
"version": "[8.44.0, )"
},
"Strata.Jazz.Client": {
"target": "Package",
"version": "[0.0.9, )"
}
}
}
},
"runtimes": {
"win": {
"#import": []
},
"win-arm64": {
"#import": []
},
"win-x64": {
"#import": []
},
"win-x86": {
"#import": []
}
}
}
}
}

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">$(UserProfile)\.nuget\packages\</NuGetPackageRoot>
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">D:\Users\jorge.burgos\.nuget\packages\;C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages</NuGetPackageFolders>
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.12.2</NuGetToolVersion>
</PropertyGroup>
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<SourceRoot Include="D:\Users\jorge.burgos\.nuget\packages\" />
<SourceRoot Include="C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages\" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" />

View File

@ -0,0 +1,97 @@
{
"version": 3,
"targets": {
".NETFramework,Version=v4.8": {},
".NETFramework,Version=v4.8/win": {},
".NETFramework,Version=v4.8/win-arm64": {},
".NETFramework,Version=v4.8/win-x64": {},
".NETFramework,Version=v4.8/win-x86": {}
},
"libraries": {},
"projectFileDependencyGroups": {
".NETFramework,Version=v4.8": [
"Strata.Configuration.Client >= 8.44.0",
"Strata.Jazz.Client >= 0.0.9"
]
},
"packageFolders": {
"D:\\Users\\jorge.burgos\\.nuget\\packages\\": {},
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages": {}
},
"project": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "D:\\Develop\\Repos\\st-monolith\\Code\\Strata.Base.Internal\\Strata.Base.Internal.vbproj",
"projectName": "Strata.Base.Internal",
"projectPath": "D:\\Develop\\Repos\\st-monolith\\Code\\Strata.Base.Internal\\Strata.Base.Internal.vbproj",
"packagesPath": "D:\\Users\\jorge.burgos\\.nuget\\packages\\",
"outputPath": "D:\\Develop\\Repos\\st-monolith\\Code\\Strata.Base.Internal\\obj\\",
"projectStyle": "PackageReference",
"skipContentFileWrite": true,
"UsingMicrosoftNETSdk": false,
"fallbackFolders": [
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"
],
"configFilePaths": [
"D:\\Develop\\Repos\\st-monolith\\NuGet.Config",
"D:\\Users\\jorge.burgos\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
],
"originalTargetFrameworks": [
"net48"
],
"sources": {
"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
"https://api.nuget.org/v3/index.json": {},
"https://proget.sdt.local/nuget/nuget/v3/index.json": {}
},
"frameworks": {
"net48": {
"projectReferences": {}
}
},
"restoreAuditProperties": {
"enableAudit": "true",
"auditLevel": "low",
"auditMode": "direct"
}
},
"frameworks": {
"net48": {
"dependencies": {
"Strata.Configuration.Client": {
"target": "Package",
"version": "[8.44.0, )"
},
"Strata.Jazz.Client": {
"target": "Package",
"version": "[0.0.9, )"
}
}
}
},
"runtimes": {
"win": {
"#import": []
},
"win-arm64": {
"#import": []
},
"win-x64": {
"#import": []
},
"win-x86": {
"#import": []
}
}
},
"logs": [
{
"code": "NU1301",
"level": "Error",
"message": "Unable to load the service index for source https://proget.sdt.local/nuget/nuget/v3/index.json.\r\n An error occurred while sending the request.\r\n The remote name could not be resolved: 'proget.sdt.local'",
"libraryId": "Strata.Configuration.Client"
}
]
}

View File

@ -0,0 +1,15 @@
{
"version": 2,
"dgSpecHash": "79VZAfPMGao=",
"success": false,
"projectFilePath": "D:\\Develop\\Repos\\st-monolith\\Code\\Strata.Base.Internal\\Strata.Base.Internal.vbproj",
"expectedPackageFiles": [],
"logs": [
{
"code": "NU1301",
"level": "Error",
"message": "Unable to load the service index for source https://proget.sdt.local/nuget/nuget/v3/index.json.\r\n An error occurred while sending the request.\r\n The remote name could not be resolved: 'proget.sdt.local'",
"libraryId": "Strata.Configuration.Client"
}
]
}

View File

@ -0,0 +1,378 @@
# VB.NET to C# Migration Guide
## Migration Sequence - Important!
### Recommended Order of Migration
The migration should be performed in two distinct phases to minimize complications and ensure a smooth transition:
1. **First Phase: .NET Framework to .NET 8 Migration (Stay in VB.NET)**
- Focus only on framework compatibility
- Keep the original VB.NET language
- Use .NET Upgrade Assistant
- Test thoroughly before proceeding
2. **Second Phase: VB.NET to C# Conversion**
- Convert the working .NET 8 VB.NET code to C#
- Use code conversion tools
- Apply C# best practices
- Final testing and optimization
### Rationale for This Sequence
- Separates framework issues from language syntax issues
- Easier debugging and problem isolation
- Framework migration tools work better with VB.NET
- Allows parallel testing between versions
- Reduces complexity of each migration step
### Example Migration Path
```
Starting Point: VB.NET on .NET Framework 4.7.1
Step 1: VB.NET on .NET 8 (framework migration)
Step 2: C# on .NET 8 (language conversion)
```
## AI-Assisted Migration Support
### Available AI Tools
1. **GitHub Copilot**
- IDE integration
- Real-time code suggestions
- Pattern recognition
- Modern C# syntax suggestions
2. **Claude or ChatGPT**
- Code analysis and review
- Pattern modernization suggestions
- Documentation generation
- Error resolution
- Test case generation
- Code optimization suggestions
3. **Amazon CodeWhisperer**
- Code completion
- Pattern suggestions
- Security checks
- Best practice recommendations
## Primary Migration Tools
### 1. .NET Upgrade Assistant (Free)
#### Features
- Official Microsoft tool
- Command-line interface
- Framework upgrade automation
- Package dependency updates
- Configuration file updates
#### Installation
```bash
dotnet tool install -g upgrade-assistant
```
#### Usage for Framework Migration
```bash
# Analyze your solution
upgrade-assistant analyze your-solution.sln
# Perform the upgrade
upgrade-assistant upgrade your-solution.sln
```
### 2. ICSharpCode.CodeConverter (Free, Open Source)
#### Features
- Built on Roslyn
- Command-line and Visual Studio integration
- Community-supported
- Regular updates
- Batch processing capability
#### Installation
```bash
dotnet tool install --global ICSharpCode.CodeConverter.Cli
```
### 3. Telerik Code Converter (Free Online Tool)
#### Features
- Web-based interface
- No installation required
- Immediate results
- Good for quick conversions
- Supports multiple code snippets
### 4. Visual Studio Built-in Tools (Free with Community Edition)
#### Features
- Code analysis tools
- Refactoring capabilities
- Project system tools
- Framework compatibility checking
- IntelliSense support
## Detailed Migration Steps with AI Enhancement
### 1. Preparation Phase
1. Analyze current codebase
- Document dependencies
- Identify framework-specific code
- List external packages
- Note VB.NET specific features
**AI Enhancement**:
- Use Claude/ChatGPT to analyze code patterns and identify potential migration challenges
- Ask AI to create a detailed dependency map
- Use AI to identify outdated patterns that should be modernized
```
Example prompt: "Analyze this VB.NET code and identify:
1. Framework-specific dependencies
2. Outdated patterns that should be modernized
3. Potential migration challenges"
```
2. Setup Environment
- Install Visual Studio Community Edition
- Install .NET Upgrade Assistant
- Install ICSharpCode.CodeConverter
- Set up version control
- Create backup of all code
3. Plan Migration Strategy
- Identify smallest/simplest libraries to start
- Create test cases for validation
- Document current functionality
- Set up continuous integration
**AI Enhancement**:
- Use AI to generate test cases
- Ask AI to review and enhance migration plan
- Generate documentation templates
```
Example prompt: "Based on this code, generate:
1. Unit test scenarios
2. Integration test cases
3. Documentation structure"
```
### 2. Framework Migration Phase (Step 1)
1. Framework Update
- Run .NET Upgrade Assistant analysis
- Review suggested changes
- Update package references
- Fix compatibility issues
**AI Enhancement**:
- Use AI to review upgrade-assistant suggestions
- Get alternative solutions for compatibility issues
- Modernize configuration files
```
Example prompt: "Review these .NET Framework 4.7.1 configuration settings
and suggest equivalent .NET 8 configurations"
```
2. Testing Framework Migration
- Run all tests in VB.NET
- Verify functionality
- Check performance
- Document any issues
**AI Enhancement**:
- Generate additional test cases
- Review test coverage
- Suggest performance improvements
```
Example prompt: "Analyze this test suite and suggest:
1. Additional test scenarios
2. Performance test cases
3. Edge cases to consider"
```
3. Framework Stabilization
- Fix identified issues
- Update dependencies
- Verify third-party compatibility
- Final framework testing
### 3. Language Migration Phase (Step 2)
1. Code Conversion
- Use ICSharpCode.CodeConverter for bulk conversion
- Use Telerik Code Converter for problematic sections
- Manual review and cleanup
- Apply C# best practices
**AI Enhancement**:
- Review converted code for optimization
- Suggest modern C# patterns
- Identify potential improvements
```
Example prompt: "Review this converted C# code and suggest:
1. Modern C# patterns to apply
2. Performance optimizations
3. Code structure improvements"
```
2. Iterative Improvements
- Convert one library at a time
- Update dependencies
- Modernize code patterns
- Implement C# specific features
**AI Enhancement**:
- Get suggestions for code modernization
- Review for best practices
- Generate documentation
```
Example prompt: "Suggest improvements for this C# code using:
1. Latest C# features
2. Modern design patterns
3. Performance best practices"
```
### 4. Testing Phase
1. Automated Testing
- Run existing unit tests
- Create new C# specific tests
- Verify functionality
- Performance testing
2. Manual Testing
- Code review
- Functionality verification
- Edge case testing
- Integration testing
**AI Enhancement**:
- Generate unit tests
- Suggest integration test scenarios
- Review test coverage
- Identify edge cases
```
Example prompt: "For this C# class, generate:
1. Unit tests covering main scenarios
2. Edge cases to test
3. Integration test examples"
```
### 5. Documentation Phase
1. Technical Documentation
- API documentation
- Migration notes
- Usage examples
- Troubleshooting guides
**AI Enhancement**:
- Generate API documentation
- Create usage examples
- Write migration notes
- Create troubleshooting guides
```
Example prompt: "Generate comprehensive documentation for this C# class including:
1. Method descriptions
2. Usage examples
3. Common troubleshooting scenarios"
```
## Best Practices
### Code Quality
- Review all automated conversions
- Follow C# coding standards
- Use modern language features
- Remove deprecated code
- Optimize for .NET 8
- Document major changes
### Testing Strategy
- Maintain test coverage
- Add new tests for C# features
- Validate performance
- Check compatibility
- Document changes
### Risk Mitigation
- Regular backups
- Incremental changes
- Keep original code
- Document conversion issues
- Maintain rollback capability
## AI-Assisted Best Practices
### Code Review Enhancement
Use AI tools to:
- Review converted code quality
- Suggest improvements
- Identify potential issues
- Check for modern patterns
```
Example prompt: "Review this converted C# code for:
1. Potential bugs
2. Performance issues
3. Modern C# feature opportunities"
```
### Testing Strategy Enhancement
Use AI tools to:
- Generate test cases
- Identify edge cases
- Create test data
- Suggest test scenarios
```
Example prompt: "For this business logic, suggest:
1. Key test scenarios
2. Edge cases
3. Test data examples"
```
### Documentation Enhancement
Use AI tools to:
- Generate technical documentation
- Create code examples
- Write API documentation
- Document migration decisions
```
Example prompt: "Create documentation for this migrated code including:
1. API reference
2. Migration decisions
3. Usage examples"
```
## Tips for Specific Scenarios
### Large Codebases
- Split into manageable chunks
- Convert one namespace at a time
- Use batch processing tools
- Automate repetitive tasks
- Track progress systematically
### Complex Logic
- Use multiple conversion tools
- Compare tool outputs
- Manual review critical sections
- Maintain business logic
- Document complex conversions
### Legacy Features
- Research modern alternatives
- Plan feature updates
- Document replacements
- Test thoroughly
- Phase out gradually
## Conclusion
A successful migration can be achieved by:
- Following the correct migration sequence (Framework first, then Language)
- Leveraging AI tools effectively
- Using multiple conversion tools
- Conducting thorough testing
- Maintaining good documentation
### AI Tool Best Practices
1. Always review AI-generated code
2. Test all suggestions thoroughly
3. Use AI tools iteratively for improvements
4. Combine multiple AI tools for better results
5. Keep security in mind when sharing code with AI tools
6. Document which parts were AI-assisted for future reference
Start with a small pilot project to validate the process and AI tool effectiveness before proceeding with the full migration.