Gopki
Jump to navigation
Jump to search
package pki
import (
"crypto" "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/pem" "errors"
)
// GenerateKeyPair generates a new RSA public/private key pair. func GenerateKeyPair() (*rsa.PrivateKey, *rsa.PublicKey, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return nil, nil, err } publicKey := &privateKey.PublicKey return privateKey, publicKey, nil
}
// MarshalPrivateKeyPEM marshals an RSA private key to PEM format. func MarshalPrivateKeyPEM(privateKey *rsa.PrivateKey) ([]byte, error) {
privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey) privateKeyPEM := pem.EncodeToMemory(&pem.Block{ Type: "RSA PRIVATE KEY", Bytes: privateKeyBytes, }) return privateKeyPEM, nil
}
// UnmarshalPrivateKeyPEM unmarshals an RSA private key from PEM format. func UnmarshalPrivateKeyPEM(privateKeyPEM []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(privateKeyPEM) if block == nil || block.Type != "RSA PRIVATE KEY" { return nil, errors.New("failed to decode PEM block containing RSA private key") } privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, err } return privateKey, nil
}
// Sign signs a message using an RSA private key. func Sign(privateKey *rsa.PrivateKey, message []byte) ([]byte, error) {
hashed := sha256.Sum256(message) signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed[:]) if err != nil { return nil, err } return signature, nil
}
// Verify verifies a signature against a message using an RSA public key. func Verify(publicKey *rsa.PublicKey, message []byte, signature []byte) error {
hashed := sha256.Sum256(message) err := rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hashed[:], signature) if err != nil { return err } return nil
}