示例#1
0
// BenchmarkSigVerify benchmarks how long it takes the secp256k1 curve to
// verify signatures.
func BenchmarkSigVerify(b *testing.B) {
	b.StopTimer()
	// Randomly generated keypair.
	// Private key: 9e0699c91ca1e3b7e3c9ba71eb71c89890872be97576010fe593fbf3fd57e66d
	pubKey := ecdsa.PublicKey{
		Curve: btcec.S256(),
		X:     fromHex("d2e670a19c6d753d1a6d8b20bd045df8a08fb162cf508956c31268c6d81ffdab"),
		Y:     fromHex("ab65528eefbb8057aa85d597258a3fbd481a24633bc9b47a9aa045c91371de52"),
	}

	// Double sha256 of []byte{0x01, 0x02, 0x03, 0x04}
	msgHash := fromHex("8de472e2399610baaa7f84840547cd409434e31f5d3bd71e4d947f283874f9c0")
	sigR := fromHex("fef45d2892953aa5bbcdb057b5e98b208f1617a7498af7eb765574e29b5d9c2c")
	sigS := fromHex("d47563f52aac6b04b55de236b7c515eb9311757db01e02cff079c3ca6efb063f")

	if !ecdsa.Verify(&pubKey, msgHash.Bytes(), sigR, sigS) {
		b.Errorf("Signature failed to verify")
		return
	}
	b.StartTimer()

	for i := 0; i < b.N; i++ {
		ecdsa.Verify(&pubKey, msgHash.Bytes(), sigR, sigS)
	}
}
示例#2
0
// VerifySignature returns nil iff sig is a valid signature, made by this
// public key, of the data hashed into signed. signed is mutated by this call.
func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) {
	if !pk.CanSign() {
		return errors.InvalidArgumentError("public key cannot generate signatures")
	}

	signed.Write(sig.HashSuffix)
	hashBytes := signed.Sum(nil)

	// NOTE(maxtaco) 2016-08-22
	//
	// We used to do this:
	//
	// if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
	//	  return errors.SignatureError("hash tag doesn't match")
	// }
	//
	// But don't do anything in this case. Some GPGs generate bad
	// 2-byte hash prefixes, but GPG also doesn't seem to care on
	// import. See BrentMaxwell's key. I think it's safe to disable
	// this check!

	if pk.PubKeyAlgo != sig.PubKeyAlgo {
		return errors.InvalidArgumentError("public key and signature use different algorithms")
	}

	switch pk.PubKeyAlgo {
	case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
		rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey)
		err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes)
		if err != nil {
			return errors.SignatureError("RSA verification failure")
		}
		return nil
	case PubKeyAlgoDSA:
		dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
		// Need to truncate hashBytes to match FIPS 186-3 section 4.6.
		subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8
		if len(hashBytes) > subgroupSize {
			hashBytes = hashBytes[:subgroupSize]
		}
		if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
			return errors.SignatureError("DSA verification failure")
		}
		return nil
	case PubKeyAlgoECDSA:
		ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey)
		if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.bytes), new(big.Int).SetBytes(sig.ECDSASigS.bytes)) {
			return errors.SignatureError("ECDSA verification failure")
		}
		return nil
	case PubKeyAlgoEdDSA:
		if !pk.edk.Verify(hashBytes, sig.EdDSASigR, sig.EdDSASigS) {
			return errors.SignatureError("EdDSA verification failure")
		}
		return nil
	default:
		return errors.SignatureError("Unsupported public key algorithm used in signature")
	}
	panic("unreachable")
}
示例#3
0
// FinishKEX verifies the signed public key. If it is valid, it will
// carry out an ECDH key agreement, zeroise the private key, and store
// the shared key.
func (kex *Session) FinishKEX(signer *ecdsa.PublicKey, signed []byte) error {
	var skey signedKey
	rest, err := asn1.Unmarshal(signed, &skey)
	if err != nil {
		return err
	} else if len(rest) != 0 {
		return errors.New("eckex: trailing data in key exchange")
	}

	hashed := sha256.Sum256(skey.Public)

	if !ecdsa.Verify(signer, hashed[:], skey.R, skey.S) {
		return errors.New("eckex: verification failure")
	}

	pub, err := unpackECPKIX(skey.Public)
	if err != nil {
		return err
	}

	priv, err := x509.ParseECPrivateKey(kex.priv)
	util.Zero(kex.priv)
	if err != nil {
		return err
	}

	kex.shared, err = nistecdh.ECDH(priv, pub)
	kex.shared = kex.shared[:32]
	return err
}
示例#4
0
// Verify the secret key's range and if a test message signed with it verifies OK
// Returns nil if averything looks OK
func VerifyKeyPair(priv []byte, publ []byte) error {
	const TestMessage = "Just some test message..."
	hash := Sha2Sum([]byte(TestMessage))

	pub_key, e := NewPublicKey(publ)
	if e != nil {
		return e
	}

	var key ecdsa.PrivateKey
	key.D = new(big.Int).SetBytes(priv)
	key.PublicKey = pub_key.PublicKey

	if key.D.Cmp(big.NewInt(0)) == 0 {
		return errors.New("pubkey value is zero")
	}

	if key.D.Cmp(secp256k1.N) != -1 {
		return errors.New("pubkey value is too big")
	}

	r, s, err := ecdsa.Sign(rand.Reader, &key, hash[:])
	if err != nil {
		return errors.New("ecdsa.Sign failed: " + err.Error())
	}

	ok := ecdsa.Verify(&key.PublicKey, hash[:], r, s)
	if !ok {
		return errors.New("ecdsa.Sign Verify")
	}
	return nil
}
示例#5
0
文件: ecc.go 项目: knq/jwt
// VerifyBytes creates a signature for buf, comparing it against the raw sig.
// If the sig is invalid, then ErrInvalidSignature is returned.
func (es *eccSigner) VerifyBytes(buf, sig []byte) error {
	var err error

	// check es.pub
	if es.pub == nil {
		return errors.New("eccSigner.VerifyBytes: pub cannot be nil")
	}

	// hash
	h := es.hash.New()
	_, err = h.Write(buf)
	if err != nil {
		return err
	}

	// check decoded length
	if len(sig) != 2*es.keyLen {
		return ErrInvalidSignature
	}

	r := big.NewInt(0).SetBytes(sig[:es.keyLen])
	s := big.NewInt(0).SetBytes(sig[es.keyLen:])

	// verify
	if !ecdsa.Verify(es.pub, h.Sum(nil), r, s) {
		return ErrInvalidSignature
	}

	return nil
}
示例#6
0
// TestSign - Return signatures for a signed message
func TestSign(w http.ResponseWriter, r *http.Request) {
	conf := ConfLoad()

	// Returns a Public / Private Key Pair
	// Read JSON config from app.yaml
	if v := os.Getenv("PRIV_KEY"); v != "" {
		err := json.Unmarshal([]byte(v), &conf)
		if err != nil {
			fmt.Printf("%#v", conf)
			panic(err)
		}
	}

	// Get the public key
	var pubkey ecdsa.PublicKey
	pubkey = conf.PublicKey

	// Try signing a message
	message := []byte("99999999")
	sig1, sig2, err := ecdsa.Sign(rand.Reader, &conf.PrivateKey, message)
	if err != nil {
		panic(err)
	}

	// Try verifying the signature
	result := ecdsa.Verify(&pubkey, message, sig1, sig2)
	if result != true {
		panic("Unable to verify signature")
	}

	fmt.Fprintf(w, "message: %#v\n\nsig1: %#v\nsig2: %#v", string(message[:]), sig1, sig2)

}
示例#7
0
文件: btcec_test.go 项目: hsk81/btcec
func TestVectors(t *testing.T) {
	sha := sha1.New()

	for i, test := range testVectors {
		pub := ecdsa.PublicKey{
			Curve: btcec.S256(),
			X:     fromHex(test.Qx),
			Y:     fromHex(test.Qy),
		}
		msg, _ := hex.DecodeString(test.msg)
		sha.Reset()
		sha.Write(msg)
		hashed := sha.Sum(nil)
		r := fromHex(test.r)
		s := fromHex(test.s)
		if f**k := ecdsa.Verify(&pub, hashed, r, s); f**k != test.ok {
			//t.Errorf("%d: bad result %v %v", i, pub, hashed)
			t.Errorf("%d: bad result %v instead of %v", i, f**k,
				test.ok)
		}
		if testing.Short() {
			break
		}
	}
}
示例#8
0
func verify(pub_key_filename string, msg []byte, signature []byte) bool {
	// load ecdsa public key from file
	pub_data, err := ioutil.ReadFile(pub_key_filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	ecpub, err := cyhcrypto.LoadECPublicKey(pub_data)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// verify signature
	v_msg_hasher := sha256.New()
	_, _ = v_msg_hasher.Write(msg)
	v_hashed := v_msg_hasher.Sum(nil)

	sig_r, sig_s, err := cyhcrypto.DecodeSignature(signature)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	result := ecdsa.Verify(ecpub, v_hashed, sig_r, sig_s)

	return result
}
示例#9
0
// verify a signature given the hash
func (v *ECDSAVerifier) VerifyHash(h, sig []byte) (err error) {
	r, s := elliptic.Unmarshal(v.c, sig)
	if r == nil || s == nil || !ecdsa.Verify(v.k, h, r, s) {
		err = ErrInvalidSignature
	}
	return
}
示例#10
0
func verifyOcSig(reqHash []byte, ocID msg.OcID, sig string) bool {
	ocCredReader := strings.NewReader(ocID.String())
	var x, y, r, s big.Int
	n, err := fmt.Fscanf(ocCredReader, string(OC_ID_PREFIX)+"%x,%x", &x, &y)
	if err != nil {
		return false
	}
	n, err = ocCredReader.Read(make([]byte, 1))
	if n != 0 || err != io.EOF {
		return false
	}

	sigReader := strings.NewReader(sig)
	n, err = fmt.Fscanf(sigReader, "%x,%x", &r, &s)
	if err != nil {
		return false
	}
	n, err = sigReader.Read(make([]byte, 1))
	if n != 0 || err != io.EOF {
		return false
	}

	curve := elliptic.P256()
	pub := ecdsa.PublicKey{
		Curve: curve,
		X:     &x,
		Y:     &y,
	}
	return ecdsa.Verify(&pub, reqHash, &r, &s)
}
示例#11
0
// Verify verifyies the signature of the data in the io.Reader using this
// PublicKey. The alg parameter should identify the digital signature
// algorithm which was used to produce the signature and should be supported
// by this public key. Returns a nil error if the signature is valid.
func (k *ecPublicKey) Verify(data io.Reader, alg string, signature []byte) error {
	// For EC keys there is only one supported signature algorithm depending
	// on the curve parameters.
	if k.signatureAlgorithm.HeaderParam() != alg {
		return fmt.Errorf("unable to verify signature: EC Public Key with curve %q does not support signature algorithm %q", k.curveName, alg)
	}

	// signature is the concatenation of (r, s), base64Url encoded.
	sigLength := len(signature)
	expectedOctetLength := 2 * ((k.Params().BitSize + 7) >> 3)
	if sigLength != expectedOctetLength {
		return fmt.Errorf("signature length is %d octets long, should be %d", sigLength, expectedOctetLength)
	}

	rBytes, sBytes := signature[:sigLength/2], signature[sigLength/2:]
	r := new(big.Int).SetBytes(rBytes)
	s := new(big.Int).SetBytes(sBytes)

	hasher := k.signatureAlgorithm.HashID().New()
	_, err := io.Copy(hasher, data)
	if err != nil {
		return fmt.Errorf("error reading data to sign: %s", err)
	}
	hash := hasher.Sum(nil)

	if !ecdsa.Verify(k.PublicKey, hash, r, s) {
		return errors.New("invalid signature")
	}

	return nil
}
示例#12
0
func TestECDSASign(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	conn, err := c.Dial(serverAddr)
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()

	sig, err := ecdsaKey.Sign(r, msg, h)
	if err != nil {
		t.Fatal(err)
	}

	if ecdsaPub, ok := ecdsaKey.Public().(*ecdsa.PublicKey); ok {
		ecdsaSig := new(struct{ R, S *big.Int })
		asn1.Unmarshal(sig, ecdsaSig)
		if !ecdsa.Verify(ecdsaPub, msg, ecdsaSig.R, ecdsaSig.S) {
			t.Log("ecdsa verify failed")
		}
	} else {
		t.Fatal("couldn't use public key as ECDSA key")
	}
}
示例#13
0
// CreateCertificate requests the creation of a new enrollment certificate by the TLSCA.
//
func (tlscap *TLSCAP) CreateCertificate(ctx context.Context, in *pb.TLSCertCreateReq) (*pb.TLSCertCreateResp, error) {
	Trace.Println("grpc TLSCAP:CreateCertificate")

	id := in.Id.Id

	sig := in.Sig
	in.Sig = nil

	r, s := big.NewInt(0), big.NewInt(0)
	r.UnmarshalText(sig.R)
	s.UnmarshalText(sig.S)

	raw := in.Pub.Key
	if in.Pub.Type != pb.CryptoType_ECDSA {
		return nil, errors.New("unsupported key type")
	}
	pub, err := x509.ParsePKIXPublicKey(in.Pub.Key)
	if err != nil {
		return nil, err
	}

	hash := utils.NewHash()
	raw, _ = proto.Marshal(in)
	hash.Write(raw)
	if ecdsa.Verify(pub.(*ecdsa.PublicKey), hash.Sum(nil), r, s) == false {
		return nil, errors.New("signature does not verify")
	}

	if raw, err = tlscap.tlsca.createCertificate(id, pub.(*ecdsa.PublicKey), x509.KeyUsageDigitalSignature, in.Ts.Seconds, nil); err != nil {
		Error.Println(err)
		return nil, err
	}

	return &pb.TLSCertCreateResp{&pb.Cert{raw}, &pb.Cert{tlscap.tlsca.raw}}, nil
}
示例#14
0
// ReadCertificate reads a transaction certificate from the TCA.
//
func (tcap *TCAP) ReadCertificate(ctx context.Context, req *pb.TCertReadReq) (*pb.Cert, error) {
	Trace.Println("grpc TCAP:ReadCertificate")

	id := req.Id.Id
	raw, err := tcap.tca.eca.readCertificate(id, x509.KeyUsageDigitalSignature)
	if err != nil {
		return nil, err
	}
	cert, err := x509.ParseCertificate(raw)
	if err != nil {
		return nil, err
	}

	sig := req.Sig
	req.Sig = nil

	r, s := big.NewInt(0), big.NewInt(0)
	r.UnmarshalText(sig.R)
	s.UnmarshalText(sig.S)

	hash := sha3.New384()
	raw, _ = proto.Marshal(req)
	hash.Write(raw)
	if ecdsa.Verify(cert.PublicKey.(*ecdsa.PublicKey), hash.Sum(nil), r, s) == false {
		return nil, errors.New("signature does not verify")
	}

	raw, err = tcap.tca.readCertificate1(id, req.Ts.Seconds)
	if err != nil {
		return nil, err
	}

	return &pb.Cert{raw}, nil
}
示例#15
0
// Verify computes the hash of data and compares it to the signature using the
// given public key. Returns nil if the signature is correct.
func Verify(pubKeyPEM []byte, signature []byte, data io.Reader) error {
	// Parse the public key
	key, err := loadPublicKey(pubKeyPEM)
	if err != nil {
		return err
	}

	// Parse the signature
	block, _ := pem.Decode(signature)
	r, s, err := unmarshalSignature(block.Bytes)
	if err != nil {
		return err
	}

	// Compute the hash of the data
	hash, err := hashReader(data)
	if err != nil {
		return err
	}

	// Verify the signature
	if !ecdsa.Verify(key, hash, r, s) {
		return errors.New("incorrect signature")
	}

	return nil
}
示例#16
0
func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error {
	if sig.Format != key.Type() {
		return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type())
	}

	h := ecHash(key.Curve).New()
	h.Write(data)
	digest := h.Sum(nil)

	// Per RFC 5656, section 3.1.2,
	// The ecdsa_signature_blob value has the following specific encoding:
	//    mpint    r
	//    mpint    s
	var ecSig struct {
		R *big.Int
		S *big.Int
	}

	if err := Unmarshal(sig.Blob, &ecSig); err != nil {
		return err
	}

	if ecdsa.Verify((*ecdsa.PublicKey)(key), digest, ecSig.R, ecSig.S) {
		return nil
	}
	return errors.New("ssh: signature did not verify")
}
示例#17
0
func MyVerify(sign *Signature, pub *ecdsa.PublicKey, hashed []byte) error {
	if !ecdsa.Verify(pub, hashed, (&big.Int{}).SetBytes(sign.R), (&big.Int{}).SetBytes(sign.S)) {
		return errors.New("Verify error")
	}

	return nil
}
示例#18
0
// VerifySignature verifies that the passed in signature over data was created by the given PublicKey.
func VerifySignature(pubKey crypto.PublicKey, data []byte, sig DigitallySigned) error {
	hash, hashType, err := generateHash(sig.Algorithm.Hash, data)
	if err != nil {
		return err
	}

	switch sig.Algorithm.Signature {
	case RSA:
		rsaKey, ok := pubKey.(*rsa.PublicKey)
		if !ok {
			return fmt.Errorf("cannot verify RSA signature with %T key", pubKey)
		}
		if err := rsa.VerifyPKCS1v15(rsaKey, hashType, hash, sig.Signature); err != nil {
			return fmt.Errorf("failed to verify rsa signature: %v", err)
		}
	case DSA:
		dsaKey, ok := pubKey.(*dsa.PublicKey)
		if !ok {
			return fmt.Errorf("cannot verify DSA signature with %T key", pubKey)
		}
		var dsaSig dsaSig
		rest, err := asn1.Unmarshal(sig.Signature, &dsaSig)
		if err != nil {
			return fmt.Errorf("failed to unmarshal DSA signature: %v", err)
		}
		if len(rest) != 0 {
			log.Printf("Garbage following signature %v", rest)
		}
		if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
			return errors.New("DSA signature contained zero or negative values")
		}
		if !dsa.Verify(dsaKey, hash, dsaSig.R, dsaSig.S) {
			return errors.New("failed to verify DSA signature")
		}
	case ECDSA:
		ecdsaKey, ok := pubKey.(*ecdsa.PublicKey)
		if !ok {
			return fmt.Errorf("cannot verify ECDSA signature with %T key", pubKey)
		}
		var ecdsaSig dsaSig
		rest, err := asn1.Unmarshal(sig.Signature, &ecdsaSig)
		if err != nil {
			return fmt.Errorf("failed to unmarshal ECDSA signature: %v", err)
		}
		if len(rest) != 0 {
			log.Printf("Garbage following signature %v", rest)
		}
		if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
			return errors.New("ECDSA signature contained zero or negative values")
		}

		if !ecdsa.Verify(ecdsaKey, hash, ecdsaSig.R, ecdsaSig.S) {
			return errors.New("failed to verify ECDSA signature")
		}
	default:
		return fmt.Errorf("unsupported Algorithm.Signature in signature: %v", sig.Algorithm.Hash)
	}
	return nil
}
示例#19
0
// Verify checks a raw ECDSA signature.
// Returns true if it's valid and false if not.
func Verify(data []byte, sig *ECDSASignature, pubkey *ecdsa.PublicKey) bool {
	// hash message
	h := ecdsaHash.New()
	h.Write(data)
	digest := h.Sum(nil)

	return ecdsa.Verify(pubkey, digest, sig.R, sig.S)
}
示例#20
0
func (p *policy) VerifySignature(hashedInput []byte, sig string) (bool, error) {
	if !p.Type.SigningSupported() {
		return false, errutil.UserError{Err: fmt.Sprintf("message verification not supported for key type %v", p.Type)}
	}

	// Verify the prefix
	if !strings.HasPrefix(sig, "vault:v") {
		return false, errutil.UserError{Err: "invalid signature: no prefix"}
	}

	splitVerSig := strings.SplitN(strings.TrimPrefix(sig, "vault:v"), ":", 2)
	if len(splitVerSig) != 2 {
		return false, errutil.UserError{Err: "invalid signature: wrong number of fields"}
	}

	ver, err := strconv.Atoi(splitVerSig[0])
	if err != nil {
		return false, errutil.UserError{Err: "invalid signature: version number could not be decoded"}
	}

	if ver > p.LatestVersion {
		return false, errutil.UserError{Err: "invalid signature: version is too new"}
	}

	if p.MinDecryptionVersion > 0 && ver < p.MinDecryptionVersion {
		return false, errutil.UserError{Err: ErrTooOld}
	}

	switch p.Type {
	case keyType_ECDSA_P256:
		asn1Sig, err := base64.StdEncoding.DecodeString(splitVerSig[1])
		if err != nil {
			return false, errutil.UserError{Err: "invalid base64 signature value"}
		}

		var ecdsaSig ecdsaSignature
		rest, err := asn1.Unmarshal(asn1Sig, &ecdsaSig)
		if err != nil {
			return false, errutil.UserError{Err: "supplied signature is invalid"}
		}
		if rest != nil && len(rest) != 0 {
			return false, errutil.UserError{Err: "supplied signature contains extra data"}
		}

		keyParams := p.Keys[ver]
		key := &ecdsa.PublicKey{
			Curve: elliptic.P256(),
			X:     keyParams.EC_X,
			Y:     keyParams.EC_Y,
		}

		return ecdsa.Verify(key, hashedInput, ecdsaSig.R, ecdsaSig.S), nil
	default:
		return false, errutil.InternalError{Err: fmt.Sprintf("unsupported key type %v", p.Type)}
	}

	return false, errutil.InternalError{Err: "no valid key type found"}
}
示例#21
0
func (txn *BlockAttribution) Verify(publicKey *ecdsa.PublicKey) bool {
	buf := bytes.NewBuffer([]byte{})
	binary.Write(buf, binary.LittleEndian, sha1.Sum([]byte("ATTRIBUTE")))
	r := new(big.Int)
	s := new(big.Int)
	r.SetBytes(txn.SignatureR)
	s.SetBytes(txn.SignatureS)
	return ecdsa.Verify(publicKey, buf.Bytes(), r, s)
}
示例#22
0
文件: nat.go 项目: Jaspper/gitchain
func (txn *NameAllocation) Verify(publicKey *ecdsa.PublicKey) bool {
	buf := bytes.NewBuffer([]byte{})
	binary.Write(buf, binary.LittleEndian, sha1.Sum(append([]byte("ALLOCATE"), txn.Name...)))
	r := new(big.Int)
	s := new(big.Int)
	r.SetBytes(txn.SignatureR)
	s.SetBytes(txn.SignatureS)
	return ecdsa.Verify(publicKey, buf.Bytes(), r, s)
}
示例#23
0
// Verify does the actual check.
func (v ECDSAVerifier) Verify(key data.PublicKey, sig []byte, msg []byte) error {
	algorithm := key.Algorithm()
	var pubKey crypto.PublicKey

	switch algorithm {
	case data.ECDSAx509Key:
		pemCert, _ := pem.Decode([]byte(key.Public()))
		if pemCert == nil {
			logrus.Debugf("failed to decode PEM-encoded x509 certificate for keyID: %s", key.ID())
			logrus.Debugf("certificate bytes: %s", string(key.Public()))
			return ErrInvalid
		}
		cert, err := x509.ParseCertificate(pemCert.Bytes)
		if err != nil {
			logrus.Debugf("failed to parse x509 certificate: %s\n", err)
			return ErrInvalid
		}
		pubKey = cert.PublicKey
	case data.ECDSAKey:
		var err error
		pubKey, err = x509.ParsePKIXPublicKey(key.Public())
		if err != nil {
			logrus.Debugf("Failed to parse private key for keyID: %s, %s\n", key.ID(), err)
			return ErrInvalid
		}
	default:
		// only accept ECDSA keys.
		logrus.Debugf("invalid key type for ECDSA verifier: %s", algorithm)
		return ErrInvalidKeyType{}
	}

	ecdsaPubKey, ok := pubKey.(*ecdsa.PublicKey)
	if !ok {
		logrus.Debugf("value isn't an ECDSA public key")
		return ErrInvalid
	}

	sigLength := len(sig)
	expectedOctetLength := 2 * ((ecdsaPubKey.Params().BitSize + 7) >> 3)
	if sigLength != expectedOctetLength {
		logrus.Debugf("signature had an unexpected length")
		return ErrInvalid
	}

	rBytes, sBytes := sig[:sigLength/2], sig[sigLength/2:]
	r := new(big.Int).SetBytes(rBytes)
	s := new(big.Int).SetBytes(sBytes)

	digest := sha256.Sum256(msg)

	if !ecdsa.Verify(ecdsaPubKey, digest[:], r, s) {
		logrus.Debugf("failed ECDSA signature validation")
		return ErrInvalid
	}

	return nil
}
示例#24
0
文件: crypto.go 项目: postfix/arx
func verify(pub *ecdsa.PublicKey, data, sig []byte) bool {
	var unpackedSig ECDSASignature
	_, err := asn1.Unmarshal(sig, &unpackedSig)
	if err != nil {
		return false
	}
	h := sha512.Sum384(data)
	return ecdsa.Verify(pub, h[:], unpackedSig.R, unpackedSig.S)
}
示例#25
0
文件: signatures.go 项目: Jonbeek/Sia
// takes as input a public key and a signed message
// returns whether the signature is valid or not
func (pk *PublicKey) Verify(signedMessage *SignedMessage) (verified bool) {
	if pk == nil || signedMessage == nil {
		return false
	}

	ecdsaKey := (*ecdsa.PublicKey)(pk)
	verified = ecdsa.Verify(ecdsaKey, []byte(signedMessage.Message), signedMessage.Signature.R, signedMessage.Signature.S)
	return
}
示例#26
0
// ReadCertificateSet reads a transaction certificate set from the TCA.  Not yet implemented.
func (tcap *TCAP) ReadCertificateSet(ctx context.Context, in *pb.TCertReadSetReq) (*pb.CertSet, error) {
	Trace.Println("grpc TCAP:ReadCertificateSet")

	req := in.Req.Id
	id := in.Id.Id

	if req != id && tcap.tca.eca.readRole(req)&int(pb.Role_AUDITOR) == 0 {
		return nil, errors.New("access denied")
	}

	raw, err := tcap.tca.eca.readCertificate(req, x509.KeyUsageDigitalSignature)
	if err != nil {
		return nil, err
	}
	cert, err := x509.ParseCertificate(raw)
	if err != nil {
		return nil, err
	}

	sig := in.Sig
	in.Sig = nil

	r, s := big.NewInt(0), big.NewInt(0)
	r.UnmarshalText(sig.R)
	s.UnmarshalText(sig.S)

	hash := primitives.NewHash()
	raw, _ = proto.Marshal(in)
	hash.Write(raw)
	if ecdsa.Verify(cert.PublicKey.(*ecdsa.PublicKey), hash.Sum(nil), r, s) == false {
		return nil, errors.New("signature does not verify")
	}

	rows, err := tcap.tca.readCertificates(id, in.Ts.Seconds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var certs []*pb.TCert
	var kdfKey []byte
	for rows.Next() {
		var raw []byte
		if err = rows.Scan(&raw, &kdfKey); err != nil {
			return nil, err
		}

		// TODO: TCert must include attribute keys, we need to save them in the db when generating the batch of TCerts
		certs = append(certs, &pb.TCert{raw, make(map[string][]byte)})
	}
	if err = rows.Err(); err != nil {
		return nil, err
	}

	return &pb.CertSet{in.Ts, in.Id, kdfKey, certs}, nil
}
示例#27
0
func BenchmarkRawVerifyP224(b *testing.B) {
	data := "foo"
	k, _ := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
	R, S, _ := ecdsa.Sign(rand.Reader, k, []byte(data))
	pk := &k.PublicKey
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		ecdsa.Verify(pk, []byte(data), R, S)
	}
}
示例#28
0
func Verify(m string, sig CertcoinSignature, pk CertcoinPublicKey) bool {
	public := ecdsa.PublicKey{
		Curve: CURVE,
		X:     pk.X,
		Y:     pk.Y,
	}

	h := CertcoinHashStr(m)
	return ecdsa.Verify(&public, h[:], sig.R, sig.S)
}
示例#29
0
文件: tack.go 项目: tack/tackgo
func (t *Tack) Verify() bool {
	curve := elliptic.P256()
	x, y := elliptic.Unmarshal(curve, append([]byte{4}, t.PublicKey...))
	pubKey := ecdsa.PublicKey{curve, x, y}

	var r, s big.Int
	r.SetBytes(t.Signature[:SIG_LENGTH/2])
	s.SetBytes(t.Signature[SIG_LENGTH/2:])
	return ecdsa.Verify(&pubKey, t.hashForSig(), &r, &s)
}
示例#30
-1
文件: main.go 项目: hyg/go.sample
func main() {
	c := elliptic.P521()
	sec, _ := ecdsa.GenerateKey(c, rand.Reader)
	pub := &sec.PublicKey
	log.Print("pub", pub)
	log.Print("sec", sec)

	pempub := exportPublicKeytoPEM(pub)
	pemsec := exportPrivateKeytoEncryptedPEM(sec, []byte("asdfgh"))
	log.Print("pempub", pempub)
	log.Print("pemsec", pemsec)

	pub = importPublicKeyfromPEM(pempub)
	//sec = importPrivateKeyfromPEM(pemsec)
	sec = importPrivateKeyfromEncryptedPEM(pemsec, []byte("asdfgh"))
	log.Print("pub", pub)
	log.Print("sec", sec)

	t := sha1.New()
	io.WriteString(t, "data") // when msg is a string
	//t.Write([]byte("data")) // when msg is []bye
	sum1 := t.Sum(nil)[:]

	r, s, _ := ecdsa.Sign(rand.Reader, sec, sum1)
	log.Printf("r=%d\ts=%d", r, s)

	b := ecdsa.Verify(pub, sum1, r, s)
	log.Printf("b=%v", b)

	b = ecdsa.Verify(pub, sum1, s, r)
	log.Printf("b=%v", b)

}