| | 1 | | #if CRYPTO_NATIVE |
| | 2 | | using System.Runtime.InteropServices; |
| | 3 | | using System.Security.Cryptography; |
| | 4 | | using System.Text; |
| | 5 | | using Konscious.Security.Cryptography; |
| | 6 | | using Org.BouncyCastle.Crypto.Parameters; |
| | 7 | |
|
| | 8 | | namespace NLightning.Infrastructure.Crypto.Providers.Native; |
| | 9 | |
|
| | 10 | | using Ciphers; |
| | 11 | | using Constants; |
| | 12 | | using Domain.Crypto.Constants; |
| | 13 | |
|
| | 14 | | using Interfaces; |
| | 15 | |
|
| | 16 | | internal sealed partial class NativeCryptoProvider: ICryptoProvider |
| | 17 | | { |
| 3558 | 18 | | private readonly IncrementalHash _sha256 = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); |
| | 19 | |
|
| | 20 | | public void Sha256Init(IntPtr state) |
| | 21 | | { |
| | 22 | | // There's no need to initialize it here, since if it was used before, it was already reseted |
| 44000 | 23 | | } |
| | 24 | |
|
| | 25 | | public void Sha256Update(IntPtr state, ReadOnlySpan<byte> data) |
| | 26 | | { |
| 42046 | 27 | | _sha256.AppendData(data.ToArray()); |
| 42046 | 28 | | } |
| | 29 | |
|
| | 30 | | public void Sha256Final(IntPtr state, Span<byte> result) |
| | 31 | | { |
| 40836 | 32 | | _ = _sha256.GetHashAndReset(result); |
| 40836 | 33 | | } |
| | 34 | |
|
| | 35 | | public int AeadChaCha20Poly1305IetfEncrypt(ReadOnlySpan<byte> key, ReadOnlySpan<byte> publicNonce, |
| | 36 | | ReadOnlySpan<byte> secureNonce, ReadOnlySpan<byte> authenticationData, |
| | 37 | | ReadOnlySpan<byte> message, Span<byte> cipher, out long cipherLength) |
| | 38 | | { |
| | 39 | | try |
| | 40 | | { |
| 4072 | 41 | | using var chaCha20Poly1305 = new ChaCha20Poly1305(key); |
| | 42 | |
|
| 4072 | 43 | | chaCha20Poly1305.Encrypt(publicNonce, message, cipher[..message.Length], |
| 4072 | 44 | | cipher[message.Length..(message.Length + CryptoConstants.CHACHA20_POLY1305_TAG_LEN) |
| 4072 | 45 | | authenticationData); |
| | 46 | |
|
| 4072 | 47 | | cipherLength = message.Length + CryptoConstants.CHACHA20_POLY1305_TAG_LEN; |
| | 48 | |
|
| 4072 | 49 | | return 0; |
| | 50 | | } |
| 0 | 51 | | catch (Exception e) |
| | 52 | | { |
| 0 | 53 | | throw new CryptographicException("Encryption failed.", e); |
| | 54 | | } |
| 4072 | 55 | | } |
| | 56 | |
|
| | 57 | | public int AeadChaCha20Poly1305IetfDecrypt(ReadOnlySpan<byte> key, ReadOnlySpan<byte> publicNonce, |
| | 58 | | ReadOnlySpan<byte> secureNonce, ReadOnlySpan<byte> authenticationData, |
| | 59 | | ReadOnlySpan<byte> cipher, Span<byte> clearTextMessage, |
| | 60 | | out long messageLength) |
| | 61 | | { |
| | 62 | | try |
| | 63 | | { |
| 4068 | 64 | | using var chaCha20Poly1305 = new ChaCha20Poly1305(key); |
| | 65 | |
|
| 4068 | 66 | | var messageLengthWithoutTag = cipher.Length - CryptoConstants.CHACHA20_POLY1305_TAG_LEN; |
| | 67 | |
|
| 4068 | 68 | | chaCha20Poly1305.Decrypt(publicNonce, cipher[..messageLengthWithoutTag], cipher[messageLengthWithoutTag..], |
| 4068 | 69 | | clearTextMessage[..messageLengthWithoutTag], authenticationData); |
| | 70 | |
|
| 4060 | 71 | | messageLength = messageLengthWithoutTag; |
| | 72 | |
|
| 4060 | 73 | | return 0; |
| | 74 | | } |
| 8 | 75 | | catch (Exception e) |
| | 76 | | { |
| 8 | 77 | | throw new CryptographicException("Decryption failed.", e); |
| | 78 | | } |
| 4060 | 79 | | } |
| | 80 | |
|
| | 81 | | public IntPtr MemoryAlloc(ulong size) |
| | 82 | | { |
| 3590 | 83 | | return Marshal.AllocHGlobal((IntPtr)size); |
| | 84 | | } |
| | 85 | |
|
| | 86 | | public int MemoryLock(IntPtr addr, ulong len) |
| | 87 | | { |
| 426 | 88 | | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| | 89 | | { |
| 0 | 90 | | return VirtualLock(addr, len) ? 0 : Marshal.GetLastWin32Error(); |
| | 91 | | } |
| | 92 | |
|
| | 93 | | // TODO: Log somewhere that Memory lock is not available on this platform. |
| | 94 | | // but return success so the process can continue |
| 426 | 95 | | return 0; |
| | 96 | | } |
| | 97 | |
|
| | 98 | | public void MemoryUnlock(IntPtr addr, ulong len) |
| | 99 | | { |
| 378 | 100 | | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| | 101 | | { |
| 0 | 102 | | _ = VirtualUnlock(addr, len); |
| | 103 | | } |
| | 104 | | // else |
| | 105 | | // { |
| | 106 | | // TODO: Log somewhere that Memory unlock is not available on this platform. |
| | 107 | | // but don't fail so the process can continue |
| | 108 | | // } |
| 378 | 109 | | } |
| | 110 | |
|
| | 111 | | public int AeadXChaCha20Poly1305IetfEncrypt(ReadOnlySpan<byte> key, ReadOnlySpan<byte> nonce, |
| | 112 | | ReadOnlySpan<byte> additionalData, ReadOnlySpan<byte> plainText, |
| | 113 | | Span<byte> cipherText, out long cipherTextLength) |
| | 114 | | { |
| | 115 | | try |
| | 116 | | { |
| 0 | 117 | | if (key.Length != XChaCha20Constants.KEY_SIZE) |
| 0 | 118 | | throw new ArgumentException("Key must be 32 bytes", nameof(key)); |
| 0 | 119 | | if (nonce.Length != XChaCha20Constants.NONCE_SIZE) |
| 0 | 120 | | throw new ArgumentException("Nonce must be 24 bytes", nameof(nonce)); |
| | 121 | |
|
| | 122 | | // subkey (hchacha20(key, nonce[0:15])) |
| 0 | 123 | | Span<byte> subkey = stackalloc byte[XChaCha20Constants.SUBKEY_SIZE]; |
| 0 | 124 | | HChaCha20.CreateSubkey(key, nonce, subkey); |
| | 125 | |
|
| | 126 | | // nonce (chacha20_nonce = "\x00\x00\x00\x00" + nonce[16:23]) |
| 0 | 127 | | Span<byte> chaChaNonce = stackalloc byte[12]; |
| 0 | 128 | | "\0\0\0\0"u8.ToArray().CopyTo(chaChaNonce[..4]); |
| 0 | 129 | | nonce[16..].CopyTo(chaChaNonce[4..]); |
| | 130 | |
|
| | 131 | | // chacha20_encrypt(subkey, chacha20_nonce, plaintext, blk_ctr) |
| 0 | 132 | | var keyMaterial = new KeyParameter(subkey.ToArray()); |
| 0 | 133 | | var parameters = new ParametersWithIV(keyMaterial, chaChaNonce.ToArray()); |
| | 134 | |
|
| 0 | 135 | | var chaCha20Poly1305 = new Org.BouncyCastle.Crypto.Modes.ChaCha20Poly1305(); |
| 0 | 136 | | chaCha20Poly1305.Init(true, parameters); |
| | 137 | |
|
| | 138 | | // if additional data present |
| 0 | 139 | | if (additionalData != Span<byte>.Empty) |
| | 140 | | { |
| 0 | 141 | | chaCha20Poly1305.ProcessAadBytes(additionalData.ToArray(), 0, additionalData.Length); |
| | 142 | | } |
| | 143 | |
|
| 0 | 144 | | var cipherTextBytes = new byte[cipherText.Length]; |
| 0 | 145 | | cipherTextLength = chaCha20Poly1305.ProcessBytes(plainText.ToArray(), 0, plainText.Length, |
| 0 | 146 | | cipherTextBytes, 0); |
| 0 | 147 | | chaCha20Poly1305.DoFinal(cipherTextBytes, (int)cipherTextLength); |
| | 148 | |
|
| 0 | 149 | | cipherTextBytes.CopyTo(cipherText); |
| 0 | 150 | | cipherTextLength = cipherTextBytes.Length; |
| | 151 | |
|
| 0 | 152 | | return 0; |
| | 153 | | } |
| 0 | 154 | | catch (Exception e) |
| | 155 | | { |
| 0 | 156 | | throw new CryptographicException("Encryption failed.", e); |
| | 157 | | } |
| 0 | 158 | | } |
| | 159 | |
|
| | 160 | | public int AeadXChaCha20Poly1305IetfDecrypt(ReadOnlySpan<byte> key, ReadOnlySpan<byte> nonce, |
| | 161 | | ReadOnlySpan<byte> additionalData, ReadOnlySpan<byte> cipherText, |
| | 162 | | Span<byte> plainText, out long plainTextLength) |
| | 163 | | { |
| | 164 | | try |
| | 165 | | { |
| 0 | 166 | | if (key.Length != XChaCha20Constants.KEY_SIZE) |
| 0 | 167 | | throw new ArgumentException("Key must be 32 bytes", nameof(key)); |
| 0 | 168 | | if (nonce.Length != XChaCha20Constants.NONCE_SIZE) |
| 0 | 169 | | throw new ArgumentException("Nonce must be 24 bytes", nameof(nonce)); |
| | 170 | |
|
| | 171 | | // subkey (hchacha20(key, nonce[0:15])) |
| 0 | 172 | | Span<byte> subkey = stackalloc byte[XChaCha20Constants.SUBKEY_SIZE]; |
| 0 | 173 | | HChaCha20.CreateSubkey(key, nonce, subkey); |
| | 174 | |
|
| | 175 | | // nonce (chacha20_nonce = "\x00\x00\x00\x00" + nonce[16:23]) |
| 0 | 176 | | Span<byte> chaChaNonce = stackalloc byte[12]; |
| 0 | 177 | | "\0\0\0\0"u8.ToArray().CopyTo(chaChaNonce[..4]); |
| 0 | 178 | | nonce[16..].CopyTo(chaChaNonce[4..]); |
| | 179 | |
|
| | 180 | | // chacha20_encrypt(subkey, chacha20_nonce, plaintext, blk_ctr) |
| 0 | 181 | | var keyMaterial = new KeyParameter(subkey.ToArray()); |
| 0 | 182 | | var parameters = new ParametersWithIV(keyMaterial, chaChaNonce.ToArray()); |
| | 183 | |
|
| 0 | 184 | | var chaCha20Poly1305 = new Org.BouncyCastle.Crypto.Modes.ChaCha20Poly1305(); |
| 0 | 185 | | chaCha20Poly1305.Init(false, parameters); |
| | 186 | |
|
| | 187 | | // if additional data present |
| 0 | 188 | | if (additionalData != Span<byte>.Empty) |
| | 189 | | { |
| 0 | 190 | | chaCha20Poly1305.ProcessAadBytes(additionalData.ToArray(), 0, additionalData.Length); |
| | 191 | | } |
| | 192 | |
|
| 0 | 193 | | var plainTextBytes = new byte[plainText.Length]; |
| 0 | 194 | | plainTextLength = chaCha20Poly1305.ProcessBytes(cipherText.ToArray(), 0, cipherText.Length, |
| 0 | 195 | | plainTextBytes, 0); |
| 0 | 196 | | chaCha20Poly1305.DoFinal(plainTextBytes, (int)plainTextLength); |
| | 197 | |
|
| 0 | 198 | | plainTextBytes.CopyTo(plainText); |
| 0 | 199 | | plainTextLength = plainTextBytes.Length; |
| | 200 | |
|
| 0 | 201 | | return 0; |
| | 202 | | } |
| 0 | 203 | | catch (Exception e) |
| | 204 | | { |
| 0 | 205 | | throw new CryptographicException("Decryption failed.", e); |
| | 206 | | } |
| 0 | 207 | | } |
| | 208 | |
|
| | 209 | | public int DeriveKeyFromPasswordUsingArgon2I(Span<byte> key, string password, ReadOnlySpan<byte> salt, ulong opsLimi |
| | 210 | | { |
| 0 | 211 | | using var argon2 = new Argon2id(Encoding.UTF8.GetBytes(password)); |
| 0 | 212 | | argon2.Salt = salt.ToArray(); |
| 0 | 213 | | argon2.Iterations = (int)opsLimit; |
| 0 | 214 | | argon2.MemorySize = (int)(memLimit / 1024); // memLimit is in bytes, MemorySize is in KB |
| 0 | 215 | | argon2.DegreeOfParallelism = Environment.ProcessorCount; |
| | 216 | |
|
| 0 | 217 | | var derived = argon2.GetBytes(key.Length); |
| 0 | 218 | | derived.CopyTo(key); |
| 0 | 219 | | return 0; |
| 0 | 220 | | } |
| | 221 | |
|
| | 222 | | public void RandomBytes(Span<byte> buffer) |
| | 223 | | { |
| 0 | 224 | | new Random().NextBytes(buffer); |
| 0 | 225 | | } |
| | 226 | |
|
| | 227 | | public void MemoryFree(IntPtr ptr) |
| | 228 | | { |
| 3518 | 229 | | Marshal.FreeHGlobal(ptr); |
| 3518 | 230 | | } |
| | 231 | |
|
| | 232 | | public void MemoryZero(IntPtr ptr, ulong len) |
| | 233 | | { |
| | 234 | | unsafe |
| | 235 | | { |
| 8046 | 236 | | var span = new Span<byte>((void*)ptr, (int)len); |
| 8046 | 237 | | CryptographicOperations.ZeroMemory(span); |
| | 238 | | } |
| 8046 | 239 | | } |
| | 240 | |
|
| | 241 | | // P/Invoke for Windows VirtualLock and VirtualUnlock |
| | 242 | | [LibraryImport("kernel32.dll", SetLastError = true)] |
| | 243 | | [return: MarshalAs(UnmanagedType.Bool)] |
| | 244 | | private static partial bool VirtualLock(IntPtr lpAddress, ulong dwSize); |
| | 245 | |
|
| | 246 | | [LibraryImport("kernel32.dll", SetLastError = true)] |
| | 247 | | [return: MarshalAs(UnmanagedType.Bool)] |
| | 248 | | private static partial bool VirtualUnlock(IntPtr lpAddress, ulong dwSize); |
| | 249 | |
|
| | 250 | | public void Dispose() |
| | 251 | | { |
| 3460 | 252 | | _sha256.Dispose(); |
| 3460 | 253 | | } |
| | 254 | | } |
| | 255 | | #endif |