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