Compare commits

..

No commits in common. "shared-secret" and "develop" have entirely different histories.

6 changed files with 1138 additions and 166 deletions

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 ekzyis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

7
README.md Normal file
View File

@ -0,0 +1,7 @@
**NIP-44 implementation in Go**
NIP-44 specification: https://github.com/nostr-protocol/nips/blob/master/44.md
To use as library: `go get -u github.com/ekzyis/nip44`
To run tests, clone repository and then run `go test`.

4
export_test.go Normal file
View File

@ -0,0 +1,4 @@
package nip44
// https://stackoverflow.com/a/60813569
var MessageKeys = messageKeys

2
go.mod
View File

@ -1,4 +1,4 @@
module git.ekzyis.com/ekzyis/nip44 module github.com/ekzyis/nip44
go 1.21.0 go 1.21.0

View File

@ -7,9 +7,12 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/base64" "encoding/base64"
"encoding/binary" "encoding/binary"
"encoding/hex"
"errors" "errors"
"fmt"
"io" "io"
"math" "math"
"math/big"
"github.com/decred/dcrd/dcrec/secp256k1/v4" "github.com/decred/dcrd/dcrec/secp256k1/v4"
"golang.org/x/crypto/chacha20" "golang.org/x/crypto/chacha20"
@ -17,7 +20,8 @@ import (
) )
var ( var (
MaxPlaintextSize = 65536 - 128 // 64kb - 128 MinPlaintextSize = 0x0001 // 1b msg => padded to 32b
MaxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb
) )
type EncryptOptions struct { type EncryptOptions struct {
@ -49,7 +53,7 @@ func Encrypt(conversationKey []byte, plaintext string, options *EncryptOptions)
} }
} }
if version != 2 { if version != 2 {
return "", errors.New("unknown version") return "", errors.New(fmt.Sprintf("unknown version %d", version))
} }
if len(salt) != 32 { if len(salt) != 32 {
return "", errors.New("salt must be 32 bytes") return "", errors.New("salt must be 32 bytes")
@ -63,7 +67,9 @@ func Encrypt(conversationKey []byte, plaintext string, options *EncryptOptions)
if ciphertext, err = chacha20_(enc, nonce, []byte(padded)); err != nil { if ciphertext, err = chacha20_(enc, nonce, []byte(padded)); err != nil {
return "", err return "", err
} }
hmac_ = sha256Hmac(auth, ciphertext) if hmac_, err = sha256Hmac(auth, ciphertext, salt); err != nil {
return "", err
}
concat = append(concat, []byte{byte(version)}...) concat = append(concat, []byte{byte(version)}...)
concat = append(concat, salt...) concat = append(concat, salt...)
concat = append(concat, ciphertext...) concat = append(concat, ciphertext...)
@ -75,9 +81,11 @@ func Decrypt(conversationKey []byte, ciphertext string) (string, error) {
var ( var (
version int = 2 version int = 2
decoded []byte decoded []byte
cLen int
dLen int dLen int
salt []byte salt []byte
ciphertext_ []byte ciphertext_ []byte
hmac []byte
hmac_ []byte hmac_ []byte
enc []byte enc []byte
nonce []byte nonce []byte
@ -87,6 +95,10 @@ func Decrypt(conversationKey []byte, ciphertext string) (string, error) {
unpadded []byte unpadded []byte
err error err error
) )
cLen = len(ciphertext)
if cLen < 132 || cLen > 87472 {
return "", errors.New(fmt.Sprintf("invalid payload length: %d", cLen))
}
if ciphertext[0:1] == "#" { if ciphertext[0:1] == "#" {
return "", errors.New("unknown version") return "", errors.New("unknown version")
} }
@ -94,22 +106,31 @@ func Decrypt(conversationKey []byte, ciphertext string) (string, error) {
return "", errors.New("invalid base64") return "", errors.New("invalid base64")
} }
if version = int(decoded[0]); version != 2 { if version = int(decoded[0]); version != 2 {
return "", errors.New("unknown version") return "", errors.New(fmt.Sprintf("unknown version %d", version))
} }
dLen = len(decoded) dLen = len(decoded)
if dLen < 99 || dLen > 65603 {
return "", errors.New(fmt.Sprintf("invalid data length: %d", dLen))
}
salt, ciphertext_, hmac_ = decoded[1:33], decoded[33:dLen-32], decoded[dLen-32:] salt, ciphertext_, hmac_ = decoded[1:33], decoded[33:dLen-32], decoded[dLen-32:]
if enc, nonce, auth, err = messageKeys(conversationKey, salt); err != nil { if enc, nonce, auth, err = messageKeys(conversationKey, salt); err != nil {
return "", err return "", err
} }
if !bytes.Equal(hmac_, sha256Hmac(auth, ciphertext_)) { if hmac, err = sha256Hmac(auth, ciphertext_, salt); err != nil {
return "", err
}
if !bytes.Equal(hmac_, hmac) {
return "", errors.New("invalid hmac") return "", errors.New("invalid hmac")
} }
if padded, err = chacha20_(enc, nonce, ciphertext_); err != nil { if padded, err = chacha20_(enc, nonce, ciphertext_); err != nil {
return "", err return "", err
} }
unpaddedLen = binary.BigEndian.Uint16(padded[0:2]) unpaddedLen = binary.BigEndian.Uint16(padded[0:2])
if unpaddedLen < uint16(MinPlaintextSize) || unpaddedLen > uint16(MaxPlaintextSize) || len(padded) != 2+calcPadding(int(unpaddedLen)) {
return "", errors.New("invalid padding")
}
unpadded = padded[2 : unpaddedLen+2] unpadded = padded[2 : unpaddedLen+2]
if len(unpadded) == 0 || len(unpadded) != int(unpaddedLen) || len(padded) != 2+calcPadding(int(unpaddedLen)) { if len(unpadded) == 0 || len(unpadded) != int(unpaddedLen) {
return "", errors.New("invalid padding") return "", errors.New("invalid padding")
} }
return string(unpadded), nil return string(unpadded), nil
@ -117,19 +138,23 @@ func Decrypt(conversationKey []byte, ciphertext string) (string, error) {
func GenerateConversationKey(sendPrivkey []byte, recvPubkey []byte) ([]byte, error) { func GenerateConversationKey(sendPrivkey []byte, recvPubkey []byte) ([]byte, error) {
var ( var (
privkey *secp256k1.PrivateKey N = secp256k1.S256().N
pubkey *secp256k1.PublicKey sk *secp256k1.PrivateKey
err error pk *secp256k1.PublicKey
err error
) )
if len(recvPubkey) == 32 { // make sure that private key is on curve before using unsafe secp256k1.PrivKeyFromBytes
// pubkey must be in compressed format // see https://pkg.go.dev/github.com/decred/dcrd/dcrec/secp256k1/v4#PrivKeyFromBytes
recvPubkey = append([]byte{0x2}, recvPubkey...) skX := new(big.Int).SetBytes(sendPrivkey)
if skX.Cmp(big.NewInt(0)) == 0 || skX.Cmp(N) >= 0 {
return []byte{}, fmt.Errorf("invalid private key: x coordinate %s is not on the secp256k1 curve", hex.EncodeToString(sendPrivkey))
} }
privkey = secp256k1.PrivKeyFromBytes(sendPrivkey) sk = secp256k1.PrivKeyFromBytes(sendPrivkey)
if pubkey, err = secp256k1.ParsePubKey(recvPubkey); err != nil { if pk, err = secp256k1.ParsePubKey(recvPubkey); err != nil {
return nil, err return []byte{}, err
} }
return secp256k1.GenerateSharedSecret(privkey, pubkey), nil shared := secp256k1.GenerateSharedSecret(sk, pk)
return hkdf.Extract(sha256.New, shared, []byte("nip44-v2")), nil
} }
func chacha20_(key []byte, nonce []byte, message []byte) ([]byte, error) { func chacha20_(key []byte, nonce []byte, message []byte) ([]byte, error) {
@ -153,10 +178,14 @@ func randomBytes(n int) ([]byte, error) {
return buf, nil return buf, nil
} }
func sha256Hmac(key []byte, ciphertext []byte) []byte { func sha256Hmac(key []byte, ciphertext []byte, aad []byte) ([]byte, error) {
if len(aad) != 32 {
return nil, errors.New("aad data must be 32 bytes")
}
h := hmac.New(sha256.New, key) h := hmac.New(sha256.New, key)
h.Write(aad)
h.Write(ciphertext) h.Write(ciphertext)
return h.Sum(nil) return h.Sum(nil), nil
} }
func messageKeys(conversationKey []byte, salt []byte) ([]byte, []byte, []byte, error) { func messageKeys(conversationKey []byte, salt []byte) ([]byte, []byte, []byte, error) {
@ -167,7 +196,13 @@ func messageKeys(conversationKey []byte, salt []byte) ([]byte, []byte, []byte, e
auth []byte = make([]byte, 32) auth []byte = make([]byte, 32)
err error err error
) )
r = hkdf.New(sha256.New, conversationKey, salt, []byte("nip44-v2")) if len(conversationKey) != 32 {
return nil, nil, nil, errors.New("conversation key must be 32 bytes")
}
if len(salt) != 32 {
return nil, nil, nil, errors.New("salt must be 32 bytes")
}
r = hkdf.Expand(sha256.New, conversationKey, salt)
if _, err = io.ReadFull(r, enc); err != nil { if _, err = io.ReadFull(r, enc); err != nil {
return nil, nil, nil, err return nil, nil, nil, err
} }
@ -189,7 +224,7 @@ func pad(s string) ([]byte, error) {
) )
sb = []byte(s) sb = []byte(s)
sbLen = len(sb) sbLen = len(sb)
if sbLen < 1 || sbLen >= MaxPlaintextSize { if sbLen < 1 || sbLen > MaxPlaintextSize {
return nil, errors.New("plaintext should be between 1b and 64kB") return nil, errors.New("plaintext should be between 1b and 64kB")
} }
padding = calcPadding(sbLen) padding = calcPadding(sbLen)

File diff suppressed because it is too large Load Diff