當前位置: 首頁>>代碼示例>>Golang>>正文


Golang ecdsa.Sign函數代碼示例

本文整理匯總了Golang中crypto/ecdsa.Sign函數的典型用法代碼示例。如果您正苦於以下問題:Golang Sign函數的具體用法?Golang Sign怎麽用?Golang Sign使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Sign函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Sign

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}
}
開發者ID:jaked122,項目名稱:bytecoin,代碼行數:7,代碼來源:crypto.go

示例2: VerifyKeyPair

// 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
}
開發者ID:ripplecripple,項目名稱:gocoin,代碼行數:34,代碼來源:wallet.go

示例3: Sign

// 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
}
開發者ID:vgorin,項目名稱:cryptogo,代碼行數:38,代碼來源:ecdsa.go

示例4: TestProcessRequestUserKey

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)
}
開發者ID:netkicorp,項目名稱:go-partner-api-client,代碼行數:26,代碼來源:netki_test.go

示例5: TestSign

// 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)

}
開發者ID:capnfuzz,項目名稱:qrtickets,代碼行數:34,代碼來源:web_handlers.go

示例6: main

/*
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, "")
}
開發者ID:netkicorp,項目名稱:go-partner-api-client,代碼行數:33,代碼來源:exampleKsk.go

示例7: Sign

// 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
	}
}
開發者ID:Guoshusheng,項目名稱:drone-exec,代碼行數:36,代碼來源:ecdsa.go

示例8: StartKEX

// 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
}
開發者ID:jmptrader,項目名稱:gocrypto,代碼行數:39,代碼來源:eckex.go

示例9: Sign

// 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
}
開發者ID:ericcapricorn,項目名稱:deis,代碼行數:36,代碼來源:ec_key.go

示例10: TestReadUserSetNonAuditor

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")
	}

}
開發者ID:srderson,項目名稱:fabric,代碼行數:29,代碼來源:eca_test.go

示例11: Sign

// 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
}
開發者ID:kisom,項目名稱:aescrypt,代碼行數:28,代碼來源:box.go

示例12: NewTag

//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
}
開發者ID:AaronGoldman,項目名稱:ccfs,代碼行數:33,代碼來源:tag.go

示例13: CreateSignature

// 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)
	}
}
開發者ID:jfrazelle,項目名稱:cfssl,代碼行數:27,代碼來源:signature.go

示例14: Sign

// 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)
}
開發者ID:tmroeder,項目名稱:cloudproxy,代碼行數:33,代碼來源:keys.go

示例15: CreateCookie

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
}
開發者ID:heipei,項目名稱:nginx-sso,代碼行數:25,代碼來源:ssocookie.go


注:本文中的crypto/ecdsa.Sign函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。