Compare commits

...

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

6 changed files with 166 additions and 1138 deletions

21
LICENSE
View File

@ -1,21 +0,0 @@
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.

View File

@ -1,7 +0,0 @@
**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`.

View File

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

2
go.mod
View File

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

View File

@ -7,12 +7,9 @@ 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"
@ -20,8 +17,7 @@ import (
) )
var ( var (
MinPlaintextSize = 0x0001 // 1b msg => padded to 32b MaxPlaintextSize = 65536 - 128 // 64kb - 128
MaxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb
) )
type EncryptOptions struct { type EncryptOptions struct {
@ -53,7 +49,7 @@ func Encrypt(conversationKey []byte, plaintext string, options *EncryptOptions)
} }
} }
if version != 2 { if version != 2 {
return "", errors.New(fmt.Sprintf("unknown version %d", version)) return "", errors.New("unknown 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")
@ -67,9 +63,7 @@ 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
} }
if hmac_, err = sha256Hmac(auth, ciphertext, salt); err != nil { hmac_ = sha256Hmac(auth, ciphertext)
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...)
@ -81,11 +75,9 @@ 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
@ -95,10 +87,6 @@ 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")
} }
@ -106,31 +94,22 @@ 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(fmt.Sprintf("unknown version %d", version)) return "", errors.New("unknown 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 hmac, err = sha256Hmac(auth, ciphertext_, salt); err != nil { if !bytes.Equal(hmac_, sha256Hmac(auth, ciphertext_)) {
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) { if len(unpadded) == 0 || len(unpadded) != int(unpaddedLen) || len(padded) != 2+calcPadding(int(unpaddedLen)) {
return "", errors.New("invalid padding") return "", errors.New("invalid padding")
} }
return string(unpadded), nil return string(unpadded), nil
@ -138,23 +117,19 @@ 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 (
N = secp256k1.S256().N privkey *secp256k1.PrivateKey
sk *secp256k1.PrivateKey pubkey *secp256k1.PublicKey
pk *secp256k1.PublicKey err error
err error
) )
// make sure that private key is on curve before using unsafe secp256k1.PrivKeyFromBytes if len(recvPubkey) == 32 {
// see https://pkg.go.dev/github.com/decred/dcrd/dcrec/secp256k1/v4#PrivKeyFromBytes // pubkey must be in compressed format
skX := new(big.Int).SetBytes(sendPrivkey) recvPubkey = append([]byte{0x2}, recvPubkey...)
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))
} }
sk = secp256k1.PrivKeyFromBytes(sendPrivkey) privkey = secp256k1.PrivKeyFromBytes(sendPrivkey)
if pk, err = secp256k1.ParsePubKey(recvPubkey); err != nil { if pubkey, err = secp256k1.ParsePubKey(recvPubkey); err != nil {
return []byte{}, err return nil, err
} }
shared := secp256k1.GenerateSharedSecret(sk, pk) return secp256k1.GenerateSharedSecret(privkey, pubkey), nil
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) {
@ -178,14 +153,10 @@ func randomBytes(n int) ([]byte, error) {
return buf, nil return buf, nil
} }
func sha256Hmac(key []byte, ciphertext []byte, aad []byte) ([]byte, error) { func sha256Hmac(key []byte, ciphertext []byte) []byte {
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), nil return h.Sum(nil)
} }
func messageKeys(conversationKey []byte, salt []byte) ([]byte, []byte, []byte, error) { func messageKeys(conversationKey []byte, salt []byte) ([]byte, []byte, []byte, error) {
@ -196,13 +167,7 @@ func messageKeys(conversationKey []byte, salt []byte) ([]byte, []byte, []byte, e
auth []byte = make([]byte, 32) auth []byte = make([]byte, 32)
err error err error
) )
if len(conversationKey) != 32 { r = hkdf.New(sha256.New, conversationKey, salt, []byte("nip44-v2"))
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
} }
@ -224,7 +189,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