示例#1
0
// This example demonstrates decrypting a message using a private key that is
// first parsed from raw bytes.
func Example_decryptMessage() {
	// Decode the hex-encoded private key.
	pkBytes, err := hex.DecodeString("a11b0a4e1a132305652ee7a8eb7848f6ad" +
		"5ea381e3ce20a2c086a2e388230811")
	if err != nil {
		fmt.Println(err)
		return
	}

	privKey, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), pkBytes)

	ciphertext, err := hex.DecodeString("35f644fbfb208bc71e57684c3c8b437402ca" +
		"002047a2f1b38aa1a8f1d5121778378414f708fe13ebf7b4a7bb74407288c1958969" +
		"00207cf4ac6057406e40f79961c973309a892732ae7a74ee96cd89823913b8b8d650" +
		"a44166dc61ea1c419d47077b748a9c06b8d57af72deb2819d98a9d503efc59fc8307" +
		"d14174f8b83354fac3ff56075162")

	// Try decrypting the message.
	plaintext, err := secp256k1.Decrypt(privKey, ciphertext)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(plaintext))

	// Output:
	// test message
}
示例#2
0
// This example demonstrates signing a message with a secp256k1 private key that
// is first parsed form raw bytes and serializing the generated signature.
func Example_signMessage() {
	// Decode a hex-encoded private key.
	pkBytes, err := hex.DecodeString("22a47fa09a223f2aa079edf85a7c2d4f87" +
		"20ee63e502ee2869afab7de234b80c")
	if err != nil {
		fmt.Println(err)
		return
	}
	privKey, pubKey := secp256k1.PrivKeyFromBytes(secp256k1.S256(), pkBytes)

	// Sign a message using the private key.
	message := "test message"
	messageHash := chainhash.HashFuncB([]byte(message))
	signature, err := privKey.Sign(messageHash)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Serialize and display the signature.
	fmt.Printf("Serialized Signature: %x\n", signature.Serialize())

	// Verify the signature for the message using the public key.
	verified := signature.Verify(messageHash, pubKey)
	fmt.Printf("Signature Verified? %v\n", verified)

	// Output:
	// Serialized Signature: 3045022100fcc0a8768cfbcefcf2cadd7cfb0fb18ed08dd2e2ae84bef1a474a3d351b26f0302200fc1a350b45f46fa00101391302818d748c2b22615511a3ffd5bb638bd777207
	// Signature Verified? true
}
示例#3
0
func randPrivKeyList(curve *secp256k1.KoblitzCurve,
	i int) []*secp256k1.PrivateKey {
	r := rand.New(rand.NewSource(54321))

	privKeyList := make([]*secp256k1.PrivateKey, i, i)
	for j := 0; j < i; j++ {
		for {
			bIn := new([32]byte)
			for k := 0; k < scalarSize; k++ {
				randByte := r.Intn(255)
				bIn[k] = uint8(randByte)
			}

			pks, _ := secp256k1.PrivKeyFromBytes(curve, bIn[:])
			if pks == nil {
				continue
			}

			// No duplicates allowed.
			if j > 0 &&
				(bytes.Equal(pks.Serialize(), privKeyList[j-1].Serialize())) {
				r.Seed(int64(j) + r.Int63n(12345))
				continue
			}
			privKeyList[j] = pks
			r.Seed(int64(j) + 54321)
			break
		}
	}

	return privKeyList
}
示例#4
0
func randSigList(curve *secp256k1.KoblitzCurve, i int) []*SignatureVerParams {
	r := rand.New(rand.NewSource(54321))

	privKeyList := make([]*secp256k1.PrivateKey, i, i)
	for j := 0; j < i; j++ {
		for {
			bIn := new([32]byte)
			for k := 0; k < scalarSize; k++ {
				randByte := r.Intn(255)
				bIn[k] = uint8(randByte)
			}

			pks, _ := secp256k1.PrivKeyFromBytes(curve, bIn[:])
			if pks == nil {
				continue
			}
			privKeyList[j] = pks
			r.Seed(int64(j) + 54321)
			break
		}
	}

	msgList := make([][]byte, i, i)
	for j := 0; j < i; j++ {
		m := make([]byte, 32, 32)
		for k := 0; k < scalarSize; k++ {
			randByte := r.Intn(255)
			m[k] = uint8(randByte)
		}
		msgList[j] = m
		r.Seed(int64(j) + 54321)
	}

	sigsList := make([]*Signature, i, i)
	for j := 0; j < i; j++ {
		r, s, err := Sign(curve, privKeyList[j], msgList[j])
		if err != nil {
			panic("sign failure")
		}
		sig := &Signature{r, s}
		sigsList[j] = sig
	}

	sigStructList := make([]*SignatureVerParams, i, i)
	for j := 0; j < i; j++ {
		ss := new(SignatureVerParams)
		pkx, pky := privKeyList[j].Public()
		ss.pubkey = secp256k1.NewPublicKey(curve, pkx, pky)
		ss.msg = msgList[j]
		ss.sig = sigsList[j]
		sigStructList[j] = ss
	}

	return sigStructList
}
示例#5
0
func GetThresholdTestVectors() []*ThresholdTestVector {
	curve := secp256k1.S256()

	var tvs []*ThresholdTestVector
	for _, v := range thresholdTestVectorsHex {
		msg, _ := hex.DecodeString(v.msg)
		combSig, _ := hex.DecodeString(v.combinedSignature)
		signers := make([]signer, len(v.signersHex), len(v.signersHex))
		for i, signerHex := range v.signersHex {
			privkeyB, _ := hex.DecodeString(signerHex.privkey)
			_, pubkey := secp256k1.PrivKeyFromBytes(curve, privkeyB)
			privateNonceB, _ := hex.DecodeString(signerHex.privateNonce)
			_, noncePub := secp256k1.PrivKeyFromBytes(curve, privateNonceB)
			pubKeySumLocalB, _ := hex.DecodeString(signerHex.pubKeySumLocal)
			pubKeySumLocal, _ := secp256k1.ParsePubKey(pubKeySumLocalB, curve)
			partialSignature, _ := hex.DecodeString(signerHex.partialSignature)

			signers[i].privkey = privkeyB
			signers[i].pubkey = pubkey
			signers[i].privateNonce = privateNonceB
			signers[i].publicNonce = noncePub
			signers[i].pubKeySumLocal = pubKeySumLocal
			signers[i].partialSignature = partialSignature
		}

		lv := ThresholdTestVector{
			msg:               msg,
			signers:           signers,
			combinedSignature: combSig,
		}

		tvs = append(tvs, &lv)
	}

	return tvs
}
示例#6
0
func TestSchnorrSigning(t *testing.T) {
	tRand := rand.New(rand.NewSource(54321))
	curve := secp256k1.S256()
	tvs := GetSigningTestVectors()
	for _, tv := range tvs {
		_, pubkey := secp256k1.PrivKeyFromBytes(curve, tv.priv)

		sig, err :=
			schnorrSign(curve, tv.msg, tv.priv, tv.nonce, nil, nil,
				testSchnorrHash)

		assert.NoError(t, err)
		assert.Equal(t, sig.Serialize(), tv.sig)

		// Make sure they verify too while we're at it.
		_, err = schnorrVerify(curve, sig.Serialize(), pubkey, tv.msg,
			testSchnorrHash)
		assert.NoError(t, err)

		// See if we can recover the public keys OK.
		var pkRecover *secp256k1.PublicKey
		pkRecover, _, err = schnorrRecover(curve, sig.Serialize(), tv.msg,
			testSchnorrHash)
		assert.NoError(t, err)
		if err == nil {
			assert.Equal(t, pubkey.Serialize(), pkRecover.Serialize())
		}

		// Screw up the signature at a random bit and make sure that breaks it.
		sigBad := sig.Serialize()
		pos := tRand.Intn(63)
		bitPos := tRand.Intn(7)
		sigBad[pos] ^= 1 << uint8(bitPos)
		_, err = schnorrVerify(curve, sigBad, pubkey, tv.msg,
			testSchnorrHash)
		assert.Error(t, err)

		// Make sure it breaks pubkey recovery too.
		valid := false
		pkRecover, valid, err = schnorrRecover(curve, sigBad, tv.msg,
			testSchnorrHash)
		if valid {
			assert.NotEqual(t, pubkey.Serialize(), pkRecover.Serialize())
		} else {
			assert.Error(t, err)
		}
	}
}
示例#7
0
// This example demonstrates encrypting a message for a public key that is first
// parsed from raw bytes, then decrypting it using the corresponding private key.
func Example_encryptMessage() {
	// Decode the hex-encoded pubkey of the recipient.
	pubKeyBytes, err := hex.DecodeString("04115c42e757b2efb7671c578530ec191a1" +
		"359381e6a71127a9d37c486fd30dae57e76dc58f693bd7e7010358ce6b165e483a29" +
		"21010db67ac11b1b51b651953d2") // uncompressed pubkey
	if err != nil {
		fmt.Println(err)
		return
	}
	pubKey, err := secp256k1.ParsePubKey(pubKeyBytes, secp256k1.S256())
	if err != nil {
		fmt.Println(err)
		return
	}

	// Encrypt a message decryptable by the private key corresponding to pubKey
	message := "test message"
	ciphertext, err := secp256k1.Encrypt(pubKey, []byte(message))
	if err != nil {
		fmt.Println(err)
		return
	}

	// Decode the hex-encoded private key.
	pkBytes, err := hex.DecodeString("a11b0a4e1a132305652ee7a8eb7848f6ad" +
		"5ea381e3ce20a2c086a2e388230811")
	if err != nil {
		fmt.Println(err)
		return
	}
	// note that we already have corresponding pubKey
	privKey, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), pkBytes)

	// Try decrypting and verify if it's the same message.
	plaintext, err := secp256k1.Decrypt(privKey, ciphertext)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(plaintext))

	// Output:
	// test message
}
示例#8
0
func TestPrivKeys(t *testing.T) {
	tests := []struct {
		name string
		key  []byte
	}{
		{
			name: "check curve",
			key: []byte{
				0xea, 0xf0, 0x2c, 0xa3, 0x48, 0xc5, 0x24, 0xe6,
				0x39, 0x26, 0x55, 0xba, 0x4d, 0x29, 0x60, 0x3c,
				0xd1, 0xa7, 0x34, 0x7d, 0x9d, 0x65, 0xcf, 0xe9,
				0x3c, 0xe1, 0xeb, 0xff, 0xdc, 0xa2, 0x26, 0x94,
			},
		},
	}

	for _, test := range tests {
		priv, pub := secp256k1.PrivKeyFromBytes(secp256k1.S256(), test.key)

		_, err := secp256k1.ParsePubKey(
			pub.SerializeUncompressed(), secp256k1.S256())
		if err != nil {
			t.Errorf("%s privkey: %v", test.name, err)
			continue
		}

		hash := []byte{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9}
		sig, err := priv.Sign(hash)
		if err != nil {
			t.Errorf("%s could not sign: %v", test.name, err)
			continue
		}

		if !sig.Verify(hash, pub) {
			t.Errorf("%s could not verify: %v", test.name, err)
			continue
		}

		serializedKey := priv.Serialize()
		if !bytes.Equal(serializedKey, test.key) {
			t.Errorf("%s unexpected serialized bytes - got: %x, "+
				"want: %x", test.name, serializedKey, test.key)
		}
	}
}
示例#9
0
// Test 2: Byte compatibility with Pyelliptic
func TestCiphering(t *testing.T) {
	pb, _ := hex.DecodeString("fe38240982f313ae5afb3e904fb8215fb11af1200592b" +
		"fca26c96c4738e4bf8f")
	privkey, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), pb)

	in := []byte("This is just a test.")
	out, _ := hex.DecodeString("b0d66e5adaa5ed4e2f0ca68e17b8f2fc02ca002009e3" +
		"3487e7fa4ab505cf34d98f131be7bd258391588ca7804acb30251e71a04e0020ecf" +
		"df0f84608f8add82d7353af780fbb28868c713b7813eb4d4e61f7b75d7534dd9856" +
		"9b0ba77cf14348fcff80fee10e11981f1b4be372d93923e9178972f69937ec850ed" +
		"6c3f11ff572ddd5b2bedf9f9c0b327c54da02a28fcdce1f8369ffec")

	dec, err := secp256k1.Decrypt(privkey, out)
	if err != nil {
		t.Fatal("failed to decrypt:", err)
	}

	if !bytes.Equal(in, dec) {
		t.Error("decrypted data doesn't match original")
	}
}
示例#10
0
func TestSchnorrThreshold(t *testing.T) {
	tRand := rand.New(rand.NewSource(54321))
	maxSignatories := 10
	numTests := 100
	numSignatories := maxSignatories * numTests

	curve := secp256k1.S256()
	msg, _ := hex.DecodeString(
		"07BE073995BF78D440B660AF7B06DC0E9BA120A8D686201989BA99AA384ADF12")
	privkeys := randPrivKeyList(curve, numSignatories)

	for i := 0; i < numTests; i++ {
		numKeysForTest := tRand.Intn(maxSignatories-2) + 2
		keyIndex := i * maxSignatories
		keysToUse := make([]*secp256k1.PrivateKey, numKeysForTest, numKeysForTest)
		for j := 0; j < numKeysForTest; j++ {
			keysToUse[j] = privkeys[j+keyIndex]
		}
		pubKeysToUse := make([]*secp256k1.PublicKey, numKeysForTest,
			numKeysForTest)
		for j := 0; j < numKeysForTest; j++ {
			_, pubkey := secp256k1.PrivKeyFromBytes(curve,
				keysToUse[j].Serialize())
			pubKeysToUse[j] = pubkey
		}
		privNoncesToUse := make([]*secp256k1.PrivateKey, numKeysForTest,
			numKeysForTest)
		pubNoncesToUse := make([]*secp256k1.PublicKey, numKeysForTest,
			numKeysForTest)
		for j := 0; j < numKeysForTest; j++ {
			nonce := nonceRFC6979(keysToUse[j].Serialize(), msg, nil,
				BlakeVersionStringRFC6979)
			privNonce, pubNonce := secp256k1.PrivKeyFromBytes(curve,
				nonce)
			privNoncesToUse[j] = privNonce
			pubNoncesToUse[j] = pubNonce
		}

		partialSignatures := make([]*Signature, numKeysForTest, numKeysForTest)

		// Partial signature generation.
		for j := range keysToUse {
			thisPubNonce := pubNoncesToUse[j]
			localPubNonces := make([]*secp256k1.PublicKey, numKeysForTest-1,
				numKeysForTest-1)
			itr := 0
			for _, pubNonce := range pubNoncesToUse {
				if bytes.Equal(thisPubNonce.Serialize(), pubNonce.Serialize()) {
					continue
				}
				localPubNonces[itr] = pubNonce
				itr++
			}
			publicNonceSum := CombinePubkeys(curve, localPubNonces)

			sig, err := schnorrPartialSign(curve, msg, keysToUse[j].Serialize(),
				privNoncesToUse[j].Serialize(), publicNonceSum,
				chainhash.HashFuncB)
			assert.NoError(t, err)

			partialSignatures[j] = sig
		}

		// Combine signatures.
		combinedSignature, err := CombineSigs(curve, partialSignatures)
		assert.NoError(t, err)

		// Combine pubkeys.
		allPubkeys := make([]*secp256k1.PublicKey, numKeysForTest,
			numKeysForTest)
		for j, pubkey := range pubKeysToUse {
			allPubkeys[j] = pubkey
		}
		allPksSum := CombinePubkeys(curve, allPubkeys)

		// Verify the combined signature and public keys.
		ok, err := schnorrVerify(curve, combinedSignature.Serialize(),
			allPksSum, msg, chainhash.HashFuncB)
		assert.NoError(t, err)
		assert.Equal(t, true, ok)

		// Corrupt some memory and make sure it breaks something.
		corruptWhat := tRand.Intn(3)
		randItem := tRand.Intn(numKeysForTest - 1)

		// Corrupt private key.
		if corruptWhat == 0 {
			privSerCorrupt := keysToUse[randItem].Serialize()
			pos := tRand.Intn(31)
			bitPos := tRand.Intn(7)
			privSerCorrupt[pos] ^= 1 << uint8(bitPos)
			keysToUse[randItem].D.SetBytes(privSerCorrupt)
		}
		// Corrupt public key.
		if corruptWhat == 1 {
			pubXCorrupt := BigIntToEncodedBytes(pubKeysToUse[randItem].GetX())
			pos := tRand.Intn(31)
			bitPos := tRand.Intn(7)
			pubXCorrupt[pos] ^= 1 << uint8(bitPos)
			pubKeysToUse[randItem].GetX().SetBytes(pubXCorrupt[:])
		}
		// Corrupt private nonce.
		if corruptWhat == 2 {
			privSerCorrupt := privNoncesToUse[randItem].Serialize()
			pos := tRand.Intn(31)
			bitPos := tRand.Intn(7)
			privSerCorrupt[pos] ^= 1 << uint8(bitPos)
			privNoncesToUse[randItem].D.SetBytes(privSerCorrupt)
		}
		// Corrupt public nonce.
		if corruptWhat == 3 {
			pubXCorrupt := BigIntToEncodedBytes(pubNoncesToUse[randItem].GetX())
			pos := tRand.Intn(31)
			bitPos := tRand.Intn(7)
			pubXCorrupt[pos] ^= 1 << uint8(bitPos)
			pubNoncesToUse[randItem].GetX().SetBytes(pubXCorrupt[:])
		}

		for j := range keysToUse {
			thisPubNonce := pubNoncesToUse[j]
			localPubNonces := make([]*secp256k1.PublicKey, numKeysForTest-1,
				numKeysForTest-1)
			itr := 0
			for _, pubNonce := range pubNoncesToUse {
				if bytes.Equal(thisPubNonce.Serialize(), pubNonce.Serialize()) {
					continue
				}
				localPubNonces[itr] = pubNonce
				itr++
			}
			publicNonceSum := CombinePubkeys(curve, localPubNonces)

			sig, _ := schnorrPartialSign(curve, msg, keysToUse[j].Serialize(),
				privNoncesToUse[j].Serialize(), publicNonceSum,
				chainhash.HashFuncB)

			partialSignatures[j] = sig
		}

		// Combine signatures.
		combinedSignature, _ = CombineSigs(curve, partialSignatures)

		// Combine pubkeys.
		allPubkeys = make([]*secp256k1.PublicKey, numKeysForTest,
			numKeysForTest)
		for j, pubkey := range pubKeysToUse {
			allPubkeys[j] = pubkey
		}
		allPksSum = CombinePubkeys(curve, allPubkeys)

		// Nothing that makes it here should be valid.
		if allPksSum != nil && combinedSignature != nil {
			ok, _ = schnorrVerify(curve, combinedSignature.Serialize(),
				allPksSum, msg, chainhash.HashFuncB)
			assert.Equal(t, false, ok)
		}
	}
}
示例#11
0
func TestSchnorrThresholdRef(t *testing.T) {
	curve := secp256k1.S256()
	tvs := GetThresholdTestVectors()
	for _, tv := range tvs {
		partialSignatures := make([]*Signature, len(tv.signers), len(tv.signers))

		// Ensure all the pubkey and nonce derivation is correct.
		for i, signer := range tv.signers {
			nonce := nonceRFC6979(signer.privkey, tv.msg, nil,
				Sha256VersionStringRFC6979)
			assert.Equal(t, nonce, signer.privateNonce)

			_, pubkey := secp256k1.PrivKeyFromBytes(curve, signer.privkey)
			assert.Equal(t, pubkey.Serialize(), signer.pubkey.Serialize())

			_, pubNonce := secp256k1.PrivKeyFromBytes(curve, nonce)
			assert.Equal(t, pubNonce.Serialize(), signer.publicNonce.Serialize())

			// Calculate the public nonce sum.
			pubKeys := make([]*secp256k1.PublicKey, len(tv.signers)-1,
				len(tv.signers)-1)

			itr := 0
			for _, signer := range tv.signers {
				if bytes.Equal(signer.publicNonce.Serialize(),
					tv.signers[i].publicNonce.Serialize()) {
					continue
				}
				pubKeys[itr] = signer.publicNonce
				itr++
			}
			publicNonceSum := CombinePubkeys(curve, pubKeys)
			assert.Equal(t, publicNonceSum, signer.pubKeySumLocal)

			sig, err := schnorrPartialSign(curve, tv.msg, signer.privkey, nonce,
				publicNonceSum, testSchnorrSha256Hash)
			assert.NoError(t, err)
			assert.Equal(t, sig.Serialize(), signer.partialSignature)

			partialSignatures[i] = sig
		}

		// Combine signatures.
		combinedSignature, err := CombineSigs(curve, partialSignatures)
		assert.NoError(t, err)
		assert.Equal(t, combinedSignature.Serialize(), tv.combinedSignature)

		// Combine pubkeys.
		allPubkeys := make([]*secp256k1.PublicKey, len(tv.signers),
			len(tv.signers))
		for i, signer := range tv.signers {
			allPubkeys[i] = signer.pubkey
		}
		allPksSum := CombinePubkeys(curve, allPubkeys)

		// Verify the combined signature and public keys.
		ok, err := schnorrVerify(curve, combinedSignature.Serialize(),
			allPksSum, tv.msg, testSchnorrSha256Hash)
		assert.NoError(t, err)
		assert.Equal(t, true, ok)
	}
}
示例#12
0
// newSecSchnorrDSA instatiates a function DSA subsystem over the secp256k1
// curve. A caveat for the functions below is that they're all routed through
// interfaces, and nil returns from the library itself for interfaces must
// ALWAYS be checked by checking the return value by attempted dereference
// (== nil).
func newSecSchnorrDSA() DSA {
	var secp DSA = &secSchnorrDSA{
		// Constants
		getP: func() *big.Int {
			return secp256k1Curve.P
		},
		getN: func() *big.Int {
			return secp256k1Curve.N
		},

		// EC Math
		add: func(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {
			return secp256k1Curve.Add(x1, y1, x2, y2)
		},
		isOnCurve: func(x, y *big.Int) bool {
			return secp256k1Curve.IsOnCurve(x, y)
		},
		scalarMult: func(x, y *big.Int, k []byte) (*big.Int, *big.Int) {
			return secp256k1Curve.ScalarMult(x, y, k)
		},
		scalarBaseMult: func(k []byte) (*big.Int, *big.Int) {
			return secp256k1Curve.ScalarBaseMult(k)
		},

		// Private keys
		newPrivateKey: func(d *big.Int) PrivateKey {
			pk := secp256k1.NewPrivateKey(secp256k1Curve, d)
			if pk != nil {
				return PrivateKey(pk)
			}
			return nil
		},
		privKeyFromBytes: func(pk []byte) (PrivateKey, PublicKey) {
			priv, pub := secp256k1.PrivKeyFromBytes(secp256k1Curve, pk)
			if priv == nil {
				return nil, nil
			}
			if pub == nil {
				return nil, nil
			}
			tpriv := PrivateKey(priv)
			tpub := PublicKey(pub)
			return tpriv, tpub
		},
		privKeyFromScalar: func(pk []byte) (PrivateKey, PublicKey) {
			priv, pub := secp256k1.PrivKeyFromScalar(secp256k1Curve, pk)
			if priv == nil {
				return nil, nil
			}
			if pub == nil {
				return nil, nil
			}
			tpriv := PrivateKey(priv)
			tpub := PublicKey(pub)
			return tpriv, tpub
		},
		privKeyBytesLen: func() int {
			return secp256k1.PrivKeyBytesLen
		},

		// Public keys
		// Note that Schnorr only allows 33 byte public keys, however
		// as they are secp256k1 you still have access to the other
		// serialization types.
		newPublicKey: func(x *big.Int, y *big.Int) PublicKey {
			pk := secp256k1.NewPublicKey(secp256k1Curve, x, y)
			tpk := PublicKey(pk)
			return tpk
		},
		parsePubKey: func(pubKeyStr []byte) (PublicKey, error) {
			pk, err := schnorr.ParsePubKey(secp256k1Curve, pubKeyStr)
			if err != nil {
				return nil, err
			}
			tpk := PublicKey(pk)
			return tpk, err
		},
		pubKeyBytesLen: func() int {
			return schnorr.PubKeyBytesLen
		},
		pubKeyBytesLenUncompressed: func() int {
			return schnorr.PubKeyBytesLen
		},
		pubKeyBytesLenCompressed: func() int {
			return schnorr.PubKeyBytesLen
		},
		pubKeyBytesLenHybrid: func() int {
			return schnorr.PubKeyBytesLen
		},

		// Signatures
		newSignature: func(r *big.Int, s *big.Int) Signature {
			sig := schnorr.NewSignature(r, s)
			ts := Signature(sig)
			return ts
		},
		parseDERSignature: func(sigStr []byte) (Signature, error) {
			sig, err := schnorr.ParseSignature(sigStr)
			ts := Signature(sig)
			return ts, err
		},
		parseSignature: func(sigStr []byte) (Signature, error) {
			sig, err := schnorr.ParseSignature(sigStr)
			ts := Signature(sig)
			return ts, err
		},
		recoverCompact: func(signature, hash []byte) (PublicKey, bool, error) {
			pk, bl, err := schnorr.RecoverPubkey(secp256k1Curve, signature,
				hash)
			tpk := PublicKey(pk)
			return tpk, bl, err
		},

		// ECDSA
		generateKey: func(rand io.Reader) ([]byte, *big.Int, *big.Int, error) {
			return secp256k1.GenerateKey(secp256k1Curve, rand)
		},
		sign: func(priv PrivateKey, hash []byte) (r, s *big.Int, err error) {
			spriv := secp256k1.NewPrivateKey(secp256k1Curve, priv.GetD())
			return schnorr.Sign(secp256k1Curve, spriv, hash)
		},
		verify: func(pub PublicKey, hash []byte, r, s *big.Int) bool {
			spub := secp256k1.NewPublicKey(secp256k1Curve, pub.GetX(), pub.GetY())
			return schnorr.Verify(secp256k1Curve, spub, hash, r, s)
		},

		// Symmetric cipher encryption
		generateSharedSecret: func(privkey []byte, x, y *big.Int) []byte {
			sprivkey, _ := secp256k1.PrivKeyFromBytes(secp256k1Curve, privkey)
			if sprivkey == nil {
				return nil
			}
			spubkey := secp256k1.NewPublicKey(secp256k1Curve, x, y)

			return secp256k1.GenerateSharedSecret(sprivkey, spubkey)
		},
		encrypt: func(x, y *big.Int, in []byte) ([]byte, error) {
			spubkey := secp256k1.NewPublicKey(secp256k1Curve, x, y)

			return secp256k1.Encrypt(spubkey, in)
		},
		decrypt: func(privkey []byte, in []byte) ([]byte, error) {
			sprivkey, _ := secp256k1.PrivKeyFromBytes(secp256k1Curve, privkey)
			if sprivkey == nil {
				return nil, fmt.Errorf("failure deserializing privkey")
			}

			return secp256k1.Decrypt(sprivkey, in)
		},
	}

	return secp.(DSA)
}
示例#13
0
func TestRFC6979(t *testing.T) {
	// Test vectors matching Trezor and CoreBitcoin implementations.
	// - https://github.com/trezor/trezor-crypto/blob/9fea8f8ab377dc514e40c6fd1f7c89a74c1d8dc6/tests.c#L432-L453
	// - https://github.com/oleganza/CoreBitcoin/blob/e93dd71207861b5bf044415db5fa72405e7d8fbc/CoreBitcoin/BTCKey%2BTests.m#L23-L49
	tests := []struct {
		key       string
		msg       string
		nonce     string
		signature string
	}{
		{
			"cca9fbcc1b41e5a95d369eaa6ddcff73b61a4efaa279cfc6567e8daa39cbaf50",
			"sample",
			"2df40ca70e639d89528a6b670d9d48d9165fdc0febc0974056bdce192b8e16a3",
			"3045022100af340daf02cc15c8d5d08d7735dfe6b98a474ed373bdb5fbecf7571be52b384202205009fb27f37034a9b24b707b7c6b79ca23ddef9e25f7282e8a797efe53a8f124",
		},
		{
			// This signature hits the case when S is higher than halforder.
			// If S is not canonicalized (lowered by halforder), this test will fail.
			"0000000000000000000000000000000000000000000000000000000000000001",
			"Satoshi Nakamoto",
			"8f8a276c19f4149656b280621e358cce24f5f52542772691ee69063b74f15d15",
			"3045022100934b1ea10a4b3c1757e2b0c017d0b6143ce3c9a7e6a4a49860d7a6ab210ee3d802202442ce9d2b916064108014783e923ec36b49743e2ffa1c4496f01a512aafd9e5",
		},
		{
			"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",
			"Satoshi Nakamoto",
			"33a19b60e25fb6f4435af53a3d42d493644827367e6453928554f43e49aa6f90",
			"3045022100fd567d121db66e382991534ada77a6bd3106f0a1098c231e47993447cd6af2d002206b39cd0eb1bc8603e159ef5c20a5c8ad685a45b06ce9bebed3f153d10d93bed5",
		},
		{
			"f8b8af8ce3c7cca5e300d33939540c10d45ce001b8f252bfbc57ba0342904181",
			"Alan Turing",
			"525a82b70e67874398067543fd84c83d30c175fdc45fdeee082fe13b1d7cfdf1",
			"304402207063ae83e7f62bbb171798131b4a0564b956930092b33b07b395615d9ec7e15c022058dfcc1e00a35e1572f366ffe34ba0fc47db1e7189759b9fb233c5b05ab388ea",
		},
		{
			"0000000000000000000000000000000000000000000000000000000000000001",
			"All those moments will be lost in time, like tears in rain. Time to die...",
			"38aa22d72376b4dbc472e06c3ba403ee0a394da63fc58d88686c611aba98d6b3",
			"30450221008600dbd41e348fe5c9465ab92d23e3db8b98b873beecd930736488696438cb6b0220547fe64427496db33bf66019dacbf0039c04199abb0122918601db38a72cfc21",
		},
		{
			"e91671c46231f833a6406ccbea0e3e392c76c167bac1cb013f6f1013980455c2",
			"There is a computer disease that anybody who works with computers knows about. It's a very serious disease and it interferes completely with the work. The trouble with computers is that you 'play' with them!",
			"1f4b84c23a86a221d233f2521be018d9318639d5b8bbd6374a8a59232d16ad3d",
			"3045022100b552edd27580141f3b2a5463048cb7cd3e047b97c9f98076c32dbdf85a68718b0220279fa72dd19bfae05577e06c7c0c1900c371fcd5893f7e1d56a37d30174671f6",
		},
	}

	for i, test := range tests {
		privKey, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), decodeHex(test.key))
		hash := sha256.Sum256([]byte(test.msg))

		// Ensure deterministically generated nonce is the expected value.
		gotNonce := secp256k1.TstNonceRFC6979(privKey.D, hash[:]).Bytes()
		wantNonce := decodeHex(test.nonce)
		if !bytes.Equal(gotNonce, wantNonce) {
			t.Errorf("NonceRFC6979 #%d (%s): Nonce is incorrect: "+
				"%x (expected %x)", i, test.msg, gotNonce,
				wantNonce)
			continue
		}

		// Ensure deterministically generated signature is the expected value.
		gotSig, err := privKey.Sign(hash[:])
		if err != nil {
			t.Errorf("Sign #%d (%s): unexpected error: %v", i,
				test.msg, err)
			continue
		}
		gotSigBytes := gotSig.Serialize()
		wantSigBytes := decodeHex(test.signature)
		if !bytes.Equal(gotSigBytes, wantSigBytes) {
			t.Errorf("Sign #%d (%s): mismatched signature: %x "+
				"(expected %x)", i, test.msg, gotSigBytes,
				wantSigBytes)
			continue
		}
	}
}
示例#14
0
文件: secp256k1.go 项目: decred/dcrd
// newSecp256k1DSA instatiates a function DSA subsystem over the secp256k1
// curve. A caveat for the functions below is that they're all routed through
// interfaces, and nil returns from the library itself for interfaces must
// ALWAYS be checked by checking the return value by attempted dereference
// (== nil).
func newSecp256k1DSA() DSA {
	var secp DSA = &secp256k1DSA{
		// Constants
		getP: func() *big.Int {
			return secp256k1Curve.P
		},
		getN: func() *big.Int {
			return secp256k1Curve.N
		},

		// EC Math
		add: func(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {
			return secp256k1Curve.Add(x1, y1, x2, y2)
		},
		isOnCurve: func(x, y *big.Int) bool {
			return secp256k1Curve.IsOnCurve(x, y)
		},
		scalarMult: func(x, y *big.Int, k []byte) (*big.Int, *big.Int) {
			return secp256k1Curve.ScalarMult(x, y, k)
		},
		scalarBaseMult: func(k []byte) (*big.Int, *big.Int) {
			return secp256k1Curve.ScalarBaseMult(k)
		},

		// Private keys
		newPrivateKey: func(d *big.Int) PrivateKey {
			if d == nil {
				return nil
			}
			pk := secp256k1.NewPrivateKey(secp256k1Curve, d)
			if pk != nil {
				return PrivateKey(pk)
			}
			return nil
		},
		privKeyFromBytes: func(pk []byte) (PrivateKey, PublicKey) {
			priv, pub := secp256k1.PrivKeyFromBytes(secp256k1Curve, pk)
			if priv == nil {
				return nil, nil
			}
			if pub == nil {
				return nil, nil
			}
			tpriv := PrivateKey(priv)
			tpub := PublicKey(pub)
			return tpriv, tpub
		},
		privKeyFromScalar: func(pk []byte) (PrivateKey, PublicKey) {
			priv, pub := secp256k1.PrivKeyFromScalar(secp256k1Curve, pk)
			if priv == nil {
				return nil, nil
			}
			if pub == nil {
				return nil, nil
			}
			tpriv := PrivateKey(priv)
			tpub := PublicKey(pub)
			return tpriv, tpub
		},
		privKeyBytesLen: func() int {
			return secp256k1.PrivKeyBytesLen
		},

		// Public keys
		newPublicKey: func(x *big.Int, y *big.Int) PublicKey {
			pk := secp256k1.NewPublicKey(secp256k1Curve, x, y)
			tpk := PublicKey(pk)
			return tpk
		},
		parsePubKey: func(pubKeyStr []byte) (PublicKey, error) {
			pk, err := secp256k1.ParsePubKey(pubKeyStr, secp256k1Curve)
			if err != nil {
				return nil, err
			}
			tpk := PublicKey(pk)
			return tpk, err
		},
		pubKeyBytesLen: func() int {
			return secp256k1.PubKeyBytesLenCompressed
		},
		pubKeyBytesLenUncompressed: func() int {
			return secp256k1.PubKeyBytesLenUncompressed
		},
		pubKeyBytesLenCompressed: func() int {
			return secp256k1.PubKeyBytesLenCompressed
		},
		pubKeyBytesLenHybrid: func() int {
			return secp256k1.PubKeyBytesLenHybrid
		},

		// Signatures
		newSignature: func(r *big.Int, s *big.Int) Signature {
			sig := secp256k1.NewSignature(r, s)
			ts := Signature(sig)
			return ts
		},
		parseDERSignature: func(sigStr []byte) (Signature, error) {
			sig, err := secp256k1.ParseDERSignature(sigStr, secp256k1Curve)
			if err != nil {
				return nil, err
			}
			ts := Signature(sig)
			return ts, err
		},
		parseSignature: func(sigStr []byte) (Signature, error) {
			sig, err := secp256k1.ParseSignature(sigStr, secp256k1Curve)
			if err != nil {
				return nil, err
			}
			ts := Signature(sig)
			return ts, err
		},
		recoverCompact: func(signature, hash []byte) (PublicKey, bool, error) {
			pk, bl, err := secp256k1.RecoverCompact(secp256k1Curve, signature,
				hash)
			tpk := PublicKey(pk)
			return tpk, bl, err
		},

		// ECDSA
		generateKey: func(rand io.Reader) ([]byte, *big.Int, *big.Int, error) {
			return secp256k1.GenerateKey(secp256k1Curve, rand)
		},
		sign: func(priv PrivateKey, hash []byte) (r, s *big.Int, err error) {
			if priv.GetType() != ECTypeSecp256k1 {
				return nil, nil, errors.New("wrong type")
			}
			spriv, ok := priv.(*secp256k1.PrivateKey)
			if !ok {
				return nil, nil, errors.New("wrong type")
			}
			sig, err := spriv.Sign(hash)
			if sig != nil {
				r = sig.GetR()
				s = sig.GetS()
			}
			return
		},
		verify: func(pub PublicKey, hash []byte, r, s *big.Int) bool {
			spub := secp256k1.NewPublicKey(secp256k1Curve, pub.GetX(), pub.GetY())
			ssig := secp256k1.NewSignature(r, s)
			return ssig.Verify(hash, spub)
		},

		// Symmetric cipher encryption
		generateSharedSecret: func(privkey []byte, x, y *big.Int) []byte {
			sprivkey, _ := secp256k1.PrivKeyFromBytes(secp256k1Curve, privkey)
			if sprivkey == nil {
				return nil
			}
			spubkey := secp256k1.NewPublicKey(secp256k1Curve, x, y)

			return secp256k1.GenerateSharedSecret(sprivkey, spubkey)
		},
		encrypt: func(x, y *big.Int, in []byte) ([]byte, error) {
			spubkey := secp256k1.NewPublicKey(secp256k1Curve, x, y)

			return secp256k1.Encrypt(spubkey, in)
		},
		decrypt: func(privkey []byte, in []byte) ([]byte, error) {
			sprivkey, _ := secp256k1.PrivKeyFromBytes(secp256k1Curve, privkey)
			if sprivkey == nil {
				return nil, fmt.Errorf("failure deserializing privkey")
			}

			return secp256k1.Decrypt(sprivkey, in)
		},
	}

	return secp.(DSA)
}