Golang crypto-rsa.VerifyPKCS1v15类(方法)实例源码

下面列出了Golang crypto-rsa.VerifyPKCS1v15 类(方法)源码代码实例,从而了解它的用法。

作者:nangong92    项目:go_sr   
// 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)
}

作者:CodeJua    项目:kubernete   
// 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)
}

作者:matomes    项目:rk   
// 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
}

作者:keysonZZ    项目:km   
//这个接口应该和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
}

作者:bakani    项目:jw   
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
}

作者:benji    项目:jw   
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
}

作者:go-nosq    项目:golan   
// 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")
}

作者:leepr    项目:gopla   
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!")
}

作者:hg3rdroc    项目:percona-agen   
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)
}

作者:ConradIrwi    项目:mrs   
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)
	}
}

作者:coderhaoxi    项目:rk   
// 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
}

作者:rrudduc    项目:golang-stuf   
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)
}

作者:root-g    项目:wig   
// 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
}

作者:jemoonki    项目:golangboo   
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("검증 성공")
	}
}

作者:marsc    项目:camlistor   
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
}

作者:tslilya    项目:SLYke   
// 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
}

作者:mozkeele    项目:certificatetransparenc   
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
}

作者:jameswe    项目:zmopenapi-sdk-golan   
//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
}

作者:0prototyp    项目:go-ia   
// 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
}

作者:octoke    项目:octokey-g   
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)
	}
}


问题


面经


文章

微信
公众号

扫码关注公众号