aboutsummaryrefslogtreecommitdiff
path: root/lib/NVault.Crypto.Noscrypt/src/Nip44Util.cs
blob: 669d5f05ade81415d1db69d0995fc470606730a9 (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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// 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.Buffers.Binary;
using System.Runtime.InteropServices;

using VNLib.Utils.Memory;

using static NVault.Crypto.Noscrypt.LibNoscrypt;

namespace NVault.Crypto.Noscrypt
{

    /// <summary>
    /// Provides a set of utility methods for working with the Noscrypt library
    /// </summary>
    public static class Nip44Util
    {
        /// <summary>
        /// Calculates the required NIP44 encryption buffer size for 
        /// the specified input data size
        /// </summary>
        /// <param name="dataSize">The size (in bytes) of the encoded data to encrypt</param>
        /// <returns>The exact size of the padded buffer output</returns>
        public static int CalcBufferSize(int dataSize)
        {
            /*
             * Taken from https://github.com/nostr-protocol/nips/blob/master/44.md
             * 
             * Not gonna lie, kinda dumb branches. I guess they want to save space
             * with really tiny messages... Dunno, but whatever RTFM
             */

            //Min message size is 32 bytes
            int minSize = Math.Max(dataSize, 32);

            //find the next power of 2 that will fit the min size
            int nexPower = 1 << ((int)Math.Log2(minSize - 1)) + 1;

            int chunk = nexPower <= 256 ? 32 : nexPower / 8;

            return (chunk * ((int)Math.Floor((double)((minSize - 1) / chunk)) + 1)) + sizeof(ushort);
        }

        /// <summary>
        /// Formats the plaintext data into a buffer that can be properly encrypted. 
        /// The output buffer must be zeroed, or can be zeroed using the 
        /// <paramref name="zeroOutput"/> parameter. Use <see cref="CalcBufferSize(uint)"/> 
        /// to determine the required output buffer size.
        /// </summary>
        /// <param name="plaintextData">A buffer containing plaintext data to copy to the output</param>
        /// <param name="output">The output data buffer to format</param>
        /// <param name="zeroOutput">A value that indicates if the buffer should be zeroed before use</param>
        public static void FormatBuffer(ReadOnlySpan<byte> plaintextData, Span<byte> output, bool zeroOutput)
        {
            //First zero out the buffer
            if (zeroOutput)
            {
                MemoryUtil.InitializeBlock(output);
            }

            //Make sure the output buffer is large enough so we dont overrun it
            ArgumentOutOfRangeException.ThrowIfLessThan(output.Length, plaintextData.Length + sizeof(ushort), nameof(output));

            //Write the data size to the first 2 bytes
            ushort dataSize = (ushort)plaintextData.Length;
            BinaryPrimitives.WriteUInt16BigEndian(output, dataSize);

            //Copy the plaintext data to the output buffer after the data size
            MemoryUtil.Memmove(
                in MemoryMarshal.GetReference(plaintextData),
                0,
                ref MemoryMarshal.GetReference(output),
                 sizeof(ushort),
                (uint)plaintextData.Length
            );

            //We assume the remaining buffer is zeroed out
        }

        public static ReadOnlySpan<byte> GetNonceFromPayload(ReadOnlySpan<byte> message)
        {
            //The nonce is 32 bytes following the 1st byte version number of the message
            return message.Slice(1, NC_ENCRYPTION_NONCE_SIZE);
        }

        public static ReadOnlySpan<byte> GetCiphertextFromPayload(ReadOnlySpan<byte> message)
        {
            //Message is between the nonce and the trailing mac
            int payloadSize = message.Length - (1 + NC_ENCRYPTION_NONCE_SIZE + NC_ENCRYPTION_MAC_SIZE);
            return message.Slice(1 + NC_ENCRYPTION_NONCE_SIZE, payloadSize);
        }

        public static ReadOnlySpan<byte> GetMacFromPayload(ReadOnlySpan<byte> message)
        {
            //The mac is the last 32 bytes of the message
            return message[^NC_ENCRYPTION_MAC_SIZE..];
        }

        public static ReadOnlySpan<byte> GetNonceAndCiphertext(ReadOnlySpan<byte> message)
        {
            //The nonce is 32 bytes following the 1st byte version number of the message
            return message.Slice(1, NC_ENCRYPTION_NONCE_SIZE + GetCiphertextFromPayload(message).Length);
        }

        public static byte GetMessageVersion(ReadOnlySpan<byte> message)
        {
            //The first byte is the message version
            return message[0];
        }

        public static ReadOnlySpan<byte> GetPlaintextMessage(ReadOnlySpan<byte> plaintextPayload)
        {
            ushort ptLength = BinaryPrimitives.ReadUInt16BigEndian(plaintextPayload);
            return plaintextPayload.Slice(sizeof(ushort), ptLength);
        }


        public static void Encrypt(
            this INostrCrypto lib,
            ref readonly NCSecretKey secretKey,
            ref readonly NCPublicKey publicKey,
            ReadOnlySpan<byte> nonce32,
            ReadOnlySpan<byte> plainText,
            Span<byte> hmackKeyOut32,
            Span<byte> cipherText
        )
        {
            ArgumentNullException.ThrowIfNull(lib);

            //Chacha requires the output buffer to be at-least the size of the input buffer
            ArgumentOutOfRangeException.ThrowIfGreaterThan(plainText.Length, cipherText.Length, nameof(plainText));

            //Nonce must be exactly 32 bytes
            ArgumentOutOfRangeException.ThrowIfNotEqual(nonce32.Length, NC_ENCRYPTION_NONCE_SIZE, nameof(nonce32));

            ArgumentOutOfRangeException.ThrowIfNotEqual(hmackKeyOut32.Length, NC_HMAC_KEY_SIZE, nameof(hmackKeyOut32));

            //Encrypt data, use the plaintext buffer size as the data size
            lib.Encrypt(
                in secretKey,
                in publicKey,
                in MemoryMarshal.GetReference(nonce32),
                in MemoryMarshal.GetReference(plainText),
                ref MemoryMarshal.GetReference(cipherText),
                (uint)plainText.Length,
                ref MemoryMarshal.GetReference(hmackKeyOut32)
            );
        }

        public static unsafe void Encrypt(
            this INostrCrypto lib,
            ref NCSecretKey secretKey,
            ref NCPublicKey publicKey,
            void* nonce32,
            void* hmacKeyOut32,
            void* plainText,
            void* cipherText,
            uint size
        )
        {
            ArgumentNullException.ThrowIfNull(plainText);
            ArgumentNullException.ThrowIfNull(cipherText);
            ArgumentNullException.ThrowIfNull(nonce32);

            //Spans are easer to forward references from pointers without screwing up arguments
            Encrypt(
                lib,
                in secretKey,
                in publicKey,
                new ReadOnlySpan<byte>(nonce32, 32),
                new ReadOnlySpan<byte>(plainText, (int)size),
                new Span<byte>(hmacKeyOut32, 32),
                new Span<byte>(cipherText, (int)size)
            );
        }


        public static void Decrypt(
            this INostrCrypto lib,
            ref readonly NCSecretKey secretKey,
            ref readonly NCPublicKey publicKey,
            ReadOnlySpan<byte> nonce32,
            ReadOnlySpan<byte> cipherText,
            Span<byte> plainText
        )
        {
            ArgumentNullException.ThrowIfNull(lib);

            //Chacha requires the output buffer to be at-least the size of the input buffer
            ArgumentOutOfRangeException.ThrowIfGreaterThan(cipherText.Length, plainText.Length, nameof(cipherText));

            //Nonce must be exactly 32 bytes
            ArgumentOutOfRangeException.ThrowIfNotEqual(nonce32.Length, 32, nameof(nonce32));

            //Decrypt data, use the ciphertext buffer size as the data size
            lib.Decrypt(
                in secretKey,
                in publicKey,
                in MemoryMarshal.GetReference(nonce32),
                in MemoryMarshal.GetReference(cipherText),
                ref MemoryMarshal.GetReference(plainText),
                (uint)cipherText.Length
            );
        }

        public static unsafe void Decrypt(
            this INostrCrypto lib,
            ref readonly NCSecretKey secretKey,
            ref readonly NCPublicKey publicKey,
            void* nonce32,
            void* cipherText,
            void* plainText,
            uint size
        )
        {
            ArgumentNullException.ThrowIfNull(nonce32);
            ArgumentNullException.ThrowIfNull(cipherText);
            ArgumentNullException.ThrowIfNull(plainText);

            //Spans are easer to forward references from pointers without screwing up arguments
            Decrypt(
                lib,
                in secretKey,
                in publicKey,
                new Span<byte>(nonce32, 32),
                new Span<byte>(cipherText, (int)size),
                new Span<byte>(plainText, (int)size)
            );
        }

        public static bool VerifyMac(
            this INostrCrypto lib,
            ref readonly NCSecretKey secretKey,
            ref readonly NCPublicKey publicKey,
            ReadOnlySpan<byte> nonce32,
            ReadOnlySpan<byte> mac32,
            ReadOnlySpan<byte> payload
        )
        {
            ArgumentNullException.ThrowIfNull(lib);
            ArgumentOutOfRangeException.ThrowIfZero(payload.Length, nameof(payload));
            ArgumentOutOfRangeException.ThrowIfNotEqual(nonce32.Length, NC_ENCRYPTION_NONCE_SIZE, nameof(nonce32));
            ArgumentOutOfRangeException.ThrowIfNotEqual(mac32.Length, NC_ENCRYPTION_MAC_SIZE, nameof(mac32));

            //Verify the HMAC
            return lib.VerifyMac(
                in secretKey,
                in publicKey,
                in MemoryMarshal.GetReference(nonce32),
                in MemoryMarshal.GetReference(mac32),
                in MemoryMarshal.GetReference(payload),
                (uint)payload.Length
            );
        }

        public static unsafe bool VerifyMac(
            this INostrCrypto lib,
            ref readonly NCSecretKey secretKey,
            ref readonly NCPublicKey publicKey,
            void* nonce32,
            void* mac32,
            void* payload,
            uint payloadSize
        )
        {
            ArgumentNullException.ThrowIfNull(nonce32);
            ArgumentNullException.ThrowIfNull(mac32);
            ArgumentNullException.ThrowIfNull(payload);

            //Spans are easer to forward references from pointers without screwing up arguments
            return VerifyMac(
                lib,
                in secretKey,
                in publicKey,
                new Span<byte>(nonce32, NC_ENCRYPTION_NONCE_SIZE),
                new Span<byte>(mac32, NC_ENCRYPTION_MAC_SIZE),
                new Span<byte>(payload, (int)payloadSize)
            );
        }

#if DEBUG
        /*
         * Conversation key is not meant to be a public api. Callers 
         * should use Encrypt/Decrypt methods to handle encryption.
         * 
         * This method exists for vector testing purposes only.
         */
        public static void GetConverstationKey(
            this NostrCrypto lib,
            ref readonly NCSecretKey secretKey,
            ref readonly NCPublicKey publicKey,
            Span<byte> conversationKeyOut32
        )
        {
            ArgumentNullException.ThrowIfNull(lib);
            ArgumentOutOfRangeException.ThrowIfNotEqual(conversationKeyOut32.Length, NC_CONVERSATION_KEY_SIZE, nameof(conversationKeyOut32));

            //Get the conversation key
            lib.GetConverstationKey(
                in secretKey,
                in publicKey,
                ref MemoryMarshal.GetReference(conversationKeyOut32)
            );

        }
#endif

    }

}