aboutsummaryrefslogtreecommitdiff
path: root/wrappers/dotnet/VNLib.Utils.Cryptography.Noscrypt/src/NostrCrypto.cs
blob: c4bef05753efc517bf1eb31080feedc0def123ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Copyright (C) 2024 Vaughn Nugent
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

using System;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;

using VNLib.Utils.Cryptography.Noscrypt.@internal;
using static VNLib.Utils.Cryptography.Noscrypt.LibNoscrypt;

using NCResult = System.Int64;

namespace VNLib.Utils.Cryptography.Noscrypt
{

    /// <summary>
    /// A default implementation of the <see cref="INostrCrypto"/> interface
    /// </summary>
    /// <param name="context">The initialized library context</param>
    public unsafe class NostrCrypto(NCContext context, bool ownsContext) : VnDisposeable, INostrCrypto
    {
        /// <summary>
        /// Gets the underlying library context.
        /// </summary>
        public NCContext Context => context;

        private ref readonly FunctionTable Functions => ref context.Library.Functions;

        ///<inheritdoc/>
        public void DecryptNip44(
            ref readonly NCSecretKey secretKey, 
            ref readonly NCPublicKey publicKey, 
            ref readonly byte nonce32, 
            ref readonly byte cipherText, 
            ref byte plainText,
            uint size
        )
        {
            Check();

            ThrowIfNullRef(in nonce32, nameof(nonce32));
        
            fixed (NCSecretKey* pSecKey = &secretKey)
            fixed (NCPublicKey* pPubKey = &publicKey)
            fixed (byte* pCipherText = &cipherText, pTextPtr = &plainText, pNonce = &nonce32)
            {
                NCEncryptionArgs data = new()
                {
                     //Set input data to the cipher text to decrypt and the output data to the plaintext buffer
                    dataSize = size,    
                    hmacKeyOut32 = null,
                    inputData = pCipherText,
                    outputData = pTextPtr,
                    nonce32 = pNonce,
                    version = NC_ENC_VERSION_NIP44
                };

                NCResult result = Functions.NCDecrypt.Invoke(context.DangerousGetHandle(), pSecKey, pPubKey, &data);
                NCUtil.CheckResult<FunctionTable.NCDecryptDelegate>(result, true);
            }
        }

        ///<inheritdoc/>
        public void EncryptNip44(
            ref readonly NCSecretKey secretKey,
            ref readonly NCPublicKey publicKey,
            ref readonly byte nonce32,
            ref readonly byte plainText,
            ref byte cipherText,
            uint size,
            ref byte hmackKeyOut32
        )
        {
            Check();

            ThrowIfNullRef(in nonce32, nameof(nonce32));
           
            fixed (NCSecretKey* pSecKey = &secretKey)
            fixed (NCPublicKey* pPubKey = &publicKey)
            fixed (byte* pCipherText = &cipherText, pTextPtr = &plainText, pHmacKeyOut = &hmackKeyOut32, pNonce = &nonce32)
            {
                NCEncryptionArgs data = new()
                {
                    nonce32 = pNonce,
                    hmacKeyOut32 = pHmacKeyOut,
                    //Set input data to the plaintext to encrypt and the output data to the cipher text buffer
                    inputData = pTextPtr,
                    outputData = pCipherText,
                    dataSize = size,
                    version = NC_ENC_VERSION_NIP44  //Force nip44 encryption
                };

                NCResult result = Functions.NCEncrypt.Invoke(context.DangerousGetHandle(), pSecKey, pPubKey, &data);
                NCUtil.CheckResult<FunctionTable.NCEncryptDelegate>(result, true);
            }
        }

        ///<inheritdoc/>
        public void GetPublicKey(ref readonly NCSecretKey secretKey, ref NCPublicKey publicKey)
        {
            Check();

            fixed (NCSecretKey* pSecKey = &secretKey)
            fixed (NCPublicKey* pPubKey = &publicKey)
            {
                NCResult result = Functions.NCGetPublicKey.Invoke(context.DangerousGetHandle(), pSecKey, pPubKey);
                NCUtil.CheckResult<FunctionTable.NCGetPublicKeyDelegate>(result, true);
            }
        }

        ///<inheritdoc/>
        public void SignData(
            ref readonly NCSecretKey secretKey, 
            ref readonly byte random32, 
            ref readonly byte data,
            uint dataSize, 
            ref byte sig64
        )
        {
            Check();
       
            fixed (NCSecretKey* pSecKey = &secretKey)
            fixed (byte* pData = &data, pSig = &sig64, pRandom = &random32)
            {
                NCResult result = Functions.NCSignData.Invoke(
                    ctx: context.DangerousGetHandle(), 
                    sk: pSecKey, 
                    random32: pRandom, 
                    data: pData, 
                    dataSize, 
                    sig64: pSig
                );

                NCUtil.CheckResult<FunctionTable.NCSignDataDelegate>(result, true);
            }
        }

        ///<inheritdoc/>
        public bool ValidateSecretKey(ref readonly NCSecretKey secretKey)
        {
            Check();

            IntPtr libCtx = context.DangerousGetHandle();

            fixed (NCSecretKey* pSecKey = &secretKey)
            {
                /*
                 * Validate should return a result of 1 if the secret key is valid
                 * or a 0 if it is not.
                 */
                NCResult result = Functions.NCValidateSecretKey.Invoke(libCtx, pSecKey);
                NCUtil.CheckResult<FunctionTable.NCValidateSecretKeyDelegate>(result, false);

                return result == NC_SUCCESS;
            }
        }

        ///<inheritdoc/>
        public bool VerifyData(
            ref readonly NCPublicKey pubKey, 
            ref readonly byte data,
            uint dataSize, 
            ref readonly byte sig64
        )
        {
            Check();
            
            fixed(NCPublicKey* pPubKey = &pubKey)
            fixed (byte* pData = &data, pSig = &sig64)
            {
                NCResult result = Functions.NCVerifyData.Invoke(context.DangerousGetHandle(), pPubKey, pData, dataSize, pSig);
                NCUtil.CheckResult<FunctionTable.NCVerifyDataDelegate>(result, false);

                return result == NC_SUCCESS;
            }
        }

        ///<inheritdoc/>
        public bool VerifyMac(
            ref readonly NCSecretKey secretKey, 
            ref readonly NCPublicKey publicKey, 
            ref readonly byte nonce32, 
            ref readonly byte mac32, 
            ref readonly byte payload, 
            uint payloadSize
        )
        {
            Check();

            //Check pointers we need to use
            ThrowIfNullRef(in nonce32, nameof(nonce32));
            ThrowIfNullRef(in mac32, nameof(mac32));
            ThrowIfNullRef(in payload, nameof(payload));

            fixed (NCSecretKey* pSecKey = &secretKey)
            fixed (NCPublicKey* pPubKey = &publicKey)
            fixed (byte* pPayload = &payload, pMac = &mac32, pNonce = &nonce32)
            {

                NCMacVerifyArgs args = new()
                {
                    payloadSize = payloadSize,
                    payload = pPayload,
                    mac32 = pMac,
                    nonce32 = pNonce
                };

                //Exec and bypass failure
                NCResult result = Functions.NCVerifyMac.Invoke(context.DangerousGetHandle(), pSecKey, pPubKey, &args);
                NCUtil.CheckResult<FunctionTable.NCVerifyMacDelegate>(result, false);

                //Result should be success if the hmac is valid
                return result == NC_SUCCESS;
            }
        }

        public void ComputeMac(ref readonly byte hmacKey32, ref readonly byte payload, uint payloadSize, ref byte hmacOut32)
        {
            Check();

            //Library will check for null pointers, since they are all arguments
            fixed (byte* pKey = &hmacKey32, pPayload = &payload, pOut = &hmacOut32)
            {
                NCResult result = Functions.NCComputeMac.Invoke(context.DangerousGetHandle(), pKey, pPayload, payloadSize, pOut);
                NCUtil.CheckResult<FunctionTable.NCComputeMacDelegate>(result, true);
            }
        }

#if DEBUG

        /// <summary>
        /// DEBUG ONLY: Gets the conversation key for the supplied secret key and public key
        /// </summary>
        /// <param name="secretKey">The sender's private key</param>
        /// <param name="publicKey">The receiver's public key</param>
        /// <param name="key32">A pointer to the 32byte buffer to write the conversation key to</param>
        public void GetConverstationKey(
            ref readonly NCSecretKey secretKey,
            ref readonly NCPublicKey publicKey,
            ref byte key32
        )
        {
            Check();

            fixed (NCSecretKey* pSecKey = &secretKey)
            fixed (NCPublicKey* pPubKey = &publicKey)
            fixed (byte* pKey = &key32)
            {
                NCResult result = Functions.NCGetConversationKey.Invoke(context.DangerousGetHandle(), pSecKey, pPubKey, pKey);
                NCUtil.CheckResult<FunctionTable.NCGetConversationKeyDelegate>(result, true);
            }
        }

#endif

        ///<inheritdoc/>
        protected override void Free()
        {
            if(ownsContext)
            {
                context.Dispose();
            }
        }
        
        private static void ThrowIfNullRef([DoesNotReturnIf(false)] ref readonly byte value, string name)
        {
            if(Unsafe.IsNullRef(in value))
            {
                throw new ArgumentNullException(name);
            }
        }

       
    }
}