package crypto import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "fmt" ) func NewKeyRSA(bitSize int) (pubPEM []byte, keyPEM []byte, err error) { // 生成 RSA 密鑰對 key, err := rsa.GenerateKey(rand.Reader, bitSize) if err != nil { return nil, nil, fmt.Errorf("failed to generate RSA key: %w", err) } // 提取公鑰部分並轉換為 PEM 格式 pubBytes, err := x509.MarshalPKIXPublicKey(key.Public()) if err != nil { return nil, nil, fmt.Errorf("failed to marshal public key: %w", err) } pubPEM = pem.EncodeToMemory( &pem.Block{ Type: "RSA PUBLIC KEY", Bytes: pubBytes, }, ) // 編碼私鑰為 PKCS#1 ASN.1 PEM 格式 keyPEM = pem.EncodeToMemory( &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), }, ) return pubPEM, keyPEM, nil } // EncryptRSA rsa加密 func EncryptRSA(value, publicKey []byte) ([]byte, error) { block, _ := pem.Decode(publicKey) if block == nil { return nil, errors.New("failed to decode public key PEM") } pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return nil, fmt.Errorf("failed to parse public key: %w", err) } pub, ok := pubInterface.(*rsa.PublicKey) if !ok { return nil, errors.New("invalid public key type") } // 使用公鑰進行加密 enc, err := rsa.EncryptPKCS1v15(rand.Reader, pub, value) if err != nil { return nil, fmt.Errorf("failed to encrypt with RSA: %w", err) } return enc, nil } // DecryptRSA rsa解密 func DecryptRSA(ciphertext, privateKey []byte) ([]byte, error) { block, _ := pem.Decode(privateKey) if block == nil { return nil, errors.New("failed to decode private key PEM") } priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("failed to parse private key: %w", err) } dec, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext) if err != nil { return nil, fmt.Errorf("failed to decrypt with RSA: %w", err) } return dec, nil }