Skip to content

Commit

Permalink
EcPrivKeyTweakMul (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
sekulicd authored Nov 15, 2021
1 parent 1b1151b commit 0d6a731
Show file tree
Hide file tree
Showing 3 changed files with 562 additions and 1 deletion.
18 changes: 18 additions & 0 deletions ecdh.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,21 @@ func EcPubKeyCombine(ctx *Context, vPk []*PublicKey) (int, *PublicKey, error) {
}
return result, pkOut, nil
}

// EcPrivKeyTweakMul tweak a private key by multiplying it by a tweak. The return code is 0
// if the tweak was out of range (chance of around 1 in 2^128 for uniformly
// random 32-byte arrays) or zero. The code is 1 otherwise.
func EcPrivKeyTweakMul(ctx *Context, seckey []byte, tweak []byte) (int, error) {
if len(tweak) != LenPrivateKey {
return 0, errors.New(ErrorTweakSize)
}
if len(seckey) != LenPrivateKey {
return 0, errors.New(ErrorPrivateKeySize)
}

result := int(C.secp256k1_ec_privkey_tweak_mul(ctx.ctx, (*C.uchar)(unsafe.Pointer(&seckey[0])), cBuf(tweak[:])))
if result != 1 {
return result, errors.New(ErrorTweakingPrivateKey)
}
return result, nil
}
46 changes: 45 additions & 1 deletion ecdh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func TestEcdh(t *testing.T) {

}

func TestPubKeyTweakAddFixtures(t *testing.T) {
func TestPubKeyTweakAddF(t *testing.T) {
ctx, err := secp256k1.ContextCreate(secp256k1.ContextSign | secp256k1.ContextVerify)
if err != nil {
panic(err)
Expand Down Expand Up @@ -163,6 +163,50 @@ func TestPubKeyNegate(t *testing.T) {

}

func TestPrivKeyTweakMultiply(t *testing.T) {
ctx, err := secp256k1.ContextCreate(secp256k1.ContextSign | secp256k1.ContextVerify)
if err != nil {
panic(err)
}

file, err := ioutil.ReadFile("testdata/privkey_tweak_mult_vectors.json")
if err != nil {
t.Fatal(err)
}

var tests map[string]interface{}
err = json.Unmarshal(file, &tests)
if err != nil {
t.Error(err)
}

vectors := tests["tweak_mult"].([]interface{})


for _, testVector := range vectors {
v := testVector.(map[string]interface{})
privKeyBytes, err := hex.DecodeString(v["privkey"].(string))
if err != nil {
t.Error(err)
}

tweakBytes, err := hex.DecodeString(v["tweak"].(string))
if err != nil {
t.Error(err)
}

tweakedBytes, err := hex.DecodeString(v["tweaked"].(string))
if err != nil {
t.Error(err)
}

r, err := secp256k1.EcPrivKeyTweakMul(ctx, privKeyBytes, tweakBytes)
spOK(t, r, err)

assert.Equal(t, tweakedBytes, privKeyBytes)
}
}

func spOK(t *testing.T, result interface{}, err error) {
assert.NoError(t, err)
switch result := result.(type) {
Expand Down
Loading

0 comments on commit 0d6a731

Please sign in to comment.