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

Golang x509.ParsePKIXPublicKey函数代码示例

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

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



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

示例1: fetchPubkey

func fetchPubkey() (*rsa.PublicKey, error) {
	resp, err := http.Get("https://s3o.ft.com/publickey")
	if err != nil || resp.StatusCode != http.StatusOK {
		return nil, errors.New("failed to read s3o public key")
	}
	defer func() {
		_, _ = io.Copy(ioutil.Discard, resp.Body)
		_ = resp.Body.Close()
	}()
	var buf bytes.Buffer
	if _, err := io.Copy(&buf, resp.Body); err != nil {
		return nil, errors.New("failed to read s3o public key")
	}
	dec := make([]byte, 8192) // should be enough for a while.
	i, err := base64.StdEncoding.Decode(dec, buf.Bytes())
	if err != nil {
		return nil, errors.New("failed to base64 decode s3o public key")
	}

	pub, err := x509.ParsePKIXPublicKey(dec[0:i])
	if err != nil {
		return nil, errors.New("failed to parse s3o public key")
	}
	return pub.(*rsa.PublicKey), nil
}
开发者ID:railsagainstignorance,项目名称:alignment,代码行数:25,代码来源:s3o.go


示例2: init

func init() {
	var err error
	var pemBytes []byte
	var pub crypto.PublicKey
	var p *pem.Block

	if client, err = NewClient(certFile, keyFile, caFile, ioutil.Discard); err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(rsaPubKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if pub, err = x509.ParsePKIXPublicKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	if rsaKey, err = client.RegisterPublicKey(server, pub); err != nil {
		log.Fatal(err)
	}

	if pemBytes, err = ioutil.ReadFile(ecdsaPubKey); err != nil {
		log.Fatal(err)
	}
	p, _ = pem.Decode(pemBytes)
	if pub, err = x509.ParsePKIXPublicKey(p.Bytes); err != nil {
		log.Fatal(err)
	}
	if ecdsaKey, err = client.RegisterPublicKey(server, pub); err != nil {
		log.Fatal(err)
	}
}
开发者ID:AnonSuite,项目名称:gokeyless,代码行数:32,代码来源:client_test.go


示例3: importKeyFromString

func importKeyFromString(str string) (prv *rsa.PrivateKey, pub *rsa.PublicKey, err error) {
	cert := []byte(str)
	for {
		var blk *pem.Block
		blk, cert = pem.Decode(cert)
		if blk == nil {
			break
		}
		switch blk.Type {
		case "RSA PRIVATE KEY":
			prv, err = x509.ParsePKCS1PrivateKey(blk.Bytes)
			return
		case "RSA PUBLIC KEY":
			var in interface{}
			in, err = x509.ParsePKIXPublicKey(blk.Bytes)
			if err != nil {
				return
			}
			pub = in.(*rsa.PublicKey)
			return
		}
		if cert == nil || len(cert) == 0 {
			break
		}
	}
	return
}
开发者ID:nicnys-8,项目名称:mdc,代码行数:27,代码来源:crypto.go


示例4: NewLog

// NewLog returns an initialized Log struct
func NewLog(uri, b64PK string) (*Log, error) {
	url, err := url.Parse(uri)
	if err != nil {
		return nil, err
	}
	url.Path = strings.TrimSuffix(url.Path, "/")
	client := ctClient.New(url.String(), nil)

	pkBytes, err := base64.StdEncoding.DecodeString(b64PK)
	if err != nil {
		return nil, fmt.Errorf("Failed to decode base64 log public key")
	}
	pk, err := x509.ParsePKIXPublicKey(pkBytes)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse log public key")
	}

	verifier, err := ct.NewSignatureVerifier(pk)
	if err != nil {
		return nil, err
	}

	// Replace slashes with dots for statsd logging
	sanitizedPath := strings.TrimPrefix(url.Path, "/")
	sanitizedPath = strings.Replace(sanitizedPath, "/", ".", -1)

	return &Log{
		logID:    b64PK,
		uri:      uri,
		statName: fmt.Sprintf("%s.%s", url.Host, sanitizedPath),
		client:   client,
		verifier: verifier,
	}, nil
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:35,代码来源:publisher.go


示例5: ParseRSAPublicKeyFromPEM

// ParseRSAPublicKeyFromPEM parses PEM encoded PKCS1 or PKCS8 public key.
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
	var err error

	// Parse PEM block
	var block *pem.Block
	if block, _ = pem.Decode(key); block == nil {
		return nil, ErrKeyMustBePEMEncoded
	}

	// Parse the key
	var parsedKey interface{}
	if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
		if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
			parsedKey = cert.PublicKey
		} else {
			return nil, err
		}
	}

	var pkey *rsa.PublicKey
	var ok bool
	if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
		return nil, ErrNotRSAPublicKey
	}

	return pkey, nil
}
开发者ID:fujitsu-cf,项目名称:cli,代码行数:28,代码来源:rsa_utils.go


示例6: 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


示例7: getPublicKey

func getPublicKey() *rsa.PublicKey {
	publicKeyFile, err := os.Open(settings.Get().PublicKeyPath)
	if err != nil {
		panic(err)
	}

	pemfileinfo, _ := publicKeyFile.Stat()
	var size int64 = pemfileinfo.Size()
	pembytes := make([]byte, size)

	buffer := bufio.NewReader(publicKeyFile)
	_, err = buffer.Read(pembytes)

	data, _ := pem.Decode([]byte(pembytes))

	publicKeyFile.Close()

	publicKeyImported, err := x509.ParsePKIXPublicKey(data.Bytes)

	if err != nil {
		panic(err)
	}

	rsaPub, ok := publicKeyImported.(*rsa.PublicKey)

	if !ok {
		panic(err)
	}

	return rsaPub
}
开发者ID:ricardolonga,项目名称:golang-jwt-authentication-api-sample,代码行数:31,代码来源:jwt_backend.go


示例8: ImportPEM

// ImportPEM imports an RSA key from a file. It works with both public and
// private keys.
func ImportPEM(filename string) (prv *rsa.PrivateKey, pub *rsa.PublicKey, err error) {
	cert, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}

	for {
		var blk *pem.Block
		blk, cert = pem.Decode(cert)
		if blk == nil {
			break
		}
		switch blk.Type {
		case "RSA PRIVATE KEY":
			prv, err = x509.ParsePKCS1PrivateKey(blk.Bytes)
			return
		case "RSA PUBLIC KEY":
			var in interface{}
			in, err = x509.ParsePKIXPublicKey(blk.Bytes)
			if err != nil {
				return
			}
			pub = in.(*rsa.PublicKey)
			return
		}
		if cert == nil || len(cert) == 0 {
			break
		}
	}
	return
}
开发者ID:jonathanmarvens,项目名称:gocrypto,代码行数:33,代码来源:crypto.go


示例9: ParsePublicKey

func ParsePublicKey(path string) *rsa.PublicKey {
	in, err := ioutil.ReadFile(path)
	if err != nil {
		log.Fatalf("%v", err)
	}

	if p, _ := pem.Decode(in); p != nil {
		if p.Type != "PUBLIC KEY" && p.Type != "RSA PUBLIC KEY" {
			log.Fatalf("invalid public key (type is %s)",
				p.Type)
		}
		in = p.Bytes
	}
	pub, err := x509.ParsePKIXPublicKey(in)
	if err != nil {
		log.Fatalf("failed to parse certificate: %v", err)
	}

	switch pub := pub.(type) {
	case *rsa.PublicKey:
		return pub
	default:
		log.Fatalf("only RSA public keys are supported")
		return nil
	}
}
开发者ID:postfix,项目名称:entropyshare,代码行数:26,代码来源:util.go


示例10: getRSAPubKey

func getRSAPubKey(key data.PublicKey) (crypto.PublicKey, error) {
	algorithm := key.Algorithm()
	var pubKey crypto.PublicKey

	switch algorithm {
	case data.RSAx509Key:
		pemCert, _ := pem.Decode([]byte(key.Public()))
		if pemCert == nil {
			logrus.Debugf("failed to decode PEM-encoded x509 certificate")
			return nil, ErrInvalid
		}
		cert, err := x509.ParseCertificate(pemCert.Bytes)
		if err != nil {
			logrus.Debugf("failed to parse x509 certificate: %s\n", err)
			return nil, ErrInvalid
		}
		pubKey = cert.PublicKey
	case data.RSAKey:
		var err error
		pubKey, err = x509.ParsePKIXPublicKey(key.Public())
		if err != nil {
			logrus.Debugf("failed to parse public key: %s\n", err)
			return nil, ErrInvalid
		}
	default:
		// only accept RSA keys
		logrus.Debugf("invalid key type for RSAPSS verifier: %s", algorithm)
		return nil, ErrInvalidKeyType{}
	}

	return pubKey, nil
}
开发者ID:jfrazelle,项目名称:notary,代码行数:32,代码来源:verifiers.go


示例11: ValidatePublicKey

// ValidatePublicKey checks that the provided public key is valid.
func ValidatePublicKey(publicKey interface{}) (bool, error) {
	switch publicKey := publicKey.(type) {
	case string:
		// at the moment we don't care about the pub interface

		decPubKey, z := pem.Decode([]byte(publicKey))
		if decPubKey == nil {
			err := fmt.Errorf("Public key does not validate: %s", z)
			return false, err
		}
		// Add the header to PKCS#1 public keys
		if strings.HasPrefix(publicKey, "-----BEGIN RSA PUBLIC KEY-----") && len(decPubKey.Bytes) == 270 {
			pkcs8head := []byte{0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00}
			pkcs8head = append(pkcs8head, decPubKey.Bytes...)
			decPubKey.Bytes = pkcs8head
		}
		if _, err := x509.ParsePKIXPublicKey(decPubKey.Bytes); err != nil {
			nerr := fmt.Errorf("Public key did not validate: %s", err.Error())
			return false, nerr
		}
		return true, nil
	default:
		err := fmt.Errorf("Public key does not validate")
		return false, err
	}
}
开发者ID:theckman,项目名称:goiardi,代码行数:27,代码来源:chefcrypto.go


示例12: HeaderDecrypt

// HeaderDecrypt decrypts the encrypted header with the client or user's public
// key for validating requests. This function is informed by chef-golang's
// privateDecrypt function.
func HeaderDecrypt(pkPem string, data string) ([]byte, error) {
	block, _ := pem.Decode([]byte(pkPem))
	if block == nil {
		return nil, fmt.Errorf("Invalid block size for '%s'", pkPem)
	}
	pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	decData, perr := base64.StdEncoding.DecodeString(data)
	if perr != nil {
		return nil, perr
	}
	dec, derr := decrypt(pubKey.(*rsa.PublicKey), decData)
	if derr != nil {
		return nil, derr
	}
	/* skip past the 0xff padding added to the header before encrypting. */
	skip := 0
	for i := 2; i < len(dec); i++ {
		if dec[i] == 0xff && dec[i+1] == 0 {
			skip = i + 2
			break
		}
	}
	return dec[skip:], nil
}
开发者ID:theckman,项目名称:goiardi,代码行数:30,代码来源:chefcrypto.go


示例13: getPublicKey

func getPublicKey() *rsa.PublicKey {
	//settings.Get().PublicKeyPath
	///Users/amosunsunday/Documents/Official/xtremepay/Sources/services/src/xtremepay.com/backoffice/security/settings/keys/public_key.pub
	publicKeyFile, err := os.Open("/Users/amosunsunday/Documents/Official/xtremepay/Sources/services/src/xtremepay.com/backoffice/security/settings/keys/public_key.pub")
	if err != nil {
		panic(err)
	}

	pemfileinfo, _ := publicKeyFile.Stat()
	var size int64 = pemfileinfo.Size()
	pembytes := make([]byte, size)

	buffer := bufio.NewReader(publicKeyFile)
	_, err = buffer.Read(pembytes)

	data, _ := pem.Decode([]byte(pembytes))

	publicKeyFile.Close()

	publicKeyImported, err := x509.ParsePKIXPublicKey(data.Bytes)

	if err != nil {
		panic(err)
	}

	rsaPub, ok := publicKeyImported.(*rsa.PublicKey)

	if !ok {
		panic(err)
	}

	return rsaPub
}
开发者ID:amosunfemi,项目名称:xtremepay,代码行数:33,代码来源:jwt_backend.go


示例14: VerifySign

func (m *MobilePayNotify) VerifySign() (bool, error) {

	// 待签名数据
	data := m.signStr()
	// Parse public key into rsa.PublicKey
	PEMBlock, _ := pem.Decode([]byte(pubKeyPEM))
	if PEMBlock == nil {
		return false, errors.New("Could not parse Public Key PEM")
	}
	if PEMBlock.Type != "PUBLIC KEY" {
		return false, errors.New("Found wrong key type")
	}
	pubkey, err := x509.ParsePKIXPublicKey(PEMBlock.Bytes)
	if err != nil {
		return false, err
	}

	// compute the sha1
	h := sha1.New()
	h.Write([]byte(data))

	signature, err := base64.StdEncoding.DecodeString(m.Sign)
	if err != nil {
		return false, err
	}

	// Verify
	err = rsa.VerifyPKCS1v15(pubkey.(*rsa.PublicKey), crypto.SHA1, h.Sum(nil), signature)
	if err != nil {
		return false, err
	}

	return true, nil
}
开发者ID:Zerak,项目名称:alipaymobilenotify,代码行数:34,代码来源:notify.go


示例15: RSAPubKeyFromWire

// Deserialize an RSA public key from wire format
func RSAPubKeyFromWire(data []byte) (pub *rsa.PublicKey, err error) {
	pk, err := x509.ParsePKIXPublicKey(data)
	if err == nil {
		pub = pk.(*rsa.PublicKey)
	}
	return
}
开发者ID:jddixon,项目名称:xlCrypto_go,代码行数:8,代码来源:rsa_serialization.go


示例16: UnmarshalJSON

// UnmarshalJSON parses a simple JSON format for log descriptions.  Both the
// URI and the public key are expected to be strings.  The public key is a
// base64-encoded PKIX public key structure.
func (logDesc *LogDescription) UnmarshalJSON(data []byte) error {
	var rawLogDesc rawLogDescription
	if err := json.Unmarshal(data, &rawLogDesc); err != nil {
		return fmt.Errorf("Failed to unmarshal log description, %s", err)
	}
	logDesc.URI = rawLogDesc.URI
	// Load Key
	pkBytes, err := base64.StdEncoding.DecodeString(rawLogDesc.PublicKey)
	if err != nil {
		return fmt.Errorf("Failed to decode base64 log public key")
	}
	pk, err := x509.ParsePKIXPublicKey(pkBytes)
	if err != nil {
		return fmt.Errorf("Failed to parse log public key")
	}
	ecdsaKey, ok := pk.(*ecdsa.PublicKey)
	if !ok {
		return fmt.Errorf("Failed to unmarshal log description for %s, unsupported public key type", logDesc.URI)
	}
	logDesc.PublicKey = ecdsaKey

	// Generate key hash for log ID
	pkHash := sha256.Sum256(pkBytes)
	logDesc.ID = base64.StdEncoding.EncodeToString(pkHash[:])
	if len(logDesc.ID) != 44 {
		return fmt.Errorf("Invalid log ID length [%d]", len(logDesc.ID))
	}

	return nil
}
开发者ID:hotelzululima,项目名称:boulder,代码行数:33,代码来源:publisher.go


示例17: 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


示例18: loadPublicKey

func loadPublicKey(path string) (*rsa.PublicKey, error) {
	// Read the private key
	pemData, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("read key file: %s", err))
	}

	// Extract the PEM-encoded data block
	block, _ := pem.Decode(pemData)
	if block == nil {
		return nil, errors.New(fmt.Sprintf("bad key data: %s", "not PEM-encoded"))
	}
	if got, want := block.Type, "PUBLIC KEY"; got != want {
		return nil, errors.New(fmt.Sprintf("unknown key type %q, want %q", got, want))
	}

	// Decode the RSA private key
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("bad public key: %s", err))
	}

	key, ok := pub.(*rsa.PublicKey)
	if !ok {
		return nil, errors.New(fmt.Sprintf("public key does not implement *rsa.PublicKey: %s", reflect.TypeOf(pub)))
	}

	return key, nil
}
开发者ID:rajatchopra,项目名称:geard,代码行数:29,代码来源:handler.go


示例19: RSAEncrypt

// Used for tests. Everytime its load key from file.
func RSAEncrypt(data []byte) ([]byte, error) {
	pathToKey, cfgErr := cfg.GetStr(cfg.STR_KEYS_PATH)
	if cfgErr != nil {
		return nil, cfgErr
	}

	pemData, err := ioutil.ReadFile(pathToKey + "public_key.pem")
	if err != nil {
		return nil, err
	}
	// Extract the PEM-encoded data block
	block, _ := pem.Decode(pemData)
	if block == nil {
		return nil, errors.New("Empty block.")
	}

	// Decode the RSA public key
	key, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pkey := key.(*rsa.PublicKey)
	// Encrypt the data
	out, err := rsa.EncryptPKCS1v15(rand.Reader, pkey, data)
	if err != nil {
		return nil, err
	}

	return out, nil
}
开发者ID:walkline,项目名称:GoMastersLunch,代码行数:31,代码来源:SimpleRSA.go


示例20: LoadPEMPubKey

// LoadPEMPubKey attempts to load a public key from PEM.
func LoadPEMPubKey(in []byte) (crypto.PublicKey, error) {
	p, rest := pem.Decode(in)
	if p == nil || len(rest) != 0 {
		return nil, errors.New("couldn't decode public key")
	}
	return x509.ParsePKIXPublicKey(p.Bytes)
}
开发者ID:Bren2010,项目名称:gokeyless,代码行数:8,代码来源:gokeyless-tester.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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