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

View File

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

File diff suppressed because it is too large Load Diff