示例#1
0
func Sign(str string, priv *ecdsa.PrivateKey) Signature {
	r, s, err := ecdsa.Sign(cryptorand.Reader, priv, []byte(str))
	if err != nil {
		log.Fatal(err)
	}
	return Signature{r, s}
}
示例#2
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
}
示例#3
0
文件: ecdsa.go 项目: vgorin/cryptogo
// Sign calculates a signature for a byte array hash using hex-encoded private key
// It is supposed that a hash is calculated for an original message to sign
// Signature is a hex-encoded JSON
func Sign(hash []byte, private_key_hex string) (signature_hex string, err error) {
	// decode private key from hex
	private_key_bytes, err := hex.DecodeString(private_key_hex)
	if err != nil {
		return "", err
	}

	// x509 parse private key
	private_key, err := x509.ParseECPrivateKey(private_key_bytes)
	if err != nil {
		return "", err
	}

	// sign
	r, s, err := ecdsa.Sign(rand.Reader, private_key, hash)
	if err != nil {
		return "", err
	}

	// prepare a signature structure to marshal into json
	signature := &signature{
		R: r,
		S: s,
	}

	// marshal to json
	signature_json, err := json.Marshal(signature)
	if err != nil {
		return "", err
	}

	// encode to hex
	signature_hex = hex.EncodeToString(signature_json)
	return signature_hex, nil
}
func TestProcessRequestUserKey(t *testing.T) {
	server, client := setupHttp(200, "application/json", `{"success":true,"message":"my message"}`)
	defer server.Close()

	// Create Test Keys
	userKey := new(ecdsa.PrivateKey)
	userKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

	partnerKey := new(ecdsa.PrivateKey)
	partnerKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

	// Sign User's Public Key (SHA1 Hash)  with Partner's Key
	userPubkey, _ := x509.MarshalPKIXPublicKey(&userKey.PublicKey)
	hash := sha1.New().Sum(userPubkey)
	r, s, _ := ecdsa.Sign(rand.Reader, partnerKey, hash)
	sigToMarshal := &ecdsaSignature{R: r, S: s}
	keySig, _ := asn1.Marshal(sigToMarshal)

	userKeyPartner := &NetkiPartner{UserKey: userKey, KeySigningKey: &partnerKey.PublicKey, KeySignature: keySig}

	requester := &NetkiRequester{HTTPClient: client}
	result, err := requester.ProcessRequest(userKeyPartner, "http://domain.com/uri", "GET", "")

	assert.Equal(t, nil, err)
	assert.NotEqual(t, nil, result)
}
示例#5
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)

}
/*
KSK Control Working Example Using Hardcoded EC Keys
*/
func main() {
	// Instantiate Partner Signing Key
	partnerKeyRaw, _ := hex.DecodeString("3077020101042095abcdbf646efc799c9b08866c185dd53cbe6ac4ceeed4ed33e2d27641c23a77a00a06082a8648ce3d030107a14403420004b220745b4195fbe16b55d578d347295c6ca9ab9b42720f794ff70d2dab732bc55049f8de66c37248fed05faaca7b12ac0924d3fb6f8a67e5166a8430f1c860b4")
	partnerKey, _ := parseECPrivateKey(nil, partnerKeyRaw)

	// Instantiate User Key and Sign DER Encoded Public Key with Partner Signing Key
	userKeyRaw, _ := hex.DecodeString("307702010104208977d5312f492e7b04cbd8cf11334ed6ccb3ab1c530252a37dc6a1fad46f8b7ba00a06082a8648ce3d030107a1440342000472866325007154426e80e40039a6414a27db6c09b536f3bb79712020f505e1ff91daff344a73eae5b96535c6864277eeb389f1d1f632d0174b77b67b4627d6b2")
	userKey, _ := parseECPrivateKey(nil, userKeyRaw)

	// Hash (SHA256) User's Public Key (DER-format) for KeySigning + Sign
	userDER, _ := x509.MarshalPKIXPublicKey(&userKey.PublicKey)
	hasher := sha256.New()
	hasher.Write(userDER)
	userDERHash := hasher.Sum(nil)
	r, s, _ := ecdsa.Sign(rand.Reader, partnerKey, userDERHash)
	sig, _ := asn1.Marshal(EcdsaSig{r, s})

	// Initialize a partner for use with key signed control
	partner := netki.NewNetkiRemotePartner("http://localhost:5000", userKey, &partnerKey.PublicKey, sig)

	d := &Domain{DomainName: "mydomain.com"}
	wallet := &Wallet{Currency: "btc", WalletAddress: "1hsdflkjghsfdlkjghfsdlkgjh"}
	submitWallets := make([]Wallet, 0)
	submitWallets = append(wallets, *wallet)

	walletName := partner.CreateNewWalletName(*d, "supertest1", submitWallets, "ext_id")
	walletName.Save(partner)

	wallets, _ := partner.GetWalletNames(*d, "")
}
示例#7
0
// Implements the Sign method from SigningMethod
// For this signing method, key must be an ecdsa.PrivateKey struct
func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) {
	// Get the key
	var ecdsaKey *ecdsa.PrivateKey
	switch k := key.(type) {
	case *ecdsa.PrivateKey:
		ecdsaKey = k
	default:
		return "", ErrInvalidKey
	}

	// Create the hasher
	if !m.Hash.Available() {
		return "", ErrHashUnavailable
	}

	hasher := m.Hash.New()
	hasher.Write([]byte(signingString))

	// Sign the string and return r, s
	if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil {
		// asn1 marhsal r, s using ecPoint as the structure
		var ecpoint = new(ECPoint)
		ecpoint.R = r
		ecpoint.S = s

		if signature, err := asn1.Marshal(*ecpoint); err != nil {
			return "", err
		} else {
			return EncodeSegment(signature), nil
		}
	} else {
		return "", err
	}
}
示例#8
0
// StartKEX prepares a new key exchange. It returns an initialised
// session handle and a signed public key that should be sent to the
// peer. peer and FinishKEX called to finalise the session. It returns a
// new session handle and a signed public key that should be sent to the
// peer.  The returned session handle has ephemeral private key data in
// it, but the shared key is not yet set up. After this call, the session
// cannot encrypt or decrypt.
func StartKEX(signer *ecdsa.PrivateKey) (*Session, []byte, error) {
	priv, err := ecdsa.GenerateKey(signer.Curve, rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	skey := signedKey{}
	skey.Public, err = x509.MarshalPKIXPublicKey(&priv.PublicKey)
	if err != nil {
		return nil, nil, err
	}

	hashedPub := sha256.Sum256(skey.Public)

	skey.R, skey.S, err = ecdsa.Sign(rand.Reader, signer, hashedPub[:])
	if err != nil {
		return nil, nil, err
	}

	kex := &Session{}
	kex.priv, err = x509.MarshalECPrivateKey(priv)
	if err != nil {
		return nil, nil, err
	}

	out, err := asn1.Marshal(skey)
	if err != nil {
		return nil, nil, err
	}

	return kex, out, nil
}
示例#9
0
// Sign signs the data read from the io.Reader using a signature algorithm supported
// by the elliptic curve private key. If the specified hashing algorithm is
// supported by this key, that hash function is used to generate the signature
// otherwise the the default hashing algorithm for this key is used. Returns
// the signature and the name of the JWK signature algorithm used, e.g.,
// "ES256", "ES384", "ES512".
func (k *ecPrivateKey) Sign(data io.Reader, hashID crypto.Hash) (signature []byte, alg string, err error) {
	// Generate a signature of the data using the internal alg.
	// The given hashId is only a suggestion, and since EC keys only support
	// on signature/hash algorithm given the curve name, we disregard it for
	// the elliptic curve JWK signature implementation.
	hasher := k.signatureAlgorithm.HashID().New()
	_, err = io.Copy(hasher, data)
	if err != nil {
		return nil, "", fmt.Errorf("error reading data to sign: %s", err)
	}
	hash := hasher.Sum(nil)

	r, s, err := ecdsa.Sign(rand.Reader, k.PrivateKey, hash)
	if err != nil {
		return nil, "", fmt.Errorf("error producing signature: %s", err)
	}
	rBytes, sBytes := r.Bytes(), s.Bytes()
	octetLength := (k.ecPublicKey.Params().BitSize + 7) >> 3
	// MUST include leading zeros in the output
	rBuf := make([]byte, octetLength-len(rBytes), octetLength)
	sBuf := make([]byte, octetLength-len(sBytes), octetLength)

	rBuf = append(rBuf, rBytes...)
	sBuf = append(sBuf, sBytes...)

	signature = append(rBuf, sBuf...)
	alg = k.signatureAlgorithm.HeaderParam()

	return
}
示例#10
0
func TestReadUserSetNonAuditor(t *testing.T) {

	ecaa := &ECAA{eca}

	req := &pb.ReadUserSetReq{
		Req:  &pb.Identity{Id: testUser.enrollID},
		Role: 1,
		Sig:  nil}

	//sign the req
	hash := primitives.NewHash()
	raw, _ := proto.Marshal(req)
	hash.Write(raw)

	r, s, err := ecdsa.Sign(rand.Reader, testUser.enrollPrivKey, hash.Sum(nil))
	if err != nil {
		t.Fatalf("Failed (ECDSA) signing [%s]", err.Error())
	}
	R, _ := r.MarshalText()
	S, _ := s.MarshalText()
	req.Sig = &pb.Signature{Type: pb.CryptoType_ECDSA, R: R, S: S}

	_, err = ecaa.ReadUserSet(context.Background(), req)

	if err == nil {
		t.Fatal("Only auditors should be able to call ReadUserSet")
	}

}
示例#11
0
// Sign computes the hash of data and signs it with the private key, returning
// a signature in PEM format.
func Sign(privKeyPEM []byte, data io.Reader) ([]byte, error) {
	// Parse the private key
	key, err := loadPrivateKey(privKeyPEM)
	if err != nil {
		return nil, err
	}

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

	// Sign the hash
	r, s, err := ecdsa.Sign(rand.Reader, key, hash)
	if err != nil {
		return nil, err
	}

	// Marshal the signature using ASN.1
	sig, err := marshalSignature(r, s)
	if err != nil {
		return nil, err
	}

	// Encode it in a PEM block
	bs := pem.EncodeToMemory(&pem.Block{
		Type:  "SIGNATURE",
		Bytes: sig,
	})

	return bs, nil
}
示例#12
0
// Sign computes an ECDSA sigature over the contextualized data, using the
// private key of the signer.
func (s *Signer) Sign(data []byte, context string) ([]byte, error) {
	ch, err := s.CreateHeader()
	if err != nil {
		return nil, err
	}

	// TODO(tmroeder): for compatibility with the C++ version, we should
	// compute ECDSA signatures over hashes truncated to fit in the ECDSA
	// signature.
	b, err := contextualizedSHA256(ch, data, context, sha256.Size)
	if err != nil {
		return nil, err
	}

	R, S, err := ecdsa.Sign(rand.Reader, s.ec, b)
	if err != nil {
		return nil, err
	}

	m, err := asn1.Marshal(ecdsaSignature{R, S})
	if err != nil {
		return nil, err
	}

	sd := &SignedData{
		Header:    ch,
		Signature: m,
	}

	return proto.Marshal(sd)
}
示例#13
0
func CreateCookie(ip string, payload *CookiePayload, privkey *ecdsa.PrivateKey, expiry time.Duration) string {

	expiration := time.Now().Add(expiry)
	expire := int32(expiration.Unix())

	sso_cookie := new(Cookie)
	sso_cookie.E = expire
	sso_cookie.P = *payload
	slice := CreateHash(ip, sso_cookie)

	log.Debugf("Hash over IP, Expires and Payload: %x", slice)

	er, es, _ := ecdsa.Sign(rand.Reader, privkey, slice)
	log.Debugf("Signature over hash: %#v, %#v", er, es)

	sso_cookie.R = *er
	sso_cookie.S = *es

	json_string, _ := json.Marshal(sso_cookie)
	url_string := url.QueryEscape(string(json_string))
	log.Debugf("%d bytes: %s", len(json_string), json_string)
	log.Debugf("%d bytes: %s", len(url_string), url_string)

	return url_string
}
示例#14
0
func ecdsaSign(privKey data.PrivateKey, hashed []byte) ([]byte, error) {
	if _, ok := privKey.(*data.ECDSAPrivateKey); !ok {
		return nil, fmt.Errorf("private key type not supported: %s", privKey.Algorithm())
	}

	// Create an ecdsa.PrivateKey out of the private key bytes
	ecdsaPrivKey, err := x509.ParseECPrivateKey(privKey.Private())
	if err != nil {
		return nil, err
	}

	// Use the ECDSA key to sign the data
	r, s, err := ecdsa.Sign(rand.Reader, ecdsaPrivKey, hashed[:])
	if err != nil {
		return nil, err
	}

	rBytes, sBytes := r.Bytes(), s.Bytes()
	octetLength := (ecdsaPrivKey.Params().BitSize + 7) >> 3

	// MUST include leading zeros in the output
	rBuf := make([]byte, octetLength-len(rBytes), octetLength)
	sBuf := make([]byte, octetLength-len(sBytes), octetLength)

	rBuf = append(rBuf, rBytes...)
	sBuf = append(sBuf, sBytes...)

	return append(rBuf, sBuf...), nil
}
示例#15
0
func (k *PrivateKey) sign(h Hash) (sig *Signature, err error) {
	r, s, err := ecdsa.Sign(rand.Reader, &k.PrivateKey, h.Hash)
	if err != nil {
		return nil, err
	}
	return &Signature{Hash: h, Principal: k.PublicKey(), R: r, S: s}, nil
}
示例#16
0
文件: box.go 项目: kisom/aescrypt
// Sign is used to certify a message with the key pair passed in. It returns a
// boolean indicating success; on success, the signature value returned will
// contain the signature.
func Sign(message []byte, key PrivateKey, pub PublicKey) (signature []byte, ok bool) {
	if message == nil {
		return nil, false
	} else if !KeyIsSuitable(key, pub) {
		return nil, false
	}
	h := sha256.New()
	h.Write(message)
	hash := h.Sum(nil)

	skey, ok := ecdsa_private(key, pub)
	if !ok {
		return
	}
	r, s, err := ecdsa.Sign(PRNG, skey, hash)
	if err != nil {
		ok = false
	} else {
		signature = marshalSignature(r, s)
		if signature == nil {
			ok = false
		}
	}
	return
}
示例#17
0
文件: tag.go 项目: AaronGoldman/ccfs
//Update the named content
func (t Tag) Update(hashBytes HID, typeString string) Tag {
	t.Parents = Parents{t.Hash()}
	t.HashBytes = hashBytes
	t.TypeString = typeString
	//t.nameSegment = t.nameSegment
	t.Version = newVersion()
	//t.hkid = t.hkid
	prikey, err := geterPoster.getPrivateKeyForHkid(t.Hkid)
	if err != nil {
		log.Panic("You don't seem to own this Domain")
	}

	ObjectHash := t.genTagHash(
		t.HashBytes,
		t.TypeString,
		t.NameSegment,
		t.Version,
		t.Parents,
		t.Hkid,
	)
	ecdsaprikey := ecdsa.PrivateKey(*prikey)
	r, s, _ := ecdsa.Sign(rand.Reader, &ecdsaprikey, ObjectHash)
	t.Signature = elliptic.Marshal(elliptic.P521(), r, s)
	return t
}
示例#18
0
func sign(prv_key_filename string, msg []byte) []byte {
	// load ecdsa private key from file
	prv_data, err := ioutil.ReadFile(prv_key_filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	ecprv, err := cyhcrypto.LoadECPrivateKey(prv_data)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// sign to message
	msg_hasher := sha256.New()
	_, _ = msg_hasher.Write(msg)
	hashed := msg_hasher.Sum(nil)
	r, s, err := ecdsa.Sign(rand.Reader, ecprv, hashed)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	signature, err := cyhcrypto.EncodeSignature(r, s)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	return signature
}
示例#19
0
// Sign wraps ecdsa.Sign to sign the provided hash (which should be the result
// of hashing a larger message) using the private key.
func (p *PrivateKey) Sign(hash []byte) (*Signature, error) {
	r, s, err := ecdsa.Sign(rand.Reader, p.ToECDSA(), hash)
	if err != nil {
		return nil, err
	}
	return &Signature{R: r, S: s}, nil
}
示例#20
0
// CreateSignature builds a signature over the given data using the specified hash algorithm and private key.
func CreateSignature(privKey crypto.PrivateKey, hashAlgo HashAlgorithm, data []byte) (DigitallySigned, error) {
	var sig DigitallySigned
	sig.Algorithm.Hash = hashAlgo
	hash, hashType, err := generateHash(sig.Algorithm.Hash, data)
	if err != nil {
		return sig, err
	}

	switch privKey := privKey.(type) {
	case rsa.PrivateKey:
		sig.Algorithm.Signature = RSA
		sig.Signature, err = rsa.SignPKCS1v15(rand.Reader, &privKey, hashType, hash)
		return sig, err
	case ecdsa.PrivateKey:
		sig.Algorithm.Signature = ECDSA
		var ecdsaSig dsaSig
		ecdsaSig.R, ecdsaSig.S, err = ecdsa.Sign(rand.Reader, &privKey, hash)
		if err != nil {
			return sig, err
		}
		sig.Signature, err = asn1.Marshal(ecdsaSig)
		return sig, err
	default:
		return sig, fmt.Errorf("unsupported private key type %T", privKey)
	}
}
示例#21
0
文件: tag.go 项目: AaronGoldman/ccfs
//NewTag build a new tag with the initial content
func NewTag(
	HashBytes HID,
	TypeString string,
	nameSegment string,
	tparent Parents,
	hkid HKID,
) Tag {
	prikey, _ := geterPoster.getPrivateKeyForHkid(hkid)
	version := newVersion()
	if tparent == nil {
		tparent = Parents{Blob{}.Hash()}
	}
	ObjectHash := Tag{}.genTagHash(
		HashBytes,
		TypeString,
		nameSegment,
		version,
		tparent,
		hkid,
	)
	ecdsaprikey := ecdsa.PrivateKey(*prikey)
	r, s, _ := ecdsa.Sign(rand.Reader, &ecdsaprikey, ObjectHash)
	signature := elliptic.Marshal(elliptic.P521(), r, s)
	t := Tag{HashBytes,
		TypeString,
		nameSegment,
		version,
		tparent,
		hkid,
		signature}
	return t
}
示例#22
0
func MySign(hashed []byte, priv *ecdsa.PrivateKey) (*Signature, error) {
	r, s, err := ecdsa.Sign(rand.Reader, priv, hashed)

	if err != nil {
		return nil, err
	}
	return &Signature{R: r.Bytes(), S: s.Bytes()}, nil
}
示例#23
0
func BenchmarkRawCreateP224(b *testing.B) {
	data := "foo"
	k, _ := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		ecdsa.Sign(rand.Reader, k, []byte(data))
	}
}
示例#24
0
func (ka *signedKeyAgreement) signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error) {
	var tls12HashId uint8
	var err error
	if ka.version >= VersionTLS12 {
		if tls12HashId, err = pickTLS12HashForSignature(ka.sigType, clientHello.signatureAndHashes, config.signatureAndHashesForServer()); err != nil {
			return nil, err
		}
		ka.sh.hash = tls12HashId
	}
	ka.sh.signature = ka.sigType
	digest, hashFunc, err := hashForServerKeyExchange(ka.sigType, tls12HashId, ka.version, clientHello.random, hello.random, params)
	if err != nil {
		return nil, err
	}

	var sig []byte
	switch ka.sigType {
	case signatureECDSA:
		privKey, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
		if !ok {
			return nil, errors.New("ECDHE ECDSA requires an ECDSA server private key")
		}
		r, s, err := ecdsa.Sign(config.rand(), privKey, digest)
		if err != nil {
			return nil, errors.New("failed to sign ECDHE parameters: " + err.Error())
		}
		sig, err = asn1.Marshal(ecdsaSignature{r, s})
	case signatureRSA:
		privKey, ok := cert.PrivateKey.(*rsa.PrivateKey)
		if !ok {
			return nil, errors.New("ECDHE RSA requires a RSA server private key")
		}
		sig, err = rsa.SignPKCS1v15(config.rand(), privKey, hashFunc, digest)
		if err != nil {
			return nil, errors.New("failed to sign ECDHE parameters: " + err.Error())
		}
	default:
		return nil, errors.New("unknown ECDHE signature algorithm")
	}

	skx := new(serverKeyExchangeMsg)
	sigAndHashLen := 0
	if ka.version >= VersionTLS12 {
		sigAndHashLen = 2
	}
	skx.key = make([]byte, len(params)+sigAndHashLen+2+len(sig))
	copy(skx.key, params)
	k := skx.key[len(params):]
	if ka.version >= VersionTLS12 {
		k[0] = tls12HashId
		k[1] = ka.sigType
		k = k[2:]
	}
	k[0] = byte(len(sig) >> 8)
	k[1] = byte(len(sig))
	copy(k[2:], sig)
	return skx, nil
}
示例#25
0
func (node *nodeImpl) getTLSCertificateFromTLSCA(id, affiliation string) (interface{}, []byte, error) {
	node.log.Info("getTLSCertificate...")

	priv, err := utils.NewECDSAKey()

	if err != nil {
		node.log.Error("Failed generating key: %s", err)

		return nil, nil, err
	}

	uuid, err := util.GenerateUUID()
	if err != nil {
		node.log.Error("Failed generating uuid: %s", err)

		return nil, nil, err
	}

	// Prepare the request
	pubraw, _ := x509.MarshalPKIXPublicKey(&priv.PublicKey)
	now := time.Now()
	timestamp := google_protobuf.Timestamp{int64(now.Second()), int32(now.Nanosecond())}

	req := &obcca.TLSCertCreateReq{
		&timestamp,
		&obcca.Identity{Id: id + "-" + uuid},
		&obcca.Password{Pw: ""},
		&obcca.PublicKey{
			Type: obcca.CryptoType_ECDSA,
			Key:  pubraw,
		}, nil}
	rawreq, _ := proto.Marshal(req)
	r, s, err := ecdsa.Sign(rand.Reader, priv, utils.Hash(rawreq))
	if err != nil {
		panic(err)
	}
	R, _ := r.MarshalText()
	S, _ := s.MarshalText()
	req.Sig = &obcca.Signature{obcca.CryptoType_ECDSA, R, S}

	pbCert, err := node.callTLSCACreateCertificate(context.Background(), req)
	if err != nil {
		node.log.Error("Failed requesting tls certificate: %s", err)

		return nil, nil, err
	}

	node.log.Info("Verifing tls certificate...")

	tlsCert, err := utils.DERToX509Certificate(pbCert.Cert)
	certPK := tlsCert.PublicKey.(*ecdsa.PublicKey)
	utils.VerifySignCapability(priv, certPK)

	node.log.Info("Verifing tls certificate...done!")

	return priv, pbCert.Cert, nil
}
示例#26
0
// ECDSASignDirect signs
func ECDSASignDirect(signKey interface{}, msg []byte) (*big.Int, *big.Int, error) {
	temp := signKey.(*ecdsa.PrivateKey)
	r, s, err := ecdsa.Sign(rand.Reader, temp, Hash(msg))
	if err != nil {
		return nil, nil, err
	}

	return r, s, nil
}
示例#27
0
func SignTorrents(k *ecdsa.PrivateKey, ts []*Torrent) (*Signature, error) {
	m := buildMerkle(ts)
	R, S, err := ecdsa.Sign(rand.Reader, k, []byte(m.hash))
	if err != nil {
		return nil, err
	}
	ek := crypto.EncodeKey(&k.PublicKey)
	return &Signature{ek, R, S, m}, nil
}
示例#28
0
func BenchmarkEcdsaSign(b *testing.B) {
	key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	val := sha256.Sum256(make([]byte, 32, 32))

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		ecdsa.Sign(rand.Reader, key, val[:])
	}
}
示例#29
0
func NewBlockAttribution(privateKey *ecdsa.PrivateKey) (txn *BlockAttribution, err error) {
	buf := bytes.NewBuffer([]byte{})
	binary.Write(buf, binary.LittleEndian, sha1.Sum([]byte("ATTRIBUTE")))
	sigR, sigS, err := ecdsa.Sign(rand.Reader, privateKey, buf.Bytes())
	return &BlockAttribution{
			Version:    NAME_ALLOCATION_VERSION,
			SignatureR: sigR.Bytes(),
			SignatureS: sigS.Bytes()},
		err
}
示例#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)

}