• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang ecdsa.Sign函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中crypto/ecdsa.Sign函数的典型用法代码示例。如果您正苦于以下问题:Golang Sign函数的具体用法?Golang Sign怎么用?Golang Sign使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Sign函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: ecdsaSign

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
}
开发者ID:useidel,项目名称:notary,代码行数:29,代码来源:verifiers_test.go


示例17: sign

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
}
开发者ID:eadmund,项目名称:spki,代码行数:7,代码来源:private_key.go


示例18: Sign

// 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
}
开发者ID:burkemw3,项目名称:syncthing,代码行数:35,代码来源:signature.go


示例19: sign

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
}
开发者ID:closeyourhead,项目名称:learn-golang,代码行数:30,代码来源:sample.go


示例20: Update

//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
}
开发者ID:AaronGoldman,项目名称:ccfs,代码行数:26,代码来源:tag.go



注:本文中的crypto/ecdsa.Sign函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang ecdsa.Verify函数代码示例发布时间:2022-05-24
下一篇:
Golang ecdsa.GenerateKey函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap