Skip to content

Commit

Permalink
Spec - Secure key storage (#481)
Browse files Browse the repository at this point in the history
* Implement secure key storage using PKCS8

* Fix lint issue

* Switch back PKCS8 to PKCS1
  • Loading branch information
MatheusFranco99 authored and GalRogozinski committed Sep 12, 2024
1 parent b9fdc3c commit d502f36
Showing 1 changed file with 11 additions and 23 deletions.
34 changes: 11 additions & 23 deletions types/encryption.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,39 +49,26 @@ func Encrypt(pk *rsa.PublicKey, plainText []byte) ([]byte, error) {
// PemToPrivateKey return rsa private key from pem
func PemToPrivateKey(skPem []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(skPem)
// nolint
enc := x509.IsEncryptedPEMBlock(block)
b := block.Bytes
if enc {
var err error
// nolint
b, err = x509.DecryptPEMBlock(block, nil)
if err != nil {
return nil, errors.Wrap(err, "Failed to decrypt private key")
}
if block == nil {
return nil, errors.New("failed to decode PEM")
}
parsedSk, err := x509.ParsePKCS1PrivateKey(b)

// Parse key as PKCS1
parsedSk, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, errors.Wrap(err, "Failed to parse private key")
}

return parsedSk, nil
}

// PemToPublicKey return rsa public key from pem
func PemToPublicKey(pkPem []byte) (*rsa.PublicKey, error) {
block, _ := pem.Decode(pkPem)
// nolint
enc := x509.IsEncryptedPEMBlock(block)
b := block.Bytes
if enc {
var err error
// nolint
b, err = x509.DecryptPEMBlock(block, nil)
if err != nil {
return nil, errors.Wrap(err, "Failed to decrypt private key")
}
if block == nil {
return nil, errors.New("failed to decode PEM")
}
parsedPk, err := x509.ParsePKIXPublicKey(b)
parsedPk, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, errors.Wrap(err, "Failed to parse public key")
}
Expand All @@ -93,10 +80,11 @@ func PemToPublicKey(pkPem []byte) (*rsa.PublicKey, error) {

// PrivateKeyToPem converts privateKey to pem encoded
func PrivateKeyToPem(sk *rsa.PrivateKey) []byte {
pemBytes := x509.MarshalPKCS1PrivateKey(sk)
return pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(sk),
Bytes: pemBytes,
},
)
}
Expand Down

0 comments on commit d502f36

Please sign in to comment.