asymmetric.go

v1.0.0
Doc Versions Source
1
package crypto
2
3
import (
4
	"crypto/rand"
5
	"crypto/rsa"
6
	"crypto/sha1"
7
	"crypto/sha256"
8
	"crypto/x509"
9
	"fmt"
10
	"hash"
11
)
12
13
// DecryptRSA decrypts a CipherString using an RSA private key.
14
func DecryptRSA(cs *CipherString, privKey *rsa.PrivateKey) ([]byte, error) {
15
	var h hash.Hash
16
	switch cs.Type {
17
	case EncRsa2048_OaepSha1_B64, EncRsa2048_OaepSha1_HmacSha256_B64:
18
		h = sha1.New()
19
	case EncRsa2048_OaepSha256_B64, EncRsa2048_OaepSha256_HmacSha256_B64:
20
		h = sha256.New()
21
	default:
22
		return nil, fmt.Errorf("not an RSA cipher string type: %d", cs.Type)
23
	}
24
25
	plaintext, err := rsa.DecryptOAEP(h, rand.Reader, privKey, cs.CT, nil)
26
	if err != nil {
27
		return nil, fmt.Errorf("RSA decrypt: %w", err)
28
	}
29
	return plaintext, nil
30
}
31
32
// EncryptRSA encrypts plaintext with an RSA public key using OAEP-SHA1 (type 4).
33
func EncryptRSA(plaintext []byte, pubKey *rsa.PublicKey) (*CipherString, error) {
34
	ct, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, pubKey, plaintext, nil)
35
	if err != nil {
36
		return nil, fmt.Errorf("RSA encrypt: %w", err)
37
	}
38
	return &CipherString{
39
		Type: EncRsa2048_OaepSha1_B64,
40
		CT:   ct,
41
	}, nil
42
}
43
44
// GenerateRSAKeyPair generates a 2048-bit RSA key pair.
45
func GenerateRSAKeyPair() (*rsa.PrivateKey, error) {
46
	return rsa.GenerateKey(rand.Reader, 2048)
47
}
48
49
// MarshalPrivateKey marshals an RSA private key to PKCS8 DER format.
50
func MarshalPrivateKey(key *rsa.PrivateKey) ([]byte, error) {
51
	return x509.MarshalPKCS8PrivateKey(key)
52
}
53
54
// MarshalPublicKey marshals an RSA public key to PKIX DER format.
55
func MarshalPublicKey(key *rsa.PublicKey) ([]byte, error) {
56
	return x509.MarshalPKIXPublicKey(key)
57
}
58
59
// ParsePrivateKey parses a PKCS8 DER-encoded RSA private key.
60
func ParsePrivateKey(der []byte) (*rsa.PrivateKey, error) {
61
	key, err := x509.ParsePKCS8PrivateKey(der)
62
	if err != nil {
63
		return nil, fmt.Errorf("parse PKCS8 private key: %w", err)
64
	}
65
	rsaKey, ok := key.(*rsa.PrivateKey)
66
	if !ok {
67
		return nil, fmt.Errorf("not an RSA private key")
68
	}
69
	return rsaKey, nil
70
}
71

Source Files