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


Golang rsa.PrivateKey類代碼示例

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


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

示例1: Generate

//Generate is use to create a pair of keys (Private and Public) you can specify if you want to save them in a file,
// the path is defined by PrivateKeyPath and PublicKeyPath global variable
func Generate(identifier string, save bool) (*rsa.PrivateKey, *rsa.PublicKey, error) {
	var publickey *rsa.PublicKey
	var privatekey *rsa.PrivateKey

	privatekey, err := rsa.GenerateKey(rand.Reader, 1024)

	if err != nil {
		return nil, nil, err
	}

	privatekey.Precompute()
	err = privatekey.Validate()

	if err != nil {
		return nil, nil, err
	}

	publickey = &privatekey.PublicKey

	if save == true {
		savePrivateKey(privatekey, PrivateKeyPath)
		savePublicKey(publickey, identifier, PublicKeyPath)
	}
	return privatekey, publickey, nil
}
開發者ID:MrGosti,項目名稱:rosa,代碼行數:27,代碼來源:rosa.go

示例2: insertIdentity

func (s *server) insertIdentity(req []byte) error {
	var record struct {
		Type string `sshtype:"17"`
		Rest []byte `ssh:"rest"`
	}
	if err := ssh.Unmarshal(req, &record); err != nil {
		return err
	}

	switch record.Type {
	case ssh.KeyAlgoRSA:
		var k rsaKeyMsg
		if err := ssh.Unmarshal(req, &k); err != nil {
			return err
		}

		priv := rsa.PrivateKey{
			PublicKey: rsa.PublicKey{
				E: int(k.E.Int64()),
				N: k.N,
			},
			D:      k.D,
			Primes: []*big.Int{k.P, k.Q},
		}
		priv.Precompute()

		return s.agent.Add(AddedKey{PrivateKey: &priv, Comment: k.Comments})
	}
	return fmt.Errorf("not implemented: %s", record.Type)
}
開發者ID:kkirsche,項目名稱:go-nessus,代碼行數:30,代碼來源:server.go

示例3: parseRSAPrivateKey

func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err os.Error) {
	rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey)
	rsaPriv := new(rsa.PrivateKey)
	rsaPriv.PublicKey = *rsaPub

	buf := bytes.NewBuffer(data)
	d, _, err := readMPI(buf)
	if err != nil {
		return
	}
	p, _, err := readMPI(buf)
	if err != nil {
		return
	}
	q, _, err := readMPI(buf)
	if err != nil {
		return
	}

	rsaPriv.D = new(big.Int).SetBytes(d)
	rsaPriv.P = new(big.Int).SetBytes(p)
	rsaPriv.Q = new(big.Int).SetBytes(q)
	pk.PrivateKey = rsaPriv
	pk.Encrypted = false
	pk.encryptedData = nil

	return nil
}
開發者ID:richlowe,項目名稱:gcc,代碼行數:28,代碼來源:private_key.go

示例4: NewSignedClientCertificate

func NewSignedClientCertificate(cfg ClientCertConfig, key *rsa.PrivateKey, caCert *x509.Certificate, caKey *rsa.PrivateKey) (*x509.Certificate, error) {
	ips := make([]net.IP, len(cfg.IPAddresses))
	for i, ipStr := range cfg.IPAddresses {
		ips[i] = net.ParseIP(ipStr)
	}

	serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64))
	if err != nil {
		return nil, err
	}

	if cfg.Duration <= 0 {
		return nil, errors.New("Cert duration must not be negative or zero.")
	}

	certTmpl := x509.Certificate{
		Subject: pkix.Name{
			CommonName:   cfg.CommonName,
			Organization: caCert.Subject.Organization,
		},
		DNSNames:     cfg.DNSNames,
		IPAddresses:  ips,
		SerialNumber: serial,
		NotBefore:    caCert.NotBefore,
		NotAfter:     time.Now().Add(cfg.Duration).UTC(),
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	certDERBytes, err := x509.CreateCertificate(rand.Reader, &certTmpl, caCert, key.Public(), caKey)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(certDERBytes)
}
開發者ID:coreos,項目名稱:coreos-kubernetes,代碼行數:34,代碼來源:x509.go

示例5: NewSignedCertificate

func NewSignedCertificate(cfg CertConfig, key *rsa.PrivateKey, caCert *x509.Certificate, caKey *rsa.PrivateKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64))
	if err != nil {
		return nil, err
	}

	certTmpl := x509.Certificate{
		Subject: pkix.Name{
			CommonName:   cfg.CommonName,
			Organization: caCert.Subject.Organization,
		},
		DNSNames:     cfg.AltNames.DNSNames,
		IPAddresses:  cfg.AltNames.IPs,
		SerialNumber: serial,
		NotBefore:    caCert.NotBefore,
		NotAfter:     time.Now().Add(Duration365d).UTC(),
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
	}
	certDERBytes, err := x509.CreateCertificate(rand.Reader, &certTmpl, caCert, key.Public(), caKey)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(certDERBytes)
}
開發者ID:40a,項目名稱:bootkube,代碼行數:25,代碼來源:tlsutil.go

示例6: NewSelfSignedCACertificate

func NewSelfSignedCACertificate(cfg CertConfig, key *rsa.PrivateKey, validDuration time.Duration) (*x509.Certificate, error) {
	now := time.Now()

	dur := Duration365d * 10
	if validDuration != 0 {
		dur = validDuration
	}

	tmpl := x509.Certificate{
		SerialNumber: new(big.Int).SetInt64(0),
		Subject: pkix.Name{
			CommonName:   cfg.CommonName,
			Organization: cfg.Organization,
		},
		NotBefore:             now,
		NotAfter:              now.Add(dur),
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA: true,
	}

	certDERBytes, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(certDERBytes)
}
開發者ID:jonboulle,項目名稱:pkg,代碼行數:27,代碼來源:k8s-tlsutil.go

示例7: signPKCS7

// signPKCS7 does the minimal amount of work necessary to embed an RSA
// signature into a PKCS#7 certificate.
//
// We prepare the certificate using the x509 package, read it back in
// to our custom data type and then write it back out with the signature.
func signPKCS7(rand io.Reader, priv *rsa.PrivateKey, msg []byte) ([]byte, error) {
	const serialNumber = 0x5462c4dd // arbitrary
	name := pkix.Name{CommonName: "gomobile"}

	template := &x509.Certificate{
		SerialNumber:       big.NewInt(serialNumber),
		SignatureAlgorithm: x509.SHA1WithRSA,
		Subject:            name,
	}

	b, err := x509.CreateCertificate(rand, template, template, priv.Public(), priv)
	if err != nil {
		return nil, err
	}

	c := certificate{}
	if _, err := asn1.Unmarshal(b, &c); err != nil {
		return nil, err
	}

	h := sha1.New()
	h.Write(msg)
	hashed := h.Sum(nil)

	signed, err := rsa.SignPKCS1v15(rand, priv, crypto.SHA1, hashed)
	if err != nil {
		return nil, err
	}

	content := pkcs7SignedData{
		ContentType: oidSignedData,
		Content: signedData{
			Version: 1,
			DigestAlgorithms: []pkix.AlgorithmIdentifier{{
				Algorithm:  oidSHA1,
				Parameters: asn1.RawValue{Tag: 5},
			}},
			ContentInfo:  contentInfo{Type: oidData},
			Certificates: c,
			SignerInfos: []signerInfo{{
				Version: 1,
				IssuerAndSerialNumber: issuerAndSerialNumber{
					Issuer:       name.ToRDNSequence(),
					SerialNumber: serialNumber,
				},
				DigestAlgorithm: pkix.AlgorithmIdentifier{
					Algorithm:  oidSHA1,
					Parameters: asn1.RawValue{Tag: 5},
				},
				DigestEncryptionAlgorithm: pkix.AlgorithmIdentifier{
					Algorithm:  oidRSAEncryption,
					Parameters: asn1.RawValue{Tag: 5},
				},
				EncryptedDigest: signed,
			}},
		},
	}

	return asn1.Marshal(content)
}
開發者ID:2722,項目名稱:lantern,代碼行數:65,代碼來源:cert.go

示例8: MarshalPKCS1PrivateKey

// MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
	key.Precompute()

	version := 0
	if len(key.Primes) > 2 {
		version = 1
	}

	priv := pkcs1PrivateKey{
		Version: version,
		N:       key.N,
		E:       key.PublicKey.E,
		D:       key.D,
		P:       key.Primes[0],
		Q:       key.Primes[1],
		Dp:      key.Precomputed.Dp,
		Dq:      key.Precomputed.Dq,
		Qinv:    key.Precomputed.Qinv,
	}

	priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
	for i, values := range key.Precomputed.CRTValues {
		priv.AdditionalPrimes[i].Prime = key.Primes[2+i]
		priv.AdditionalPrimes[i].Exp = values.Exp
		priv.AdditionalPrimes[i].Coeff = values.Coeff
	}

	b, _ := asn1.Marshal(priv)
	return b
}
開發者ID:aubonbeurre,項目名稱:gcc,代碼行數:31,代碼來源:pkcs1.go

示例9: NewRsaEncrypt

func NewRsaEncrypt(privateKeyInput io.Reader, keyBytes int, newHash func() hash.Hash) (*RsaEncrypt, error) {
	data, err := ioutil.ReadAll(privateKeyInput)
	if err != nil {
		return nil, err
	}

	var block *pem.Block
	if block, _ = pem.Decode(data); block == nil || block.Type != "RSA PRIVATE KEY" {
		return nil, errors.New("wrong private key")
	}

	var privateKey *rsa.PrivateKey
	if privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
		return nil, err
	}

	privateKey.Precompute()
	if err = privateKey.Validate(); err != nil {
		return nil, err
	}
	h := newHash()
	r := &RsaEncrypt{
		privateKey:  privateKey,
		keyBytes:    keyBytes,
		maxMsgBytes: keyBytes - (h.Size()*2 + 2),
		newHash:     newHash,
	}
	return r, nil
}
開發者ID:RivenZoo,項目名稱:goutil,代碼行數:29,代碼來源:rsa.go

示例10: MarshalPKCS1PrivateKey

// MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
	key.Precompute()

	version := 0
	if len(key.Primes) > 2 {
		version = 1
	}

	priv := pkcs1PrivateKey{
		Version: version,
		N:       rawValueForBig(key.N),
		E:       key.PublicKey.E,
		D:       rawValueForBig(key.D),
		P:       rawValueForBig(key.Primes[0]),
		Q:       rawValueForBig(key.Primes[1]),
		Dp:      rawValueForBig(key.Precomputed.Dp),
		Dq:      rawValueForBig(key.Precomputed.Dq),
		Qinv:    rawValueForBig(key.Precomputed.Qinv),
	}

	priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
	for i, values := range key.Precomputed.CRTValues {
		priv.AdditionalPrimes[i].Prime = rawValueForBig(key.Primes[2+i])
		priv.AdditionalPrimes[i].Exp = rawValueForBig(values.Exp)
		priv.AdditionalPrimes[i].Coeff = rawValueForBig(values.Coeff)
	}

	b, _ := asn1.Marshal(priv)
	return b
}
開發者ID:go-nosql,項目名稱:golang,代碼行數:31,代碼來源:x509.go

示例11: main

func main() {
	var primes []uint64 = prime.PrimeSieveBatch{BatchSize: 100}.GetPrimes(10000)
	var p, q uint64 = /*uint64(104723), uint64(104729) */ primes[len(primes)-2], primes[len(primes)-1]
	fmt.Println(p, q)
	var mod int64 = int64(p * q)
	fmt.Println(mod)
	var puk, prk = /*int(65537), uint64(10195862609) */ KeyGenerator1{}.KeyGen(p, q)
	fmt.Println(puk, prk)

	b := []byte("Hi")
	var pub rsa.PublicKey = rsa.PublicKey{N: big.NewInt(mod), E: puk}
	var priv rsa.PrivateKey = rsa.PrivateKey{PublicKey: pub}
	priv.D = big.NewInt(int64(prk))
	priv.Primes = []*big.Int{big.NewInt(int64(p)), big.NewInt(int64(q))}

	fmt.Println(len(b))
	fmt.Printf("% x\n", b)

	//h := md5.New()
	enc, erre := rsa.EncryptPKCS1v15(rand.Reader, &pub, b)
	//h.Reset()
	dec, errd := rsa.DecryptPKCS1v15(rand.Reader, &priv, b)

	//fmt.Println(64 - 11)
	fmt.Printf("%s\n", erre)
	fmt.Printf("%s\n", errd)
	fmt.Printf("% x\n", enc)
	fmt.Printf("% x\n", dec)
}
開發者ID:frankbryce,項目名稱:crypto-explore,代碼行數:29,代碼來源:main.go

示例12: GetTLSCertificate

// GetTLSCertificate - takes x509 cert and private key, returns tls.Certificate that is ready for proxy use
func GetTLSCertificate(cert *x509.Certificate, priv *rsa.PrivateKey, hostname string, validity time.Duration) (*tls.Certificate, error) {
	host, _, err := net.SplitHostPort(hostname)
	if err == nil {
		hostname = host
	}
	pub := priv.Public()

	pkixpub, err := x509.MarshalPKIXPublicKey(pub)
	if err != nil {
		return nil, err
	}
	h := sha1.New()
	h.Write(pkixpub)
	keyID := h.Sum(nil)

	serial, err := rand.Int(rand.Reader, MaxSerialNumber)
	if err != nil {
		return nil, err
	}

	tmpl := &x509.Certificate{
		SerialNumber: serial,
		Subject: pkix.Name{
			CommonName:   hostname,
			Organization: cert.Subject.Organization,
		},
		SubjectKeyId:          keyID,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		NotBefore:             time.Now().Add(validity),
		NotAfter:              time.Now().Add(validity),
	}

	if ip := net.ParseIP(hostname); ip != nil {
		tmpl.IPAddresses = []net.IP{ip}
	} else {
		tmpl.DNSNames = []string{hostname}
	}

	raw, err := x509.CreateCertificate(rand.Reader, tmpl, cert, priv.Public(), priv)
	if err != nil {
		return nil, err
	}

	// Parse certificate bytes to get a leaf certificate
	x509c, err := x509.ParseCertificate(raw)
	if err != nil {
		return nil, err
	}

	tlsc := &tls.Certificate{
		Certificate: [][]byte{raw, cert.Raw},
		PrivateKey:  priv,
		Leaf:        x509c,
	}

	return tlsc, nil
}
開發者ID:SpectoLabs,項目名稱:hoverfly,代碼行數:60,代碼來源:certs.go

示例13: NewKeyChain

// NewKeyChain sets up a new keychain based on the RSA private key passed
// in. It ensures the returned keychain is valid.
func NewKeyChain(prv *rsa.PrivateKey) (kc *KeyChain, err error) {
	if err = prv.Validate(); err != nil {
		return
	}
	kc = new(KeyChain)
	kc.Private = prv
	kc.Public = make([]*PubKey, 0)
	return
}
開發者ID:jonathanmarvens,項目名稱:gocrypto,代碼行數:11,代碼來源:keychain.go

示例14: keyFunc

func keyFunc(key *rsa.PrivateKey) func(token *jwt.Token) (interface{}, error) {
	return func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}

		return key.Public(), nil
	}
}
開發者ID:xoebus,項目名稱:checkin,代碼行數:9,代碼來源:oauth_handler.go

示例15: UnpackPrivateKey

// msg -> rsa
func UnpackPrivateKey(k *msgs.PrivateKey) *rsa.PrivateKey {
	var key rsa.PrivateKey
	key.PublicKey = *UnpackKey(k.PublicKey)
	key.D = new(big.Int)
	key.D.SetBytes(k.D)
	for _, p := range k.Primes {
		key.Primes = append(key.Primes, new(big.Int).SetBytes(p))
	}
	return &key
}
開發者ID:Craig-Macomber,項目名稱:election,代碼行數:11,代碼來源:pack.go


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