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

Golang rsa.VerifyPKCS1v15函数代码示例

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

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



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

示例1: Verify

// Implements the Verify method from SigningMethod
// For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA public key as
// []byte, or an rsa.PublicKey structure.
func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
	var err error

	// Decode the signature
	var sig []byte
	fmt.Println("right: ")
	if sig, err = DecodeSegment(signature); err != nil {
		return err
	}

	var rsaKey *rsa.PublicKey

	switch k := key.(type) {
	case []byte:
		if rsaKey, err = ParseRSAPublicKeyFromPEM(k); err != nil {
			return err
		}
	case *rsa.PublicKey:
		rsaKey = k
	default:
		return ErrInvalidKey
	}

	// Create hasher
	if !m.Hash.Available() {
		return ErrHashUnavailable
	}
	hasher := m.Hash.New()
	hasher.Write([]byte(signingString))

	// Verify the signature
	err = rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
	fmt.Printf("%#v\n, %#v\n, %#v\n, %#v\n, %#v\n", rsaKey, m.Hash, hasher.Sum(nil), sig, err)
	return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
}
开发者ID:nangong92t,项目名称:go_src,代码行数:38,代码来源:rsa.go


示例2: Verify

// Implements the Verify method from SigningMethod
// For this signing method, must be an rsa.PublicKey structure.
func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
	var err error

	// Decode the signature
	var sig []byte
	if sig, err = DecodeSegment(signature); err != nil {
		return err
	}

	var rsaKey *rsa.PublicKey
	var ok bool

	if rsaKey, ok = key.(*rsa.PublicKey); !ok {
		return ErrInvalidKeyType
	}

	// Create hasher
	if !m.Hash.Available() {
		return ErrHashUnavailable
	}
	hasher := m.Hash.New()
	hasher.Write([]byte(signingString))

	// Verify the signature
	return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
}
开发者ID:CodeJuan,项目名称:kubernetes,代码行数:28,代码来源:rsa.go


示例3: QuoteVerify

// QuoteVerify verifies that a quote was genuinely provided by the TPM. It
// takes the quote data, quote validation blob, public half of the AIK,
// current PCR values and the nonce used in the original quote request. It
// then verifies that the validation block is a valid signature for the
// quote data, that the secrets are the same (in order to avoid replay
// attacks), and that the PCR values are the same. It returns an error if
// any stage of the validation fails.
func QuoteVerify(data []byte, validation []byte, aikpub []byte, pcrvalues [][]byte, secret []byte) error {
	n := big.NewInt(0)
	n.SetBytes(aikpub)
	e := 65537

	pKey := rsa.PublicKey{N: n, E: int(e)}

	dataHash := sha1.Sum(data[:])

	err := rsa.VerifyPKCS1v15(&pKey, crypto.SHA1, dataHash[:], validation)
	if err != nil {
		return err
	}

	pcrHash := data[8:28]
	nonceHash := data[28:48]

	secretHash := sha1.Sum(secret[:])

	if bytes.Equal(secretHash[:], nonceHash) == false {
		return fmt.Errorf("Secret doesn't match")
	}

	pcrComposite := []byte{0x00, 0x02, 0xff, 0xff, 0x00, 0x00, 0x01, 0x40}
	for i := 0; i < 16; i++ {
		pcrComposite = append(pcrComposite, pcrvalues[i]...)
	}
	pcrCompositeHash := sha1.Sum(pcrComposite[:])

	if bytes.Equal(pcrCompositeHash[:], pcrHash) == false {
		return fmt.Errorf("PCR values don't match")
	}

	return nil
}
开发者ID:matomesc,项目名称:rkt,代码行数:42,代码来源:attestation.go


示例4: RsaOpensslVerify

//这个接口应该和php版的openssl_verify在使用rsa公钥的时候有完全相同的输入输出,加密的坑简直太多了..
//msg是需要验证签名的消息,sig是签名之后生成的
func RsaOpensslVerify(pub *rsa.PublicKey, h crypto.Hash, msg []byte, sig []byte) (err error) {
	h1 := h.New()
	h1.Write(msg)
	digest := h1.Sum(nil)
	err = rsa.VerifyPKCS1v15(pub, h, digest, sig)
	return
}
开发者ID:keysonZZZ,项目名称:kmg,代码行数:9,代码来源:rsa.go


示例5: Verify

func (m *SigningMethodRS256) Verify(signingString, signature string, key []byte) (err error) {
	// Key
	var sig []byte
	if sig, err = DecodeSegment(signature); err == nil {
		var block *pem.Block
		if block, _ = pem.Decode(key); block != nil {
			var parsedKey interface{}
			if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
				parsedKey, err = x509.ParseCertificate(block.Bytes)
			}
			if err == nil {
				if rsaKey, ok := parsedKey.(*rsa.PublicKey); ok {
					hasher := sha256.New()
					hasher.Write([]byte(signingString))

					err = rsa.VerifyPKCS1v15(rsaKey, crypto.SHA256, hasher.Sum(nil), sig)
				} else if cert, ok := parsedKey.(*x509.Certificate); ok {
					err = cert.CheckSignature(x509.SHA256WithRSA, []byte(signingString), sig)
				} else {
					err = errors.New("Key is not a valid RSA public key")
				}
			}
		} else {
			err = errors.New("Could not parse key data")
		}
	}
	return
}
开发者ID:bakanis,项目名称:jwt,代码行数:28,代码来源:rs256.go


示例6: validate

func (v RSValidator) validate(jwt *jwt) (bool, error) {

	if v.PublicKey == nil {
		return false, ErrBadSignature
	}

	jwt.Header.Algorithm = v.algorithm
	jwt.rawEncode()

	signature, err := base64.URLEncoding.DecodeString(string(jwt.Signature))

	if err != nil {
		return false, err
	}

	hsh := v.hashType.New()
	hsh.Write([]byte(string(jwt.headerRaw) + "." + string(jwt.payloadRaw)))
	hash := hsh.Sum(nil)

	err = rsa.VerifyPKCS1v15(v.PublicKey, v.hashType, hash, signature)

	if err != nil {
		return false, ErrBadSignature
	}

	return true, nil
}
开发者ID:benjic,项目名称:jwt,代码行数:27,代码来源:rs.go


示例7: VerifySignature

// 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 os.Error) {
	if !pk.CanSign() {
		return error.InvalidArgumentError("public key cannot generate signatures")
	}

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

	if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
		return error.SignatureError("hash tag doesn't match")
	}

	if pk.PubKeyAlgo != sig.PubKeyAlgo {
		return error.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)
		if err != nil {
			return error.SignatureError("RSA verification failure")
		}
		return nil
	case PubKeyAlgoDSA:
		dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
		if !dsa.Verify(dsaPublicKey, hashBytes, sig.DSASigR, sig.DSASigS) {
			return error.SignatureError("DSA verification failure")
		}
		return nil
	default:
		panic("shouldn't happen")
	}
	panic("unreachable")
}
开发者ID:go-nosql,项目名称:golang,代码行数:37,代码来源:public_key.go


示例8: main

func main() {
	privateKey, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		fmt.Printf("rsa.GenerateKey: %v\n", err)
		return
	}

	message := "Hello World!"
	messageBytes := bytes.NewBufferString(message)
	hash := sha512.New()
	hash.Write(messageBytes.Bytes())
	digest := hash.Sum(nil)

	fmt.Printf("messageBytes: %v\n", messageBytes)
	fmt.Printf("hash: %V\n", hash)
	fmt.Printf("digest: %v\n", digest)

	signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA512, digest)
	if err != nil {
		fmt.Printf("rsa.SignPKCS1v15 error: %v\n", err)
		return
	}

	fmt.Printf("signature: %v\n", signature)

	err = rsa.VerifyPKCS1v15(&privateKey.PublicKey, crypto.SHA512, digest, signature)
	if err != nil {
		fmt.Printf("rsa.VerifyPKCS1v15 error: %V\n", err)
	}

	fmt.Println("Signature good!")
}
开发者ID:leepro,项目名称:goplay,代码行数:32,代码来源:rsasign.go


示例9: checkSignature

func (u *Updater) checkSignature(data, sig []byte) error {
	u.logger.Debug("checkSignature:call")
	defer u.logger.Debug("checkSignature:return")
	hash := sha256.New()
	hash.Write(data)
	return rsa.VerifyPKCS1v15(u.rsaPubKey, crypto.SHA256, hash.Sum(nil), sig)
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:7,代码来源:update.go


示例10: TestSessionSign

func TestSessionSign(t *testing.T) {

	k, err := rsa.GenerateKey(rand.Reader, 512)

	if err != nil {
		t.Fatal(err)
	}

	buffer := sha1.Sum([]byte("Monkey!"))
	hashed := buffer[0:20]

	t.Log(hashed)

	k1, k2, err := SplitPrivateKey(k)

	if err != nil {
		t.Fatal(err)
	}

	session := Session{k1.PublicKey, []PartialDecryptor{k1, k2}}

	signature, err := session.SignPKCS1v15(crypto.SHA1, hashed)

	if err != nil {
		t.Fatal(err)
	}

	err = rsa.VerifyPKCS1v15(&k.PublicKey, crypto.SHA1, hashed, signature)

	if err != nil {
		t.Fatal(err)
	}
}
开发者ID:ConradIrwin,项目名称:mrsa,代码行数:33,代码来源:session_test.go


示例11: KeyVerify

// KeyVerify verifies that a key certification request was genuinely
// provided by the TPM. It takes the certification data, certification
// validation blob, the public half of the AIK, the public half of the key
// to be certified and the nonce used in the original quote request. It then
// verifies that the validation block is a valid signature for the
// certification data, that the certification data matches the certified key
// and that the secrets are the same (in order to avoid replay attacks). It
// returns an error if any stage of the validation fails.
func KeyVerify(data []byte, validation []byte, aikpub []byte, keypub []byte, secret []byte) error {
	n := big.NewInt(0)
	n.SetBytes(aikpub)
	e := 65537

	pKey := rsa.PublicKey{N: n, E: int(e)}

	dataHash := sha1.Sum(data[:])

	err := rsa.VerifyPKCS1v15(&pKey, crypto.SHA1, dataHash[:], validation)
	if err != nil {
		return err
	}

	keyHash := data[43:63]
	nonceHash := data[63:83]

	secretHash := sha1.Sum(secret[:])

	if bytes.Equal(secretHash[:], nonceHash) == false {
		return fmt.Errorf("Secret doesn't match")
	}

	certHash := sha1.Sum(keypub[:])

	if bytes.Equal(certHash[:], keyHash) == false {
		return fmt.Errorf("Key doesn't match")
	}

	return nil
}
开发者ID:coderhaoxin,项目名称:rkt,代码行数:39,代码来源:verification.go


示例12: Decrypt

func Decrypt() {
    key := Key()
    h, ha := HashAlgorithm()
    encrypted, err := ioutil.ReadFile(EncryptedFile)
    if err != nil {
        log.Fatalf("failed reading encrypted data: %s", err)
    }

    signature, err := ioutil.ReadFile(SignatureFile)
    if err != nil {
        log.Fatalf("failed saving signature data: %s", err)
    }

    if err = rsa.VerifyPKCS1v15(&key.PublicKey, ha, HashMessage(encrypted), signature); err != nil {
        log.Fatalf("message not valid: %s", err)
    } else {
        log.Printf("message is valid!")
    }

    plaintext, err := rsa.DecryptOAEP(h, rand.Reader, key, encrypted, nil)
    if err != nil {
        log.Fatalf("failed decrypting: %s", err)
    }
    log.Printf("decrypted message: %s", plaintext)
}
开发者ID:rrudduck,项目名称:golang-stuff,代码行数:25,代码来源:rsa.go


示例13: VerifyUuidSignature

// Verify the validity of an uuid signature
func (this *Authority) VerifyUuidSignature(uuid string, uuidSignature []byte) (err error) {
	hash := crypto.SHA256.New()
	hash.Write([]byte(uuid))
	digest := hash.Sum(nil)
	err = rsa.VerifyPKCS1v15(&this.privateKey.PublicKey, crypto.SHA256, digest, uuidSignature)
	return
}
开发者ID:root-gg,项目名称:wigo,代码行数:8,代码来源:authority.go


示例14: main

func main() {
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048) // 개인 키와 공개 키 생성
	if err != nil {
		fmt.Println(err)
		return
	}
	publicKey := &privateKey.PublicKey // 개인 키 변수 안에 공개 키가 들어있음

	message := "안녕하세요. Go 언어"
	hash := md5.New()           // 해시 인스턴스 생성
	hash.Write([]byte(message)) // 해시 인스턴스에 문자열 추가
	digest := hash.Sum(nil)     // 문자열의 MD5 해시 값 추출

	var h1 crypto.Hash
	signature, err := rsa.SignPKCS1v15( // 개인 키로 서명
		rand.Reader,
		privateKey, // 개인 키
		h1,
		digest, // MD5 해시 값
	)

	var h2 crypto.Hash
	err = rsa.VerifyPKCS1v15( // 공개 키로 서명 검증
		publicKey, // 공개 키
		h2,
		digest,    // MD5 해시 값
		signature, // 서명 값
	)

	if err != nil {
		fmt.Println("검증 실패")
	} else {
		fmt.Println("검증 성공")
	}
}
开发者ID:jemoonkim,项目名称:golangbook,代码行数:35,代码来源:rsa_sign.go


示例15: VerifySignature

func (vr *VerifyRequest) VerifySignature() bool {
	armorData := reArmor(vr.CamliSig)
	block, _ := armor.Decode([]byte(armorData))
	if block == nil {
		return vr.fail("Can't parse camliSig armor")
	}
	buf := bytes.NewBuffer(block.Bytes)
	p, err := packet.ReadPacket(buf)
	if err != nil {
		return vr.fail("Error reading PGP packet from camliSig")
	}
	sig, ok := p.(packet.SignaturePacket)
	if !ok {
		return vr.fail("PGP packet isn't a signature packet")
	}
	if sig.Hash != packet.HashFuncSHA1 {
		return vr.fail("I can only verify SHA1 signatures")
	}
	if sig.SigType != packet.SigTypeBinary {
		return vr.fail("I can only verify binary signatures")
	}
	hash := sha1.New()
	hash.Write(vr.bp) // payload bytes
	hash.Write(sig.HashSuffix)
	hashBytes := hash.Sum()
	if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
		return vr.fail("hash tag doesn't match")
	}
	err = rsa.VerifyPKCS1v15(&vr.PublicKeyPacket.PublicKey, rsa.HashSHA1, hashBytes, sig.Signature)
	if err != nil {
		return vr.fail(fmt.Sprintf("bad signature: %s", err))
	}
	return true
}
开发者ID:marsch,项目名称:camlistore,代码行数:34,代码来源:verify.go


示例16: UpdatePublicKey

// Returns error on failure, nil on success
// Updates a public key, signed by the user
// signature should be signed on JSON-marshalled transaction data
func UpdatePublicKey(key rsa.PublicKey, sig []byte, email string) error {
	// value already in map, don't reregister
	oldKey, ok := Database[email]
	if !ok {
		return fmt.Errorf("You have never registered for a public key")
	}
	jsonBytes, err := json.Marshal(&Transaction{Type: Update, Email: email, PublicKey: key})
	if err != nil {
		return err
	}

	// protocol: user uses SHA256 to hash the transaction
	hash := sha256.Sum256(jsonBytes)
	hashbytes := hash[:]
	if err := rsa.VerifyPKCS1v15(&oldKey, crypto.SHA256, hashbytes, sig); err != nil {
		return fmt.Errorf("bad signature")
	}
	trans := Transaction{
		Type:      Update,
		Email:     email,
		PublicKey: key,
		Signature: sig,
	}
	// add this to our "block" that we're working on
	addToBlock(trans)
	return nil
}
开发者ID:tslilyai,项目名称:SLYkey,代码行数:30,代码来源:transaction.go


示例17: verifyRSASignature

func verifyRSASignature(key *rsa.PublicKey, hash crypto.Hash, signatureBytes []byte, digest []byte) error {
	err := rsa.VerifyPKCS1v15(key, hash, digest, signatureBytes)
	if err != nil {
		return errors.New("certificatetransparency: signature verification failed: " + err.Error())
	}
	return nil
}
开发者ID:mozkeeler,项目名称:certificatetransparency,代码行数:7,代码来源:ct.go


示例18: VerifySignature

//VerifySignature verify whether the given signature is correct
func VerifySignature(raw []byte, signature string, algorithm crypto.Hash) bool {
	if raw == nil || signature == "" {
		return false
	}
	publicKey := []byte(PublicKey)
	if !ginutil.IsProduction() {
		publicKey = []byte(TestPublicKey)
	}
	block, _ := pem.Decode(publicKey)
	if block == nil {
		return false
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return false
	}
	pub := pubInterface.(*rsa.PublicKey)
	var data []byte
	if algorithm == crypto.SHA1 {
		data = EncryptSHA(raw)
	} else {
		data = EncryptMD5(EncryptSHA(raw))
	}
	err = rsa.VerifyPKCS1v15(pub, algorithm, data, DecryptBase64(signature))
	if err != nil {
		return false
	}
	return true
}
开发者ID:jameswei,项目名称:zmopenapi-sdk-golang,代码行数:30,代码来源:crypto_util.go


示例19: VerifySignature

// VerifySignature verifies in app billing signature.
// You need to prepare a public key for your Android app's in app billing
// at https://play.google.com/apps/publish/
func VerifySignature(base64EncodedPublicKey string, receipt []byte, signature string) (isValid bool, err error) {
	// prepare public key
	decodedPublicKey, err := base64.StdEncoding.DecodeString(base64EncodedPublicKey)
	if err != nil {
		return false, fmt.Errorf("failed to decode public key")
	}
	publicKeyInterface, err := x509.ParsePKIXPublicKey(decodedPublicKey)
	if err != nil {
		return false, fmt.Errorf("failed to parse public key")
	}
	publicKey, _ := publicKeyInterface.(*rsa.PublicKey)

	// generate hash value from receipt
	hasher := sha1.New()
	hasher.Write(receipt)
	hashedReceipt := hasher.Sum(nil)

	// decode signature
	decodedSignature, err := base64.StdEncoding.DecodeString(signature)
	if err != nil {
		return false, fmt.Errorf("failed to decode signature")
	}

	// verify
	if err := rsa.VerifyPKCS1v15(publicKey, crypto.SHA1, hashedReceipt, decodedSignature); err != nil {
		return false, nil
	}

	return true, nil
}
开发者ID:0prototype,项目名称:go-iap,代码行数:33,代码来源:validator.go


示例20: TestEscrowServer

func TestEscrowServer(t *testing.T) {

	k1, k2, err := octokey.GeneratePartialKey()

	if err != nil {
		t.Fatal(err)
	}

	_, err = uploadFile("http://localhost:5005/upload", "key", []byte(k2.String()))
	if err != nil {
		t.Fatal(err)
	}

	p2 := &octokey.PartialSigner{"http://localhost:5005/sign", (*octokey.PublicKey)(&k2.PublicKey)}

	s := new(mrsa.Session)
	s.Decryptors = append(s.Decryptors, p2)
	s.Decryptors = append(s.Decryptors, k1)
	s.PublicKey = k1.PublicKey

	buffer := sha1.Sum([]byte("Monkey!"))
	hashed := buffer[0:20]
	signature, err := s.SignPKCS1v15(crypto.SHA1, hashed)
	if err != nil {
		t.Fatal(err)
	}

	err = rsa.VerifyPKCS1v15((*rsa.PublicKey)(&k1.PublicKey), crypto.SHA1, hashed, signature)
	if err != nil {
		t.Fatal(err)
	}
}
开发者ID:octokey,项目名称:octokey-go,代码行数:32,代码来源:escrow_test.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang rsa.VerifyPSS函数代码示例发布时间:2022-05-24
下一篇:
Golang rsa.Validate函数代码示例发布时间: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