File: rsa.go

package info (click to toggle)
golang-github-dvsekhvalnov-jose2go 1.5-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 440 kB
  • sloc: makefile: 4
file content (62 lines) | stat: -rw-r--r-- 1,544 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//package Rsa provides helpers for creating rsa leys
package Rsa

import (
		"crypto/rsa"
	    "crypto/x509"
		"encoding/pem"
		"errors"
)

// ReadPrivate loads rsa.PrivateKey from PKCS1 or PKCS8 blobs 
func ReadPrivate(raw []byte) (key *rsa.PrivateKey,err error) {	
	var encoded *pem.Block

	if encoded, _ = pem.Decode(raw); encoded == nil {
		return nil, errors.New("Rsa.NewPrivate(): Key must be PEM encoded PKCS1 or PKCS8 private key")
	}

	var parsedKey interface{}

	if parsedKey,err=x509.ParsePKCS1PrivateKey(encoded.Bytes);err!=nil {
		if parsedKey, err = x509.ParsePKCS8PrivateKey(encoded.Bytes);err!=nil {
			return nil,err
		}
	}

	var ok bool
		
	if key,ok=parsedKey.(*rsa.PrivateKey);!ok {
		return nil, errors.New("Rsa.NewPrivate(): Key is not valid *rsa.PrivateKey")
	}
	
	return key,nil
}

// ReadPublic loads rsa.PublicKey from PKIX or PKCS1 X509 blobs
func ReadPublic(raw []byte) (key *rsa.PublicKey,err error)  {
	var encoded *pem.Block
	
	if encoded, _ = pem.Decode(raw); encoded == nil {
		return nil, errors.New("Rsa.NewPublic(): Key must be PEM encoded PKCS1 X509 certificate or PKIX public key")
	}
		
	var parsedKey interface{}
	var cert *x509.Certificate
	
	if parsedKey, err = x509.ParsePKIXPublicKey(encoded.Bytes); err != nil {
		if cert,err = x509.ParseCertificate(encoded.Bytes);err!=nil {
			return nil, err
		}
		
		parsedKey=cert.PublicKey
	}
	
	var ok bool
	
	if key, ok = parsedKey.(*rsa.PublicKey); !ok {
		return nil, errors.New("Rsa.NewPublic(): Key is not a valid RSA public key")
	}
	
	return key, nil
}