Skip to content

Commit

Permalink
Ed25519 public key to curve25519
Browse files Browse the repository at this point in the history
  • Loading branch information
crossle committed Dec 9, 2020
1 parent 12707e7 commit 9e8b46f
Showing 1 changed file with 36 additions and 4 deletions.
40 changes: 36 additions & 4 deletions pin.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ import (
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"time"

"github.com/MixinNetwork/mixin/crypto/edwards25519"
"golang.org/x/crypto/curve25519"
)

Expand Down Expand Up @@ -76,10 +78,10 @@ func EncryptEd25519PIN(ctx context.Context, pin, pinTokenBase64, sessionId, priv
if err != nil {
return "", err
}
var dst, curve, pub [32]byte
PrivateKeyToCurve25519(&curve, private)
var keyBytes, curvePriv, pub [32]byte
PrivateKeyToCurve25519(&curvePriv, private)
copy(pub[:], public[:])
curve25519.ScalarMult(&dst, &curve, &pub)
curve25519.ScalarMult(&keyBytes, &curvePriv, &pub)

pinByte := []byte(pin)
timeBytes := make([]byte, 8)
Expand All @@ -91,7 +93,7 @@ func EncryptEd25519PIN(ctx context.Context, pin, pinTokenBase64, sessionId, priv
padding := aes.BlockSize - len(pinByte)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
pinByte = append(pinByte, padtext...)
block, err := aes.NewCipher(dst[:])
block, err := aes.NewCipher(keyBytes[:])
if err != nil {
return "", err
}
Expand Down Expand Up @@ -158,3 +160,33 @@ func PrivateKeyToCurve25519(curve25519Private *[32]byte, privateKey ed25519.Priv

copy(curve25519Private[:], digest)
}

func PublicKeyToCurve25519(curve25519Public *[32]byte, publicKey ed25519.PublicKey) error {
var k [32]byte
copy(k[:], publicKey[:])
var A edwards25519.ExtendedGroupElement
if !A.FromBytes(&k) {
return fmt.Errorf("Invalid public key %x", publicKey)
}

// A.Z = 1 as a postcondition of FromBytes.
var x edwards25519.FieldElement
edwardsToMontgomeryX(&x, &A.Y)
edwards25519.FeToBytes(curve25519Public, &x)
return nil
}

func edwardsToMontgomeryX(outX, y *edwards25519.FieldElement) {
// We only need the x-coordinate of the curve25519 point, which I'll
// call u. The isomorphism is u=(y+1)/(1-y), since y=Y/Z, this gives
// u=(Y+Z)/(Z-Y). We know that Z=1, thus u=(Y+1)/(1-Y).
var oneMinusY edwards25519.FieldElement
edwards25519.FeOne(&oneMinusY)
edwards25519.FeSub(&oneMinusY, &oneMinusY, y)
edwards25519.FeInvert(&oneMinusY, &oneMinusY)

edwards25519.FeOne(outX)
edwards25519.FeAdd(outX, outX, y)

edwards25519.FeMul(outX, outX, &oneMinusY)
}

0 comments on commit 9e8b46f

Please sign in to comment.