├── .github └── workflows │ └── main.yml ├── .gitignore ├── EasyEncryption.sln ├── Encryption.Framework ├── Algorithms │ ├── AES.cs │ ├── AesThenHmac.cs │ ├── Des.cs │ ├── MD5.cs │ ├── RSA.cs │ └── SHA.cs ├── Encryption.Framework.csproj ├── Encryption.Framework.csproj.DotSettings ├── Enums │ └── CreditCardType.cs ├── Properties │ └── AssemblyInfo.cs └── Tools │ └── RandomGenerator.cs ├── Encryption.Tests ├── Algorithms │ ├── AesTests.cs │ ├── AesThenHmacTests.cs │ ├── DesTests.cs │ ├── MD5Tests.cs │ ├── RSATests.cs │ └── SHATests.cs ├── Encryption.Tests.csproj ├── Properties │ └── AssemblyInfo.cs └── Tools │ └── RandomGeneratorTests.cs ├── Encryption.csproj ├── LICENSE ├── Properties └── AssemblyInfo.cs └── README.md /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: publish to nuget 2 | on: 3 | push: 4 | branches: 5 | - master # Default release branch 6 | jobs: 7 | publish: 8 | name: build, pack & publish 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | 13 | # - name: Setup dotnet 14 | # uses: actions/setup-dotnet@v1 15 | # with: 16 | # dotnet-version: 3.1.200 17 | 18 | # Publish 19 | - name: publish on version change 20 | id: publish_nuget 21 | uses: rohith/publish-nuget@v2 22 | with: 23 | # Filepath of the project to be packaged, relative to root of repository 24 | PROJECT_FILE_PATH: Core/Core.csproj 25 | 26 | # NuGet package id, used for version detection & defaults to project name 27 | # PACKAGE_NAME: Core 28 | 29 | # Filepath with version info, relative to root of repository & defaults to PROJECT_FILE_PATH 30 | # VERSION_FILE_PATH: Directory.Build.props 31 | 32 | # Regex pattern to extract version info in a capturing group 33 | # VERSION_REGEX: ^\s*(.*)<\/Version>\s*$ 34 | 35 | # Useful with external providers like Nerdbank.GitVersioning, ignores VERSION_FILE_PATH & VERSION_REGEX 36 | # VERSION_STATIC: 1.0.0 37 | 38 | # Flag to toggle git tagging, enabled by default 39 | # TAG_COMMIT: true 40 | 41 | # Format of the git tag, [*] gets replaced with actual version 42 | # TAG_FORMAT: v* 43 | 44 | # API key to authenticate with NuGet server 45 | # NUGET_KEY: ${{secrets.NUGET_API_KEY}} 46 | 47 | # NuGet server uri hosting the packages, defaults to https://api.nuget.org 48 | # NUGET_SOURCE: https://api.nuget.org 49 | 50 | # Flag to toggle pushing symbols along with nuget package to the server, disabled by default 51 | # INCLUDE_SYMBOLS: false 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Build Folders (you can keep bin if you'd like, to store dlls and pdbs) 2 | [Bb]in/ 3 | [Oo]bj/ 4 | 5 | # mstest test results 6 | TestResults 7 | 8 | ## Ignore Visual Studio temporary files, build results, and 9 | ## files generated by popular Visual Studio add-ons. 10 | 11 | # User-specific files 12 | *.suo 13 | *.user 14 | *.sln.docstates 15 | .idea/ 16 | # Build results 17 | [Dd]ebug/ 18 | [Rr]elease/ 19 | x64/ 20 | *_i.c 21 | *_p.c 22 | *.ilk 23 | *.meta 24 | *.obj 25 | *.pch 26 | *.pdb 27 | *.pgc 28 | *.pgd 29 | *.rsp 30 | *.sbr 31 | *.tlb 32 | *.tli 33 | *.tlh 34 | *.tmp 35 | *.log 36 | *.vspscc 37 | *.vssscc 38 | .builds 39 | 40 | # Visual C++ cache files 41 | ipch/ 42 | *.aps 43 | *.ncb 44 | *.opensdf 45 | *.sdf 46 | 47 | # Visual Studio profiler 48 | *.psess 49 | *.vsp 50 | *.vspx 51 | 52 | # Guidance Automation Toolkit 53 | *.gpState 54 | 55 | # ReSharper is a .NET coding add-in 56 | _ReSharper* 57 | 58 | # NCrunch 59 | *.ncrunch* 60 | .*crunch*.local.xml 61 | 62 | # Installshield output folder 63 | [Ee]xpress 64 | 65 | # DocProject is a documentation generator add-in 66 | DocProject/buildhelp/ 67 | DocProject/Help/*.HxT 68 | DocProject/Help/*.HxC 69 | DocProject/Help/*.hhc 70 | DocProject/Help/*.hhk 71 | DocProject/Help/*.hhp 72 | DocProject/Help/Html2 73 | DocProject/Help/html 74 | 75 | # Click-Once directory 76 | publish 77 | 78 | # Publish Web Output 79 | *.Publish.xml 80 | 81 | # NuGet Packages Directory 82 | packages 83 | 84 | # Windows Azure Build Output 85 | csx 86 | *.build.csdef 87 | 88 | # Windows Store app package directory 89 | AppPackages/ 90 | 91 | # Others 92 | [Bb]in 93 | [Oo]bj 94 | sql 95 | TestResults 96 | [Tt]est[Rr]esult* 97 | *.Cache 98 | ClientBin 99 | [Ss]tyle[Cc]op.* 100 | ~$* 101 | *.dbmdl 102 | Generated_Code #added for RIA/Silverlight projects 103 | 104 | # Backup & report files from converting an old project file to a newer 105 | # Visual Studio version. Backup files are not needed, because we have git ;-) 106 | _UpgradeReport_Files/ 107 | Backup*/ 108 | UpgradeLog*.XML 109 | -------------------------------------------------------------------------------- /EasyEncryption.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.24720.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Encryption.Tests", "Encryption.Tests\Encryption.Tests.csproj", "{4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Encryption.Framework", "Encryption.Framework\Encryption.Framework.csproj", "{8291C00A-362E-4409-B761-78B7DFB0904D}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Debug|ARM = Debug|ARM 14 | Debug|x64 = Debug|x64 15 | Debug|x86 = Debug|x86 16 | Release|Any CPU = Release|Any CPU 17 | Release|ARM = Release|ARM 18 | Release|x64 = Release|x64 19 | Release|x86 = Release|x86 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Debug|ARM.ActiveCfg = Debug|Any CPU 25 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Debug|ARM.Build.0 = Debug|Any CPU 26 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Debug|x64.ActiveCfg = Debug|Any CPU 27 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Debug|x64.Build.0 = Debug|Any CPU 28 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Debug|x86.ActiveCfg = Debug|Any CPU 29 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Debug|x86.Build.0 = Debug|Any CPU 30 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Release|ARM.ActiveCfg = Release|Any CPU 33 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Release|ARM.Build.0 = Release|Any CPU 34 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Release|x64.ActiveCfg = Release|Any CPU 35 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Release|x64.Build.0 = Release|Any CPU 36 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Release|x86.ActiveCfg = Release|Any CPU 37 | {4C30F616-7750-4D24-A3C3-2FEF8DC3E5D4}.Release|x86.Build.0 = Release|Any CPU 38 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Debug|ARM.ActiveCfg = Debug|Any CPU 41 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Debug|ARM.Build.0 = Debug|Any CPU 42 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Debug|x64.ActiveCfg = Debug|Any CPU 43 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Debug|x64.Build.0 = Debug|Any CPU 44 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Debug|x86.ActiveCfg = Debug|Any CPU 45 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Debug|x86.Build.0 = Debug|Any CPU 46 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Release|ARM.ActiveCfg = Release|Any CPU 49 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Release|ARM.Build.0 = Release|Any CPU 50 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Release|x64.ActiveCfg = Release|Any CPU 51 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Release|x64.Build.0 = Release|Any CPU 52 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Release|x86.ActiveCfg = Release|Any CPU 53 | {8291C00A-362E-4409-B761-78B7DFB0904D}.Release|x86.Build.0 = Release|Any CPU 54 | EndGlobalSection 55 | GlobalSection(SolutionProperties) = preSolution 56 | HideSolutionNode = FALSE 57 | EndGlobalSection 58 | EndGlobal 59 | -------------------------------------------------------------------------------- /Encryption.Framework/Algorithms/AES.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Security.Cryptography; 4 | using System.Text; 5 | 6 | namespace EasyEncryption 7 | { 8 | public abstract class AES 9 | { 10 | /// 11 | /// Encrypt text using AES algorithm. 12 | /// 13 | /// The text that you want to encrypt 14 | /// Symmetric key that is used for encryption and decryption. 15 | /// Initialization vector (IV) for the symmetric algorithm. 16 | /// Encrypt base64 string 17 | public static string Encrypt(string plainText, string key, string iv) 18 | { 19 | var bytes = Encoding.UTF8.GetBytes(plainText); // parse text to bites array 20 | using (var desCryptoService = new AesCryptoServiceProvider()) 21 | { 22 | desCryptoService.Key = Encoding.UTF8.GetBytes(key); 23 | desCryptoService.IV = Encoding.UTF8.GetBytes(iv); 24 | 25 | using (var memoryStream = new MemoryStream()) 26 | { 27 | var cryptoStream = new CryptoStream(memoryStream, desCryptoService.CreateEncryptor(), CryptoStreamMode.Write); // open cryptoStream 28 | cryptoStream.Write(bytes, 0, bytes.Length); 29 | cryptoStream.Close(); 30 | memoryStream.Close(); 31 | return Convert.ToBase64String(memoryStream.ToArray()); 32 | } 33 | } 34 | } 35 | /// 36 | /// Decrypt text using AES algorithm. 37 | /// 38 | /// Your encrypted base64 string 39 | /// Symmetric key that is used for encryption and decryption. 40 | /// Initialization vector (IV) for the symmetric algorithm. 41 | /// Decrypted string 42 | public static string Decrypt(string encryptedText, string key, string iv) 43 | { 44 | var encryptedTextByte = Convert.FromBase64String(encryptedText); ; // parse text to bites array 45 | using (var aesCryptoServiceProvider = new AesCryptoServiceProvider()) 46 | { 47 | aesCryptoServiceProvider.Key = Encoding.UTF8.GetBytes(key); 48 | aesCryptoServiceProvider.IV = Encoding.UTF8.GetBytes(iv); 49 | var decryptor = aesCryptoServiceProvider.CreateDecryptor(aesCryptoServiceProvider.Key, aesCryptoServiceProvider.IV); 50 | // Create the streams used for decryption. 51 | using (var msDecrypt = new MemoryStream(encryptedTextByte)) 52 | { 53 | using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) 54 | { 55 | using (var srDecrypt = new StreamReader(csDecrypt)) 56 | { 57 | var res = srDecrypt.ReadToEnd(); 58 | csDecrypt.Close(); 59 | srDecrypt.Close(); 60 | return res; 61 | } 62 | } 63 | } 64 | } 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Encryption.Framework/Algorithms/AesThenHmac.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Security.Cryptography; 4 | using System.Text; 5 | 6 | namespace EasyEncryption 7 | { 8 | public abstract class AesThenHmac 9 | { 10 | private static readonly RandomNumberGenerator Random = RandomNumberGenerator.Create(); 11 | 12 | //Preconfigured Encryption Parameters 13 | public static readonly int BlockBitSize = 128; 14 | public static readonly int KeyBitSize = 256; 15 | 16 | //Preconfigured Password Key Derivation Parameters 17 | public static readonly int SaltBitSize = 64; 18 | public static readonly int Iterations = 10000; 19 | public static readonly int MinPasswordLength = 1; 20 | 21 | /// 22 | /// Helper that generates a random key on each call. 23 | /// 24 | /// 25 | public static byte[] NewKey() 26 | { 27 | var key = new byte[KeyBitSize / 8]; 28 | Random.GetBytes(key); 29 | return key; 30 | } 31 | 32 | /// 33 | /// Simple Encryption (AES) then Authentication (HMAC) for a UTF8 Message. 34 | /// 35 | /// The secret message. 36 | /// The crypt key. 37 | /// The auth key. 38 | /// (Optional) Non-Secret Payload. 39 | /// 40 | /// Encrypted Message 41 | /// 42 | /// Secret Message Required!;secretMessage 43 | /// 44 | /// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize + HMac-Tag(32)) * 1.33 Base64 45 | /// 46 | public static string SimpleEncrypt(string secretMessage, byte[] cryptKey, byte[] authKey, 47 | byte[] nonSecretPayload = null) 48 | { 49 | if (string.IsNullOrEmpty(secretMessage)) 50 | throw new ArgumentException("Secret Message Required!", nameof(secretMessage)); 51 | 52 | var plainText = Encoding.UTF8.GetBytes(secretMessage); 53 | var cipherText = SimpleEncrypt(plainText, cryptKey, authKey, nonSecretPayload); 54 | return Convert.ToBase64String(cipherText); 55 | } 56 | 57 | /// 58 | /// Simple Authentication (HMAC) then Decryption (AES) for a secrets UTF8 Message. 59 | /// 60 | /// The encrypted message. 61 | /// The crypt key. 62 | /// The auth key. 63 | /// Length of the non secret payload. 64 | /// 65 | /// Decrypted Message 66 | /// 67 | /// Encrypted Message Required!;encryptedMessage 68 | public static string SimpleDecrypt(string encryptedMessage, byte[] cryptKey, byte[] authKey, 69 | int nonSecretPayloadLength = 0) 70 | { 71 | if (string.IsNullOrWhiteSpace(encryptedMessage)) 72 | throw new ArgumentException("Encrypted Message Required!", nameof(encryptedMessage)); 73 | 74 | var cipherText = Convert.FromBase64String(encryptedMessage); 75 | var plainText = SimpleDecrypt(cipherText, cryptKey, authKey, nonSecretPayloadLength); 76 | return plainText == null ? null : Encoding.UTF8.GetString(plainText); 77 | } 78 | 79 | /// 80 | /// Simple Encryption (AES) then Authentication (HMAC) of a UTF8 message 81 | /// using Keys derived from a Password (PBKDF2). 82 | /// 83 | /// The secret message. 84 | /// The password. 85 | /// The non secret payload. 86 | /// 87 | /// Encrypted Message 88 | /// 89 | /// password 90 | /// 91 | /// Significantly less secure than using random binary keys. 92 | /// Adds additional non secret payload for key generation parameters. 93 | /// 94 | public static string SimpleEncryptWithPassword(string secretMessage, string password, 95 | byte[] nonSecretPayload = null) 96 | { 97 | if (string.IsNullOrEmpty(secretMessage)) 98 | throw new ArgumentException("Secret Message Required!", nameof(secretMessage)); 99 | 100 | var plainText = Encoding.UTF8.GetBytes(secretMessage); 101 | var cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload); 102 | return Convert.ToBase64String(cipherText); 103 | } 104 | 105 | /// 106 | /// Simple Authentication (HMAC) and then Descryption (AES) of a UTF8 Message 107 | /// using keys derived from a password (PBKDF2). 108 | /// 109 | /// The encrypted message. 110 | /// The password. 111 | /// Length of the non secret payload. 112 | /// 113 | /// Decrypted Message 114 | /// 115 | /// Encrypted Message Required!;encryptedMessage 116 | /// 117 | /// Significantly less secure than using random binary keys. 118 | /// 119 | public static string SimpleDecryptWithPassword(string encryptedMessage, string password, 120 | int nonSecretPayloadLength = 0) 121 | { 122 | if (string.IsNullOrWhiteSpace(encryptedMessage)) 123 | throw new ArgumentException("Encrypted Message Required!", nameof(encryptedMessage)); 124 | if (string.IsNullOrEmpty(password)) 125 | throw new ArgumentException("Secret Message Required!", nameof(password)); 126 | 127 | var cipherText = Convert.FromBase64String(encryptedMessage); 128 | var plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength); 129 | return plainText == null ? null : Encoding.UTF8.GetString(plainText); 130 | } 131 | 132 | /// 133 | /// Simple Encryption(AES) then Authentication (HMAC) for a UTF8 Message. 134 | /// 135 | /// The secret message. 136 | /// The crypt key. 137 | /// The auth key. 138 | /// (Optional) Non-Secret Payload. 139 | /// 140 | /// Encrypted Message 141 | /// 142 | /// 143 | /// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize + HMac-Tag(32)) * 1.33 Base64 144 | /// 145 | public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, 146 | byte[] nonSecretPayload = null) 147 | { 148 | //User Error Checks 149 | if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) 150 | throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), nameof(cryptKey)); 151 | 152 | if (authKey == null || authKey.Length != KeyBitSize / 8) 153 | throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), nameof(authKey)); 154 | 155 | if (secretMessage == null || secretMessage.Length < 1) 156 | throw new ArgumentException("Secret Message Required!", nameof(secretMessage)); 157 | 158 | //non-secret payload optional 159 | nonSecretPayload = nonSecretPayload ?? new byte[] { }; 160 | 161 | byte[] cipherText; 162 | byte[] iv; 163 | 164 | using (var aes = new AesManaged 165 | { 166 | KeySize = KeyBitSize, 167 | BlockSize = BlockBitSize, 168 | Mode = CipherMode.CBC, 169 | Padding = PaddingMode.PKCS7 170 | }) 171 | { 172 | //Use random IV 173 | aes.GenerateIV(); 174 | iv = aes.IV; 175 | 176 | using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) 177 | using (var cipherStream = new MemoryStream()) 178 | { 179 | using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) 180 | using (var binaryWriter = new BinaryWriter(cryptoStream)) 181 | { 182 | //Encrypt Data 183 | binaryWriter.Write(secretMessage); 184 | } 185 | 186 | cipherText = cipherStream.ToArray(); 187 | } 188 | } 189 | 190 | //Assemble encrypted message and add authentication 191 | using (var hmac = new HMACSHA256(authKey)) 192 | using (var encryptedStream = new MemoryStream()) 193 | { 194 | using (var binaryWriter = new BinaryWriter(encryptedStream)) 195 | { 196 | //Prepend non-secret payload if any 197 | binaryWriter.Write(nonSecretPayload); 198 | //Prepend IV 199 | binaryWriter.Write(iv); 200 | //Write Ciphertext 201 | binaryWriter.Write(cipherText); 202 | binaryWriter.Flush(); 203 | 204 | //Authenticate all data 205 | var tag = hmac.ComputeHash(encryptedStream.ToArray()); 206 | //Postpend tag 207 | binaryWriter.Write(tag); 208 | } 209 | return encryptedStream.ToArray(); 210 | } 211 | } 212 | 213 | /// 214 | /// Simple Authentication (HMAC) then Decryption (AES) for a secrets UTF8 Message. 215 | /// 216 | /// The encrypted message. 217 | /// The crypt key. 218 | /// The auth key. 219 | /// Length of the non secret payload. 220 | /// Decrypted Message 221 | public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, 222 | int nonSecretPayloadLength = 0) 223 | { 224 | //Basic Usage Error Checks 225 | if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) 226 | throw new ArgumentException(string.Format("CryptKey needs to be {0} bit!", KeyBitSize), nameof(cryptKey)); 227 | 228 | if (authKey == null || authKey.Length != KeyBitSize / 8) 229 | throw new ArgumentException(string.Format("AuthKey needs to be {0} bit!", KeyBitSize), nameof(authKey)); 230 | 231 | if (encryptedMessage == null || encryptedMessage.Length == 0) 232 | throw new ArgumentException("Encrypted Message Required!", nameof(encryptedMessage)); 233 | 234 | using (var hmac = new HMACSHA256(authKey)) 235 | { 236 | var sentTag = new byte[hmac.HashSize / 8]; 237 | //Calculate Tag 238 | var calcTag = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length); 239 | var ivLength = (BlockBitSize / 8); 240 | 241 | //if message length is to small just return null 242 | if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength) 243 | return null; 244 | 245 | //Grab Sent Tag 246 | Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length); 247 | 248 | //Compare Tag with constant time comparison 249 | var compare = 0; 250 | for (var i = 0; i < sentTag.Length; i++) 251 | compare |= sentTag[i] ^ calcTag[i]; 252 | 253 | //if message doesn't authenticate return null 254 | if (compare != 0) 255 | return null; 256 | 257 | using (var aes = new AesManaged 258 | { 259 | KeySize = KeyBitSize, 260 | BlockSize = BlockBitSize, 261 | Mode = CipherMode.CBC, 262 | Padding = PaddingMode.PKCS7 263 | }) 264 | { 265 | //Grab IV from message 266 | var iv = new byte[ivLength]; 267 | Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length); 268 | 269 | using (var decrypter = aes.CreateDecryptor(cryptKey, iv)) 270 | using (var plainTextStream = new MemoryStream()) 271 | { 272 | using ( 273 | var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write)) 274 | using (var binaryWriter = new BinaryWriter(decrypterStream)) 275 | { 276 | //Decrypt Cipher Text from Message 277 | binaryWriter.Write( 278 | encryptedMessage, 279 | nonSecretPayloadLength + iv.Length, 280 | encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length 281 | ); 282 | } 283 | //Return Plain Text 284 | return plainTextStream.ToArray(); 285 | } 286 | } 287 | } 288 | } 289 | 290 | /// 291 | /// Simple Encryption (AES) then Authentication (HMAC) of a UTF8 message 292 | /// using Keys derived from a Password (PBKDF2) 293 | /// 294 | /// The secret message. 295 | /// The password. 296 | /// The non secret payload. 297 | /// 298 | /// Encrypted Message 299 | /// 300 | /// Must have a password of minimum length;password 301 | /// 302 | /// Significantly less secure than using random binary keys. 303 | /// Adds additional non secret payload for key generation parameters. 304 | /// 305 | public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password, 306 | byte[] nonSecretPayload = null) 307 | { 308 | nonSecretPayload = nonSecretPayload ?? new byte[] { }; 309 | 310 | //User Error Checks 311 | if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength) 312 | throw new ArgumentException( 313 | String.Format("Must have a password of at least {0} characters!", MinPasswordLength), nameof(password)); 314 | 315 | if (secretMessage == null || secretMessage.Length == 0) 316 | throw new ArgumentException("Secret Message Required!", nameof(secretMessage)); 317 | 318 | var payload = new byte[((SaltBitSize / 8) * 2) + nonSecretPayload.Length]; 319 | 320 | Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length); 321 | int payloadIndex = nonSecretPayload.Length; 322 | 323 | byte[] cryptKey; 324 | byte[] authKey; 325 | //Use Random Salt to prevent pre-generated weak password attacks. 326 | using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations)) 327 | { 328 | var salt = generator.Salt; 329 | 330 | //Generate Keys 331 | cryptKey = generator.GetBytes(KeyBitSize / 8); 332 | 333 | //Create Non Secret Payload 334 | Array.Copy(salt, 0, payload, payloadIndex, salt.Length); 335 | payloadIndex += salt.Length; 336 | } 337 | 338 | //Deriving separate key, might be less efficient than using HKDF, 339 | //but now compatible with RNEncryptor which had a very similar wireformat and requires less code than HKDF. 340 | using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize / 8, Iterations)) 341 | { 342 | var salt = generator.Salt; 343 | 344 | //Generate Keys 345 | authKey = generator.GetBytes(KeyBitSize / 8); 346 | 347 | //Create Rest of Non Secret Payload 348 | Array.Copy(salt, 0, payload, payloadIndex, salt.Length); 349 | } 350 | 351 | return SimpleEncrypt(secretMessage, cryptKey, authKey, payload); 352 | } 353 | 354 | /// 355 | /// Simple Authentication (HMAC) and then Descryption (AES) of a UTF8 Message 356 | /// using keys derived from a password (PBKDF2). 357 | /// 358 | /// The encrypted message. 359 | /// The password. 360 | /// Length of the non secret payload. 361 | /// 362 | /// Decrypted Message 363 | /// 364 | /// Must have a password of minimum length;password 365 | /// 366 | /// Significantly less secure than using random binary keys. 367 | /// 368 | public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, 369 | int nonSecretPayloadLength = 0) 370 | { 371 | //User Error Checks 372 | if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength) 373 | throw new ArgumentException( 374 | String.Format("Must have a password of at least {0} characters!", MinPasswordLength), nameof(password)); 375 | 376 | if (encryptedMessage == null || encryptedMessage.Length == 0) 377 | throw new ArgumentException("Encrypted Message Required!", nameof(encryptedMessage)); 378 | 379 | var cryptSalt = new byte[SaltBitSize / 8]; 380 | var authSalt = new byte[SaltBitSize / 8]; 381 | 382 | //Grab Salt from Non-Secret Payload 383 | Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length); 384 | Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length); 385 | 386 | byte[] cryptKey; 387 | byte[] authKey; 388 | 389 | //Generate crypt key 390 | using (var generator = new Rfc2898DeriveBytes(password, cryptSalt, Iterations)) 391 | { 392 | cryptKey = generator.GetBytes(KeyBitSize / 8); 393 | } 394 | //Generate auth key 395 | using (var generator = new Rfc2898DeriveBytes(password, authSalt, Iterations)) 396 | { 397 | authKey = generator.GetBytes(KeyBitSize / 8); 398 | } 399 | 400 | return SimpleDecrypt(encryptedMessage, cryptKey, authKey, 401 | cryptSalt.Length + authSalt.Length + nonSecretPayloadLength); 402 | } 403 | } 404 | } -------------------------------------------------------------------------------- /Encryption.Framework/Algorithms/Des.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Security.Cryptography; 3 | using System.Text; 4 | 5 | namespace EasyEncryption 6 | { 7 | public abstract class DES 8 | { 9 | /// 10 | /// Encrypt text using DES algorithm. 11 | /// 12 | /// 13 | /// Symmetric key that is used for encryption and decryption. 14 | /// Initialization vector (IV) for the symmetric algorithm. 15 | /// 16 | public static string Encrypt(string text, string key, string iv) 17 | { 18 | var pText = Encoding.UTF8.GetBytes(text); 19 | using (var desCryptoService = new DESCryptoServiceProvider()) 20 | { 21 | desCryptoService.Key = Encoding.ASCII.GetBytes(key); 22 | desCryptoService.IV = Encoding.ASCII.GetBytes(iv); 23 | using (var memoryStream = new MemoryStream()) 24 | { 25 | var cryptoStream = new CryptoStream(memoryStream, desCryptoService.CreateEncryptor(), CryptoStreamMode.Write); 26 | cryptoStream.Write(pText, 0, pText.Length); 27 | cryptoStream.Close(); 28 | memoryStream.Close(); 29 | var result = Encoding.Default.GetString(memoryStream.ToArray()); 30 | return result; 31 | } 32 | } 33 | } 34 | /// 35 | /// 36 | /// 37 | /// 38 | /// Symmetric key that is used for encryption and decryption. 39 | /// Initialization vector (IV) for the symmetric algorithm. 40 | /// 41 | public static string Decrypt(string encryptedText, string key, string iv) 42 | { 43 | var encryptedTextByte = Encoding.Default.GetBytes(encryptedText); // parse text to bites array 44 | using (var desCryptoService = new DESCryptoServiceProvider()) 45 | { 46 | desCryptoService.Key = Encoding.ASCII.GetBytes(key); 47 | desCryptoService.IV = Encoding.ASCII.GetBytes(iv); 48 | var decryptor = desCryptoService.CreateDecryptor(desCryptoService.Key, desCryptoService.IV); 49 | using (var msDecrypt = new MemoryStream(encryptedTextByte)) 50 | { 51 | using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) 52 | { 53 | using (var srDecrypt = new StreamReader(csDecrypt)) 54 | { 55 | var res = srDecrypt.ReadToEnd(); 56 | return res; 57 | } 58 | } 59 | } 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Encryption.Framework/Algorithms/MD5.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Security.Cryptography; 4 | using System.Text; 5 | 6 | namespace EasyEncryption 7 | { 8 | public abstract class MD5 9 | { 10 | /// 11 | /// Returns a MD5 hash as a string 12 | /// 13 | /// String to be hashed. 14 | /// Hash as string. 15 | public static string ComputeMD5Hash(string text) 16 | { 17 | var encodedPassword = new UTF8Encoding().GetBytes(text); 18 | var hash = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword); 19 | var encoded = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower(); 20 | return encoded; 21 | } 22 | public static bool IsValidMD5(string md5) 23 | { 24 | if (md5 == null || md5.Length != 32) return false; 25 | return md5.All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Encryption.Framework/Algorithms/RSA.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Security.Cryptography; 3 | using System.Text; 4 | 5 | namespace EasyEncryption 6 | { 7 | public abstract class RSA 8 | { 9 | public static RSAKeysModel GenerateKeys(int keySize) 10 | { 11 | using (var rsa = new RSACryptoServiceProvider(keySize)) 12 | { 13 | var model = new RSAKeysModel 14 | { 15 | PrivateKey = rsa.ToXmlString(true), 16 | PublicKey = rsa.ToXmlString(false) 17 | }; 18 | return model; 19 | } 20 | 21 | } 22 | 23 | #region Encryption 24 | /// 25 | /// Encrypt data 26 | /// 27 | /// 28 | /// 29 | /// 30 | public static byte[] Encrypt(byte[] data, string publicKey) 31 | { 32 | using (var rsaCryptoServiceProvider = new RSACryptoServiceProvider()) 33 | { 34 | rsaCryptoServiceProvider.FromXmlString(publicKey); 35 | var encryptedData = rsaCryptoServiceProvider.Encrypt(data, false); 36 | return encryptedData; 37 | } 38 | } 39 | /// 40 | /// 41 | /// 42 | /// 43 | /// 44 | /// 45 | public static string Encrypt(string data, string publicKey) 46 | { 47 | var dataArray = Encoding.UTF8.GetBytes(data); 48 | var res = Convert.ToBase64String(Encrypt(dataArray, publicKey)); 49 | return res; 50 | } 51 | /// 52 | /// 53 | /// 54 | /// 55 | /// 56 | /// Base64 string result 57 | public static byte[] Decrypt(byte[] data, string privateKey) 58 | { 59 | using (var rsaCryptoServiceProvider = new RSACryptoServiceProvider()) 60 | { 61 | rsaCryptoServiceProvider.FromXmlString(privateKey); 62 | var decryptedData = rsaCryptoServiceProvider.Decrypt(data, false); 63 | return decryptedData; 64 | } 65 | } 66 | /// 67 | /// 68 | /// 69 | /// 70 | /// 71 | /// 72 | public static string Decrypt(string data, string privateKey) 73 | { 74 | var dataArray = Convert.FromBase64String(data); 75 | var res = Encoding.UTF8.GetString(Decrypt(dataArray, privateKey)); 76 | return res; 77 | } 78 | 79 | #endregion 80 | 81 | #region Sign 82 | public static string SignData(string message, string privateKey) 83 | { 84 | //// The array to store the signed message in bytes 85 | byte[] signedBytes; 86 | using (var rsa = new RSACryptoServiceProvider()) 87 | { 88 | var encoder = new UTF8Encoding(); 89 | var originalData = encoder.GetBytes(message); 90 | 91 | try 92 | { 93 | rsa.FromXmlString(privateKey); 94 | // Sign the data, using SHA512 as the hashing algorithm 95 | signedBytes = rsa.SignData(originalData, CryptoConfig.MapNameToOID("SHA512")); 96 | } 97 | catch (CryptographicException e) 98 | { 99 | Console.WriteLine(e.Message); 100 | return null; 101 | } 102 | finally 103 | { 104 | rsa.PersistKeyInCsp = false; 105 | } 106 | } 107 | //// Convert the a base64 string before returning 108 | return Convert.ToBase64String(signedBytes); 109 | } 110 | 111 | public static bool VerifyData(string originalMessage, string signedMessage, string publicKey) 112 | { 113 | 114 | using (var rsa = new RSACryptoServiceProvider()) 115 | { 116 | var bytesToVerify = Encoding.UTF8.GetBytes(originalMessage); 117 | var signedBytes = Convert.FromBase64String(signedMessage); 118 | rsa.FromXmlString(publicKey); 119 | return rsa.VerifyData(bytesToVerify, CryptoConfig.MapNameToOID("SHA512"), signedBytes); 120 | } 121 | } 122 | #endregion 123 | } 124 | 125 | public class RSAKeysModel 126 | { 127 | public string PrivateKey { get; set; } 128 | public string PublicKey { get; set; } 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /Encryption.Framework/Algorithms/SHA.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Security.Cryptography; 4 | using System.Text; 5 | 6 | namespace EasyEncryption 7 | { 8 | public abstract class SHA 9 | { 10 | public static string ComputeSHA1Hash(string stringToHash) 11 | { 12 | using (var sha1 = new SHA1Managed()) 13 | { 14 | return 15 | BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(stringToHash))) 16 | .Replace("-", string.Empty) 17 | .ToLower(); 18 | } 19 | } 20 | public static string ComputeSHA256Hash(string stringToHash) 21 | { 22 | using (var hash = SHA256.Create()) 23 | { 24 | return string.Join("", hash 25 | .ComputeHash(Encoding.UTF8.GetBytes(stringToHash)) 26 | .Select(item => item.ToString("x2"))); 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Encryption.Framework/Encryption.Framework.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netstandard2.0 4 | Library 5 | EasyEncryption 6 | EasyEncryption 7 | false 8 | 9 | 10 | 11 | all 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Encryption.Framework/Encryption.Framework.csproj.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True -------------------------------------------------------------------------------- /Encryption.Framework/Enums/CreditCardType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace EasyEncryption.Enums 8 | { 9 | public enum CreditCardType 10 | { 11 | Visa, 12 | Maestro, 13 | MasterCard, 14 | AmericanExpress, 15 | JCB 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Encryption.Framework/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("EasyEncryption")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("EasyEncryption")] 12 | [assembly: AssemblyCopyright("Copyright Artem Polischuk© 2016")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("8291c00a-362e-4409-b761-78b7dfb0904d")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Encryption.Framework/Tools/RandomGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using EasyEncryption.Enums; 7 | 8 | namespace EasyEncryption.Tools 9 | { 10 | public abstract class RandomGenerator 11 | { 12 | /// 13 | /// Generate random number 14 | /// 15 | /// number length 16 | /// 17 | public static string GenerateNumber(int numberLength) 18 | { 19 | if (numberLength < 0) 20 | { 21 | throw new ArgumentOutOfRangeException("numberLength must be >= 0"); 22 | } 23 | var random = new Random(); 24 | var output = new StringBuilder(); 25 | for (var i = 0; i < numberLength; i++) 26 | { 27 | output.Append(random.Next(0, 10)); 28 | } 29 | return output.ToString(); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Encryption.Tests/Algorithms/AesTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using NUnit.Framework; 3 | using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; 4 | 5 | namespace EasyEncryption.Tests.Algorithms 6 | { 7 | [TestFixture] 8 | [Category("AES")] 9 | public class AesTests 10 | { 11 | [Test] 12 | [TestCaseSource(nameof(AesEncryptTestCases))] 13 | public void AesEncrypt_WithValidData_ShouldReturnEncryptedString(string text, string key, string iv) 14 | { 15 | var result = AES.Encrypt(text, key, iv); 16 | Assert.IsNotNull(result); 17 | } 18 | 19 | [Test] 20 | [TestCaseSource(nameof(AesEncryptTestCases))] 21 | public void AesDecrypt_WithValidData_ShouldReturnDecryptedString(string text, string key, string iv) 22 | { 23 | var encryptString = AES.Encrypt(text, key, iv); 24 | Assert.IsNotNull(encryptString); 25 | var result = AES.Decrypt(encryptString, key, iv); 26 | Assert.IsNotNull(result); 27 | Assert.AreEqual(text, result); 28 | } 29 | 30 | private static IEnumerable AesEncryptTestCases 31 | { 32 | get 33 | { 34 | var testCaseData = new List 35 | { 36 | new TestCaseData("Test", "HNtgQw0wAbZrURKx", "VN53WuL2VkKaVTf5"), 37 | new TestCaseData("Polischuk", "iUaHmasVRY6xDIsZ", "NFmYfOnWCLFUZ0qq"), 38 | new TestCaseData("Artem", "ghrw8z1mA6kOMQrFnwxq4321", "IGwRDzLAr0BCQ6jv"), 39 | new TestCaseData("JULIK", "IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv", "IGwRDzLAr0BCQ6jv"), 40 | new TestCaseData("Тестируем разную КІРїЛЁЦґ", "IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv", "IGwRDzLAr0BCQ6jv") 41 | }; 42 | return testCaseData; 43 | } 44 | } 45 | } 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Encryption.Tests/Algorithms/AesThenHmacTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using NUnit.Framework; 5 | 6 | namespace EasyEncryption.Tests.Algorithms 7 | { 8 | [TestFixture] 9 | [Category("AESThenHmac")] 10 | public class AesThenHmacTests 11 | { 12 | #region SimpleEncryptWithPassword 13 | [Test] 14 | [TestCaseSource(nameof(SimpleEncryptWithPasswordTestCases))] 15 | public void SimpleEncryptWithPassword_WithValidData_ShouldReturnEncryptedString(string message, string password) 16 | { 17 | var result = AesThenHmac.SimpleEncryptWithPassword(message, password); 18 | Assert.IsNotNull(result); 19 | } 20 | [Test] 21 | [TestCaseSource(nameof(SimpleEncryptWithPasswordTestCases))] 22 | public void SimpleEncryptWithPassword_WithValidData_ShouldReturnEncryptedBytes(string message, string password) 23 | { 24 | var bytesMessage = Encoding.Default.GetBytes(message); 25 | var result = AesThenHmac.SimpleEncryptWithPassword(bytesMessage, password); 26 | Assert.IsNotNull(result); 27 | Assert.IsTrue(result.Length > 0); 28 | } 29 | 30 | [Test] 31 | [TestCase("Artem", "")] 32 | [TestCase("Polischuk", null)] 33 | public void SimpleEncryptWithPassword_WithInvalidPassword_ShouldReturnArgumentException(string message, string password) 34 | { 35 | try 36 | { 37 | AesThenHmac.SimpleEncryptWithPassword(message, password); 38 | Assert.Fail("Password not validated"); 39 | } 40 | catch (ArgumentException ex) 41 | { 42 | Assert.IsNotNull(ex); 43 | } 44 | } 45 | #endregion 46 | 47 | #region SimpleDecryptWithPassword 48 | [Test] 49 | [TestCaseSource(nameof(SimpleEncryptWithPasswordTestCases))] 50 | public void SimpleDecryptWithPassword_WithValidData_ShouldReturnEncryptedString(string message, string password) 51 | { 52 | var encryptString = AesThenHmac.SimpleEncryptWithPassword(message, password); 53 | var result = AesThenHmac.SimpleDecryptWithPassword(encryptString, password); 54 | Assert.IsNotNull(result); 55 | Assert.AreEqual(message, result); 56 | } 57 | [Test] 58 | [TestCaseSource(nameof(SimpleEncryptWithPasswordTestCases))] 59 | public void SimpleDecryptWithPassword_WithValidData_ShouldReturnEncryptedBytes(string message, string password) 60 | { 61 | var bytesMessage = Encoding.Default.GetBytes(message); 62 | var encryptByte = AesThenHmac.SimpleEncryptWithPassword(bytesMessage, password); 63 | var result = AesThenHmac.SimpleDecryptWithPassword(encryptByte, password); 64 | Assert.IsNotNull(result); 65 | var stringResult = Encoding.Default.GetString(result); 66 | Assert.AreEqual(message, stringResult); 67 | } 68 | 69 | [Test] 70 | [TestCase("Artem", "")] 71 | [TestCase("Polischuk", null)] 72 | public void SimpleDecryptWithPassword_WithInvalidPassword_ShouldReturnArgumentException(string message, string password) 73 | { 74 | try 75 | { 76 | AesThenHmac.SimpleDecryptWithPassword(message, password); 77 | Assert.Fail("Password not validated"); 78 | } 79 | catch (ArgumentException ex) 80 | { 81 | Assert.IsNotNull(ex); 82 | } 83 | } 84 | #endregion 85 | 86 | #region SimpleEncrypt 87 | [Test] 88 | [TestCaseSource(nameof(SimpleEncryptTestCases))] 89 | public void SimpleEncrypt_WithValidData_ShouldReturnEncryptedString(byte[] message, byte[] password, byte[] authKey) 90 | { 91 | var result = AesThenHmac.SimpleEncrypt(message, password, authKey); 92 | Assert.IsNotNull(result); 93 | } 94 | 95 | public void SimpleEncrypt_WithInvalidCryptKeyLength_ShouldReturnArgumentException() 96 | { 97 | try 98 | { 99 | AesThenHmac.SimpleEncrypt(new byte[15], new byte[4], new byte[32]); 100 | Assert.Fail(); 101 | } 102 | catch (ArgumentException ex) 103 | { 104 | Assert.IsNotNull(ex); 105 | Assert.AreEqual(ex.Message, "Key needs to be 256 bit!\r\nParameter name: cryptKey"); 106 | } 107 | } 108 | [Test] 109 | public void SimpleEncrypt_WithInvalidAuthKeyLength_ShouldReturnArgumentException() 110 | { 111 | try 112 | { 113 | AesThenHmac.SimpleEncrypt(new byte[15], new byte[32], new byte[45]); 114 | Assert.Fail(); 115 | } 116 | catch (ArgumentException ex) 117 | { 118 | Assert.IsNotNull(ex); 119 | Assert.AreEqual(ex.Message, "Key needs to be 256 bit!\r\nParameter name: authKey"); 120 | } 121 | } 122 | #endregion 123 | 124 | #region SimpleDecrypt 125 | [Test] 126 | [TestCaseSource(nameof(SimpleEncryptTestCases))] 127 | public void SimpleDecrypt_WithValidData_ShouldReturnEncryptedBytes(byte[] message, byte[] password, byte[] authKey) 128 | { 129 | var encryptByte = AesThenHmac.SimpleEncrypt(message, password, authKey); 130 | var result = AesThenHmac.SimpleDecrypt(encryptByte, password, authKey); 131 | Assert.IsNotNull(result); 132 | Assert.AreEqual(message, result); 133 | } 134 | 135 | [Test] 136 | public void SimpleDecrypt_WithInvalidCryptKeyLength_ShouldReturnArgumentException() 137 | { 138 | try 139 | { 140 | var encryptByte = AesThenHmac.SimpleEncrypt(new byte[15], new byte[32], new byte[32]); 141 | AesThenHmac.SimpleDecrypt(encryptByte, new byte[15], new byte[15]); 142 | Assert.Fail(); 143 | } 144 | catch (ArgumentException ex) 145 | { 146 | Assert.IsNotNull(ex); 147 | Assert.AreEqual(ex.Message, "CryptKey needs to be 256 bit!\r\nParameter name: cryptKey"); 148 | } 149 | } 150 | [Test] 151 | public void SimpleDecrypt_WithInvalidAuthKeyLength_ShouldReturnArgumentException() 152 | { 153 | try 154 | { 155 | var encryptByte = AesThenHmac.SimpleEncrypt(new byte[15], new byte[32], new byte[32]); 156 | AesThenHmac.SimpleDecrypt(encryptByte, new byte[32], new byte[15]); 157 | Assert.Fail(); 158 | } 159 | catch (ArgumentException ex) 160 | { 161 | Assert.IsNotNull(ex); 162 | Assert.AreEqual(ex.Message, "AuthKey needs to be 256 bit!\r\nParameter name: authKey"); 163 | } 164 | } 165 | #endregion 166 | 167 | #region TestCases 168 | private static IEnumerable SimpleEncryptTestCases 169 | { 170 | get 171 | { 172 | var testCaseData = new List 173 | { 174 | new TestCaseData(Encoding.UTF8.GetBytes("Test"), 175 | Encoding.UTF8.GetBytes("IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv"), 176 | Encoding.UTF8.GetBytes("IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv")), 177 | new TestCaseData(Encoding.UTF8.GetBytes("Polischuk"), 178 | Encoding.UTF8.GetBytes("IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv"), 179 | Encoding.UTF8.GetBytes("IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv")), 180 | new TestCaseData(Encoding.UTF8.GetBytes("Artem"), 181 | Encoding.UTF8.GetBytes("IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv"), 182 | Encoding.UTF8.GetBytes("IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv")), 183 | new TestCaseData(Encoding.UTF8.GetBytes("Тестируем разную КІРїЛЁЦґ"), 184 | Encoding.UTF8.GetBytes("IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv"), 185 | Encoding.UTF8.GetBytes("IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv")) 186 | }; 187 | return testCaseData; 188 | } 189 | } 190 | private static IEnumerable SimpleEncryptWithPasswordTestCases 191 | { 192 | get 193 | { 194 | var testCaseData = new List 195 | { 196 | new TestCaseData("Test", "HNtgQw0wAbZrURKx"), 197 | new TestCaseData("Polischuk", "iUaHmasVRY6xDIsZ"), 198 | new TestCaseData("Artem", "ghrw8z1mA6kOMQrFnwxq4321"), 199 | new TestCaseData("JULIK", "IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv"), 200 | new TestCaseData("Тестируем разную КІРїЛЁЦґ", "IGwRDzLAr0BCQ6jvIGwRDzLAr0BCQ6jv"), 201 | new TestCaseData("JULIK", "1234"), 202 | new TestCaseData("JULIK", "12345"), 203 | new TestCaseData("JULIK", "123") 204 | }; 205 | return testCaseData; 206 | } 207 | } 208 | #endregion 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /Encryption.Tests/Algorithms/DesTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using NUnit.Framework; 3 | using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; 4 | 5 | namespace EasyEncryption.Tests.Algorithms 6 | { 7 | [TestFixture] 8 | [Category("DES")] 9 | public class DesTests 10 | { 11 | [Test] 12 | [TestCaseSource(nameof(DesEncryptTestCases))] 13 | public void DesEncrypt_WithValidData_ShouldReturnEncryptedString(string text, string key, string iv) 14 | { 15 | var result = DES.Encrypt(text, key, iv); 16 | Assert.IsNotNull(result); 17 | } 18 | 19 | [Test] 20 | [TestCaseSource(nameof(DesEncryptTestCases))] 21 | public void DesDecrypt_WithValidData_ShouldReturnDecryptedString(string text, string key, string iv) 22 | { 23 | var encryptString = DES.Encrypt(text, key, iv); 24 | Assert.IsNotNull(encryptString); 25 | var result = DES.Decrypt(encryptString, key, iv); 26 | Assert.IsNotNull(result); 27 | Assert.AreEqual(text, result); 28 | } 29 | 30 | private static IEnumerable DesEncryptTestCases 31 | { 32 | get 33 | { 34 | var testCaseData = new List 35 | { 36 | new TestCaseData("Test", "bZr2URKx", "HNtgQw0w"), 37 | new TestCaseData("Polischuk", "iUaHmasV", "NFmYfOnW"), 38 | new TestCaseData("Artem", "ghrw8z1m", "IGwRDzLA"), 39 | new TestCaseData("JULIK", "IGwRDzLA", "r0BCQ6jv"), 40 | new TestCaseData("Тестируем разную КІРїЛЁЦґ", "CQ6jvIGw", "Ar0BQ6jv") 41 | }; 42 | return testCaseData; 43 | } 44 | } 45 | } 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Encryption.Tests/Algorithms/MD5Tests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using NUnit.Framework; 4 | 5 | namespace EasyEncryption.Tests.Algorithms 6 | { 7 | [TestFixture] 8 | [Category("MD5")] 9 | public class MD5Tests 10 | { 11 | 12 | #region CalculateMD5Hash 13 | [Test] 14 | [TestCaseSource(nameof(CalculateMD5HashTestCases))] 15 | public void CalculateMD5Hash_WithValidData_ShouldReturnMD5String(string text) 16 | { 17 | var result = MD5.ComputeMD5Hash(text); 18 | Assert.IsNotNull(result); 19 | Console.WriteLine(result); 20 | } 21 | #endregion 22 | 23 | #region IsValidMD5 24 | [Test] 25 | [TestCaseSource(nameof(CalculateMD5HashTestCases))] 26 | public void IsValidMD5_WithInvalidMD5_ShouldReturnFalse(string text) 27 | { 28 | var md5Hash = "012345"; 29 | var result = MD5.IsValidMD5(md5Hash); 30 | Assert.False(result); 31 | } 32 | 33 | [Test] 34 | [TestCaseSource(nameof(CalculateMD5HashTestCases))] 35 | public void IsValidMD5_WithValidMD5_ShouldReturnTrue(string text) 36 | { 37 | var md5Hash = MD5.ComputeMD5Hash(text); 38 | Assert.IsNotNull(md5Hash); 39 | var result = MD5.IsValidMD5(md5Hash); 40 | Assert.True(result); 41 | } 42 | #endregion 43 | 44 | private static IEnumerable CalculateMD5HashTestCases 45 | { 46 | get 47 | { 48 | var testCaseData = new List 49 | { 50 | new TestCaseData("Test"), 51 | new TestCaseData("Polischuk"), 52 | new TestCaseData("Artem"), 53 | new TestCaseData("JULIK"), 54 | new TestCaseData("Тестируем разную КІРїЛЁЦґ") 55 | }; 56 | return testCaseData; 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Encryption.Tests/Algorithms/RSATests.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using NUnit.Framework; 3 | 4 | namespace EasyEncryption.Tests.Algorithms 5 | { 6 | [TestFixture] 7 | [Category("RSA")] 8 | public class RSATests 9 | { 10 | [Test] 11 | public void GenerateRSAKeys() 12 | { 13 | var keys = RSA.GenerateKeys(2048); 14 | Assert.IsNotNull(keys); 15 | Assert.IsNotNull(keys.PublicKey); 16 | Assert.IsNotNull(keys.PrivateKey); 17 | } 18 | [Test] 19 | public void Encrypt_WithValidData_ShouldReturnEncryptedBytes() 20 | { 21 | var keys = RSA.GenerateKeys(2048); 22 | var encryptedData = RSA.Encrypt(Encoding.UTF8.GetBytes("test"), keys.PrivateKey); 23 | Assert.IsNotNull(encryptedData); 24 | } 25 | [Test] 26 | public void Decrypt_WithValidData_ShouldReturnDecryptedBytes() 27 | { 28 | var keys = RSA.GenerateKeys(2048); 29 | var data = Encoding.UTF8.GetBytes("test"); 30 | var encryptedData = RSA.Encrypt(data, keys.PublicKey); 31 | Assert.IsNotNull(encryptedData); 32 | var decryptedData = RSA.Decrypt(encryptedData, keys.PrivateKey); 33 | Assert.AreEqual(data, decryptedData); 34 | } 35 | [Test] 36 | public void Encrypt_WithValidData_ShouldReturnEncryptedString() 37 | { 38 | var keys = RSA.GenerateKeys(2048); 39 | var encryptedData = RSA.Encrypt("test", keys.PrivateKey); 40 | Assert.IsNotNull(encryptedData); 41 | } 42 | [Test] 43 | public void Decrypt_WithValidData_ShouldReturnDecryptedString() 44 | { 45 | var keys = RSA.GenerateKeys(2048); 46 | var data = "test"; 47 | var encryptedData = RSA.Encrypt(data, keys.PublicKey); 48 | Assert.IsNotNull(encryptedData); 49 | var decryptedData = RSA.Decrypt(encryptedData, keys.PrivateKey); 50 | Assert.AreEqual(data, decryptedData); 51 | } 52 | [Test] 53 | public void SignData_WithValidData_ShouldReturnSignString() 54 | { 55 | var keys = RSA.GenerateKeys(2048); 56 | var encryptedData = RSA.Encrypt("test", keys.PrivateKey); 57 | Assert.IsNotNull(encryptedData); 58 | } 59 | [Test] 60 | public void VerifyData_WithValidData_ShouldReturnTrue() 61 | { 62 | var keys = RSA.GenerateKeys(2048); 63 | var data = "test"; 64 | var signData = RSA.SignData(data, keys.PrivateKey); 65 | Assert.IsNotNull(signData); 66 | var isCorrect = RSA.VerifyData(data, signData, keys.PublicKey); 67 | Assert.IsTrue(isCorrect); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Encryption.Tests/Algorithms/SHATests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using NUnit.Framework; 7 | 8 | namespace EasyEncryption.Tests.Algorithms 9 | { 10 | [TestFixture] 11 | [Category("SHA")] 12 | public class SHATests 13 | { 14 | 15 | [Test] 16 | [TestCaseSource(nameof(ComputeHashTestCases))] 17 | public void ComputeSHA1Hash_WithValidData_ShouldReturnSHAString(string text) 18 | { 19 | var result = EasyEncryption.SHA.ComputeSHA1Hash(text); 20 | Assert.IsNotNull(result); 21 | Console.WriteLine(result); 22 | } 23 | 24 | [Test] 25 | [TestCaseSource(nameof(ComputeHashTestCases))] 26 | public void ComputeSHA256Hash_WithValidData_ShouldReturnSHAString(string text) 27 | { 28 | var result = EasyEncryption.SHA.ComputeSHA256Hash(text); 29 | Assert.IsNotNull(result); 30 | Console.WriteLine(result); 31 | } 32 | private static IEnumerable ComputeHashTestCases 33 | { 34 | get 35 | { 36 | var testCaseData = new List 37 | { 38 | new TestCaseData("Test"), 39 | new TestCaseData("Polischuk"), 40 | new TestCaseData("Artem"), 41 | new TestCaseData("JULIK"), 42 | new TestCaseData("Тестируем разную КІРїЛЁЦґ") 43 | }; 44 | return testCaseData; 45 | } 46 | } 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Encryption.Tests/Encryption.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | EasyEncryption.Tests 4 | EasyEncryption.Tests 5 | 6 | 7 | net6.0 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | all 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | False 38 | 39 | 40 | False 41 | 42 | 43 | False 44 | 45 | 46 | False 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /Encryption.Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("Encryption.Tests")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("Encryption.Tests")] 12 | [assembly: AssemblyCopyright("Copyright © 2016")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("4c30f616-7750-4d24-a3c3-2fef8dc3e5d4")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Encryption.Tests/Tools/RandomGeneratorTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using EasyEncryption.Enums; 7 | using EasyEncryption.Tools; 8 | using NUnit.Framework; 9 | 10 | namespace EasyEncryption.Tests.Tools 11 | { 12 | [TestFixture] 13 | [Category("RandomGenerator")] 14 | public class RandomGeneratorTests 15 | { 16 | [Test] 17 | [TestCaseSource(nameof(GenerateNumberTestCases))] 18 | public void GenerateNumber_WithCorrectNumberLength_ShouldReturnRandomNumberString(int numberLength) 19 | { 20 | var result = RandomGenerator.GenerateNumber(numberLength); 21 | Assert.IsNotNull(result); 22 | Assert.AreEqual(numberLength, result.Length); 23 | } 24 | 25 | [Test] 26 | public void GenerateNumber_NumberLengthLessThan0_ShouldReturnArgumentOutOfRangeException() 27 | { 28 | try 29 | { 30 | RandomGenerator.GenerateNumber(-1); 31 | } 32 | catch (ArgumentOutOfRangeException) 33 | { 34 | } 35 | catch (Exception ex) 36 | { 37 | Assert.Fail(ex.Message); 38 | } 39 | } 40 | 41 | private static IEnumerable GenerateNumberTestCases 42 | { 43 | get 44 | { 45 | var testCaseData = new List 46 | { 47 | new TestCaseData(1), 48 | new TestCaseData(2), 49 | new TestCaseData(3), 50 | new TestCaseData(4), 51 | new TestCaseData(5), 52 | new TestCaseData(6), 53 | new TestCaseData(7), 54 | new TestCaseData(15) 55 | }; 56 | return testCaseData; 57 | } 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /Encryption.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {83F457EF-35E6-4C46-9565-3F86F7DD74CA} 8 | Library 9 | Properties 10 | Encryption.Core 11 | Encryption.Core 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Artem Polischuk 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Encryption.Core")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Encryption")] 13 | [assembly: AssemblyCopyright("Copyright Artem Polischuk © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("83f457ef-35e6-4c46-9565-3f86f7dd74ca")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EasyEncryption 2 | Several encryption algorithms implemented in this library such as: AES, DES, AesThenHmac, MD5, SHA1, SHA256 3 | 4 | ## Usage 5 | Install from the package manager console: 6 | 7 | PM> Install-Package EasyEncryption 8 | 9 | ## Manual 10 | [Goto wiki](https://github.com/polischuk/EasyEncryption/wiki/Usage-wiki) 11 | --------------------------------------------------------------------------------