NIP44.swift (14415B)
1 // 2 // NIP44.swift 3 // damus 4 // 5 // Based on NIP44v2Encrypting.swift created by Terry Yiu on 3/16/24, from https://github.com/nostr-sdk/nostr-sdk-ios, which is MIT licensed. 6 // 7 // MIT License 8 // 9 // Copyright (c) 2023 Nostr SDK 10 // 11 // Permission is hereby granted, free of charge, to any person obtaining a copy 12 // of this software and associated documentation files (the "Software"), to deal 13 // in the Software without restriction, including without limitation the rights 14 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 15 // copies of the Software, and to permit persons to whom the Software is 16 // furnished to do so, subject to the following conditions: 17 // 18 // The above copyright notice and this permission notice shall be included in all 19 // copies or substantial portions of the Software. 20 // 21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 27 // SOFTWARE. 28 // 29 // 30 // Adapted by Daniel D’Aquino on 2025-02-10. 31 // 32 import Foundation 33 import CryptoKit 34 import CryptoSwift 35 import secp256k1 36 37 struct NIP44v2Encryption { 38 39 /// Produces a `String` containing `plaintext` that has been encrypted using the `privateKey` of user A and the `publicKey` of user B. 40 /// 41 /// The result is non-deterministic because a cryptographically secure pseudorandom generated nonce is used each time, 42 /// but can be decrypted deterministically with a call to ``NIP44v2Encryption/decrypt(payload:privateKeyA:publicKeyB:)``, 43 /// where user A and user B are interchangeable. 44 /// 45 /// This function can `throw` an error from ``EncryptionError`` if it fails to encrypt the plaintext. 46 /// 47 /// - Parameters: 48 /// - plaintext: The plaintext to encrypt. 49 /// - privateKeyA: The private key of user A. 50 /// - publicKeyB: The public key of user B. 51 /// - Returns: The encrypted ciphertext. 52 static func encrypt(plaintext: String, privateKeyA: Privkey, publicKeyB: Pubkey) throws -> String { 53 let conversationKey = try conversationKey(privateKeyA: privateKeyA, publicKeyB: publicKeyB) 54 55 return try encrypt(plaintext: plaintext, conversationKey: conversationKey) 56 } 57 58 /// Produces a `String` containing `payload` that has been decrypted using the `privateKey` of user A and the `publicKey` of user B, 59 /// and the result is identical to if the `privateKey` of user B and `publicKey` of user A were used to decrypt `payload` instead. 60 /// 61 /// Any ciphertext returned from the call to ``NIP44v2Encryption/encrypt(plaintext:privateKeyA:publicKeyB:)`` 62 /// can be decrypted, where user A and B are interchangeable. 63 /// 64 /// This function can `throw` an error from ``EncryptionError`` if it fails to decrypt the payload. 65 /// 66 /// - Parameters: 67 /// - payload: The payload to decrypt. 68 /// - privateKeyA: The private key of user A. 69 /// - publicKeyB: The public key of user B. 70 /// - Returns: The decrypted plaintext message. 71 static func decrypt(payload: String, privateKeyA: Privkey, publicKeyB: Pubkey) throws -> String { 72 let conversationKey = try conversationKey(privateKeyA: privateKeyA, publicKeyB: publicKeyB) 73 74 return try decrypt(payload: payload, conversationKey: conversationKey) 75 } 76 77 /// Calculates length of the padded byte array. 78 static func calculatePaddedLength(_ unpaddedLength: Int) throws -> Int { 79 guard unpaddedLength > 0 else { 80 throw EncryptionError.unpaddedLengthInvalid(unpaddedLength) 81 } 82 if unpaddedLength <= 32 { 83 return 32 84 } 85 86 let nextPower = 1 << (Int(floor(log2(Double(unpaddedLength) - 1))) + 1) 87 let chunk: Int 88 89 if nextPower <= 256 { 90 chunk = 32 91 } else { 92 chunk = nextPower / 8 93 } 94 95 return chunk * (Int(floor((Double(unpaddedLength) - 1) / Double(chunk))) + 1) 96 } 97 98 /// Converts unpadded plaintext to padded bytes. 99 static func pad(_ plaintext: String) throws -> Data { 100 guard let unpadded = plaintext.data(using: .utf8) else { 101 throw EncryptionError.utf8EncodingFailed 102 } 103 104 let unpaddedLength = unpadded.count 105 106 guard 1...65535 ~= unpaddedLength else { 107 throw EncryptionError.plaintextLengthInvalid(unpaddedLength) 108 } 109 110 var prefix = Data(count: 2) 111 prefix.withUnsafeMutableBytes { (ptr: UnsafeMutableRawBufferPointer) in 112 ptr.storeBytes(of: UInt16(unpaddedLength).bigEndian, as: UInt16.self) 113 } 114 115 let suffix = Data(count: try calculatePaddedLength(unpaddedLength) - unpaddedLength) 116 117 return prefix + unpadded + suffix 118 } 119 120 /// Converts padded bytes to unpadded plaintext. 121 static func unpad(_ padded: Data) throws -> String { 122 guard padded.count >= 2 else { 123 throw EncryptionError.paddingInvalid 124 } 125 126 let unpaddedLength = (Int(padded[0]) << 8) | Int(padded[1]) 127 128 guard 2+unpaddedLength <= padded.count else { 129 throw EncryptionError.paddingInvalid 130 } 131 132 let unpadded = toBytes(from: padded)[2..<2+unpaddedLength] 133 let paddedLength = try calculatePaddedLength(unpaddedLength) 134 135 guard unpaddedLength > 0, 136 unpadded.count == unpaddedLength, 137 padded.count == 2 + paddedLength, 138 let result = String(data: Data(unpadded), encoding: .utf8) else { 139 throw EncryptionError.paddingInvalid 140 } 141 142 return result 143 } 144 145 static func decodePayload(_ payload: String) throws -> DecodedPayload { 146 let payloadLength = payload.count 147 148 guard payloadLength > 0 && payload.first != "#" else { 149 throw EncryptionError.unknownVersion() 150 } 151 guard 132...87472 ~= payloadLength else { 152 throw EncryptionError.payloadSizeInvalid(payloadLength) 153 } 154 155 guard let data = Data(base64Encoded: payload) else { 156 throw EncryptionError.base64EncodingFailed 157 } 158 159 let dataLength = data.count 160 161 guard 99...65603 ~= dataLength else { 162 throw EncryptionError.dataSizeInvalid(dataLength) 163 } 164 165 guard let version = data.first else { 166 throw EncryptionError.unknownVersion() 167 } 168 169 guard version == 2 else { 170 throw EncryptionError.unknownVersion(Int(version)) 171 } 172 173 let nonce = data[data.index(data.startIndex, offsetBy: 1)..<data.index(data.startIndex, offsetBy: 33)] 174 let ciphertext = data[data.index(data.startIndex, offsetBy: 33)..<data.index(data.startIndex, offsetBy: dataLength - 32)] 175 let mac = data[data.index(data.startIndex, offsetBy: dataLength - 32)..<data.index(data.startIndex, offsetBy: dataLength)] 176 177 return DecodedPayload(nonce: nonce, ciphertext: ciphertext, mac: mac) 178 } 179 180 static func hmacAad(key: Data, message: Data, aad: Data) throws -> Data { 181 guard aad.count == 32 else { 182 throw EncryptionError.aadLengthInvalid(aad.count) 183 } 184 185 let combined = aad + message 186 187 return Data(CryptoKit.HMAC<CryptoKit.SHA256>.authenticationCode(for: combined, using: SymmetricKey(data: key))) 188 } 189 190 static func toBytes(from data: Data) -> [UInt8] { 191 data.withUnsafeBytes { bytesPointer in Array(bytesPointer) } 192 } 193 194 static func preparePublicKeyBytes(from publicKey: Pubkey) throws -> [UInt8] { 195 let publicKeyBytes = publicKey.bytes 196 197 let prefix = Data([2]) 198 let prefixBytes = toBytes(from: prefix) 199 200 return prefixBytes + publicKeyBytes 201 } 202 203 static func parsePublicKey(from bytes: [UInt8]) throws -> secp256k1_pubkey { 204 var publicKey = secp256k1_pubkey() 205 guard secp256k1_ec_pubkey_parse(secp256k1.Context.raw, &publicKey, bytes, bytes.count) == 1 else { 206 throw EncryptionError.publicKeyInvalid 207 } 208 return publicKey 209 } 210 211 static func computeSharedSecret(using publicKey: secp256k1_pubkey, and privateKeyBytes: [UInt8]) throws -> [UInt8] { 212 var sharedSecret = [UInt8](repeating: 0, count: 32) 213 var mutablePublicKey = publicKey 214 215 // Multiplication of point B by scalar a (a ⋅ B), defined in [BIP340](https://github.com/bitcoin/bips/blob/e918b50731397872ad2922a1b08a5a4cd1d6d546/bip-0340.mediawiki). 216 // The operation produces a shared point, and we encode the shared point's 32-byte x coordinate, using method bytes(P) from BIP340. 217 // Private and public keys must be validated as per BIP340: pubkey must be a valid, on-curve point, and private key must be a scalar in range [1, secp256k1_order - 1] 218 guard secp256k1_ecdh(secp256k1.Context.raw, &sharedSecret, &mutablePublicKey, privateKeyBytes, { (output, x32, _, _) in 219 memcpy(output, x32, 32) 220 return 1 221 }, nil) != 0 else { 222 throw EncryptionError.sharedSecretComputationFailed 223 } 224 return sharedSecret 225 } 226 227 /// Calculates long-term key between users A and B. 228 /// The conversation key of A's private key and B's public key is equal to the conversation key of B's private key and A's public key. 229 static func conversationKey(privateKeyA: Privkey, publicKeyB: Pubkey) throws -> ContiguousBytes { 230 let privateKeyABytes = privateKeyA.bytes 231 let publicKeyBBytes = try preparePublicKeyBytes(from: publicKeyB) 232 let parsedPublicKeyB = try parsePublicKey(from: publicKeyBBytes) 233 let sharedSecret = try computeSharedSecret(using: parsedPublicKeyB, and: privateKeyABytes) 234 235 return CryptoKit.HKDF<CryptoKit.SHA256>.extract(inputKeyMaterial: SymmetricKey(data: sharedSecret), salt: Data("nip44-v2".utf8)) 236 } 237 238 /// Calculates unique per-message key. 239 static func messageKeys(conversationKey: ContiguousBytes, nonce: Data) throws -> MessageKeys { 240 let conversationKeyByteCount = conversationKey.bytes.count 241 guard conversationKeyByteCount == 32 else { 242 throw EncryptionError.conversationKeyLengthInvalid(conversationKeyByteCount) 243 } 244 245 guard nonce.count == 32 else { 246 throw EncryptionError.nonceLengthInvalid(nonce.count) 247 } 248 249 let keys = CryptoKit.HKDF<CryptoKit.SHA256>.expand(pseudoRandomKey: conversationKey, info: nonce, outputByteCount: 76) 250 let keysBytes = keys.bytes 251 252 let chaChaKey = Data(keysBytes[0..<32]) 253 let chaChaNonce = Data(keysBytes[32..<44]) 254 let hmacKey = Data(keysBytes[44..<76]) 255 256 return MessageKeys(chaChaKey: chaChaKey, chaChaNonce: chaChaNonce, hmacKey: hmacKey) 257 } 258 259 static func encrypt(plaintext: String, conversationKey: ContiguousBytes, nonce: Data? = nil) throws -> String { 260 let nonceData: Data 261 if let nonce { 262 nonceData = nonce 263 } else { 264 // Fetches randomness from CSPRNG. 265 nonceData = Data.secureRandomBytes(count: 32) 266 } 267 268 let messageKeys = try messageKeys(conversationKey: conversationKey, nonce: nonceData) 269 let padded = try pad(plaintext) 270 let paddedBytes = toBytes(from: padded) 271 272 let chaChaKey = toBytes(from: messageKeys.chaChaKey) 273 let chaChaNonce = toBytes(from: messageKeys.chaChaNonce) 274 275 let ciphertext = try ChaCha20(key: chaChaKey, iv: chaChaNonce).encrypt(paddedBytes) 276 let ciphertextData = Data(ciphertext) 277 278 let mac = try hmacAad(key: messageKeys.hmacKey, message: ciphertextData, aad: nonceData) 279 280 let data = Data([2]) + nonceData + ciphertextData + mac 281 return data.base64EncodedString() 282 } 283 284 static func decrypt(payload: String, conversationKey: ContiguousBytes) throws -> String { 285 let decodedPayload = try decodePayload(payload) 286 let nonce = decodedPayload.nonce 287 let ciphertext = decodedPayload.ciphertext 288 let ciphertextBytes = toBytes(from: ciphertext) 289 let mac = decodedPayload.mac 290 291 let messageKeys = try messageKeys(conversationKey: conversationKey, nonce: nonce) 292 293 let calculatedMac = try hmacAad(key: messageKeys.hmacKey, message: ciphertext, aad: nonce) 294 295 guard calculatedMac == mac else { 296 throw EncryptionError.macInvalid 297 } 298 299 let chaChaNonce = toBytes(from: messageKeys.chaChaNonce) 300 let chaChaKey = toBytes(from: messageKeys.chaChaKey) 301 302 let paddedPlaintext = try ChaCha20(key: chaChaKey, iv: chaChaNonce).decrypt(ciphertextBytes) 303 let paddedPlaintextData = Data(paddedPlaintext.bytes) 304 305 return try unpad(paddedPlaintextData) 306 } 307 } 308 309 310 // MARK: - Helper structures and extensions 311 312 extension Data { 313 /// Random data of a given size, from CSPRNG 314 /// - Parameter count: The size of the data, in bytes 315 /// - Returns: Bytes randomly generated from CSPRNG 316 static func secureRandomBytes(count: Int) -> Data { 317 var bytes = [Int8](repeating: 0, count: count) 318 guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { 319 fatalError("can't copy secure random data") 320 } 321 return Data(bytes: bytes, count: count) 322 } 323 } 324 325 extension NIP44v2Encryption { 326 struct DecodedPayload { 327 let nonce: Data 328 let ciphertext: Data 329 let mac: Data 330 } 331 332 struct MessageKeys { 333 let chaChaKey: Data 334 let chaChaNonce: Data 335 let hmacKey: Data 336 } 337 338 public enum EncryptionError: Error { 339 case aadLengthInvalid(Int) 340 case base64EncodingFailed 341 case chaCha20DecryptionFailed 342 case chaCha20EncryptionFailed 343 case conversationKeyLengthInvalid(Int) 344 case dataSizeInvalid(Int) 345 case macInvalid 346 case nonceLengthInvalid(Int) 347 case paddingInvalid 348 case payloadSizeInvalid(Int) 349 case plaintextLengthInvalid(Int) 350 case privateKeyInvalid 351 case publicKeyInvalid 352 case sharedSecretComputationFailed 353 case unknownVersion(Int? = nil) 354 case unpaddedLengthInvalid(Int) 355 case utf8EncodingFailed 356 } 357 }