| 1 |
package keypair |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto/ecdsa" |
| 5 |
"crypto/rand" |
| 6 |
"encoding/pem" |
| 7 |
"strings" |
| 8 |
|
| 9 |
"github.com/dromara/dongle/coding" |
| 10 |
"github.com/dromara/dongle/crypto/internal/sm2" |
| 11 |
"github.com/dromara/dongle/internal/utils" |
| 12 |
) |
| 13 |
|
| 14 |
// Sm2CipherMode specifies the concatenation mode of SM2 ciphertext |
| 15 |
// components. It controls how the library assembles (encrypt) and |
| 16 |
// interprets (decrypt) the C1, C2, C3 parts. |
| 17 |
// |
| 18 |
// C1: EC point (x1||y1) in uncompressed form; C2: XORed plaintext; |
| 19 |
// C3: SM3 digest over x2 || M || y2. |
| 20 |
type Sm2CipherMode string |
| 21 |
|
| 22 |
// Supported SM2 ciphertext orders. |
| 23 |
const ( |
| 24 |
// C1C2C3 means ciphertext bytes are C1 || C2 || C3. |
| 25 |
C1C2C3 Sm2CipherMode = "c1c2c3" |
| 26 |
// C1C3C2 means ciphertext bytes are C1 || C3 || C2. |
| 27 |
C1C3C2 Sm2CipherMode = "c1c3c2" |
| 28 |
) |
| 29 |
|
| 30 |
var ( |
| 31 |
bitStringPublicKeyParser = sm2.ParseBitStringPublicKey |
| 32 |
bitStringPrivateKeyParser = sm2.ParseBitStringPrivateKey |
| 33 |
) |
| 34 |
|
| 35 |
// Sm2KeyPair represents an SM2 key pair with public and private keys. |
| 36 |
// Keys are handled in PKCS8 (for private) and PKIX (for public) PEM formats. |
| 37 |
type Sm2KeyPair struct { |
| 38 |
// PublicKey contains the PEM-encoded public key |
| 39 |
PublicKey []byte |
| 40 |
|
| 41 |
// PrivateKey contains the PEM-encoded private key |
| 42 |
PrivateKey []byte |
| 43 |
|
| 44 |
// Order specifies the mode of SM2 ciphertext components. |
| 45 |
// It controls how Encrypt assembles and Decrypt interprets ciphertext. |
| 46 |
Mode Sm2CipherMode |
| 47 |
|
| 48 |
// Window controls internal SM2 fixed-base/wNAF window size (2..6). |
| 49 |
// 4 means use library default. |
| 50 |
Window int |
| 51 |
|
| 52 |
// UID is the user identifier for SM2 signature operations. |
| 53 |
// If empty, the default UID "1234567812345678" will be used (per GM/T 0009-2012). |
| 54 |
UID []byte |
| 55 |
} |
| 56 |
|
| 57 |
// NewSm2KeyPair returns a new Sm2KeyPair with defaults |
| 58 |
// (Order=C1C3C2, Window=4). |
| 59 |
func NewSm2KeyPair() *Sm2KeyPair { |
| 60 |
return &Sm2KeyPair{ |
| 61 |
Mode: C1C3C2, |
| 62 |
Window: 4, |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
// GenKeyPair generates a new SM2 key pair and fills PublicKey/PrivateKey. |
| 67 |
// Private key is PKCS#8 (PEM "PRIVATE KEY"), public key is SPKI/PKIX (PEM "PUBLIC KEY"). |
| 68 |
func (k *Sm2KeyPair) GenKeyPair() error { |
| 69 |
c := sm2.NewCurve() |
| 70 |
|
| 71 |
// Generate unbiased scalar d in range [1, n-1] |
| 72 |
d, err := sm2.RandScalar(c, rand.Reader) |
| 73 |
if err != nil { |
| 74 |
return err |
| 75 |
} |
| 76 |
|
| 77 |
x, y := c.ScalarBaseMult(d.Bytes()) |
| 78 |
privateKey := &ecdsa.PrivateKey{PublicKey: ecdsa.PublicKey{Curve: c, X: x, Y: y}, D: d} |
| 79 |
|
| 80 |
// Marshal PKCS8 private key |
| 81 |
privateKeyDer, _ := sm2.MarshalPKCS8PrivateKey(privateKey) |
| 82 |
k.PrivateKey = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privateKeyDer}) |
| 83 |
|
| 84 |
// Marshal SPKI public key |
| 85 |
publicKeyDer, _ := sm2.MarshalSPKIPublicKey(&privateKey.PublicKey) |
| 86 |
k.PublicKey = pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicKeyDer}) |
| 87 |
return nil |
| 88 |
} |
| 89 |
|
| 90 |
// SetOrder sets ciphertext order to C1C3C2 or C1C2C3. |
| 91 |
// Deprecated: `SetOrder` will be removed in the future, use `SetMode` instead. |
| 92 |
func (k *Sm2KeyPair) SetOrder(order Sm2CipherMode) { |
| 93 |
k.SetMode(order) |
| 94 |
} |
| 95 |
|
| 96 |
// SetMode sets ciphertext mode to C1C3C2 or C1C2C3. |
| 97 |
// It affects how Encrypt assembles and Decrypt interprets ciphertext. |
| 98 |
func (k *Sm2KeyPair) SetMode(mode Sm2CipherMode) { |
| 99 |
k.Mode = mode |
| 100 |
} |
| 101 |
|
| 102 |
// SetWindow sets scalar-multiplication window (2..6). |
| 103 |
// Values outside the range are clamped. |
| 104 |
func (k *Sm2KeyPair) SetWindow(window int) { |
| 105 |
if window < 2 { |
| 106 |
window = 2 |
| 107 |
} |
| 108 |
if window > 6 { |
| 109 |
window = 6 |
| 110 |
} |
| 111 |
k.Window = window |
| 112 |
} |
| 113 |
|
| 114 |
// SetUID sets the user identifier for SM2 signature operations. |
| 115 |
// If uid is nil or empty, the default UID "1234567812345678" will be used. |
| 116 |
func (k *Sm2KeyPair) SetUID(uid []byte) { |
| 117 |
k.UID = uid |
| 118 |
} |
| 119 |
|
| 120 |
// SetPublicKey sets the public key after formatting to PEM. |
| 121 |
// Accepts base64-encoded DER of SubjectPublicKeyInfo. |
| 122 |
func (k *Sm2KeyPair) SetPublicKey(publicKey []byte) error { |
| 123 |
key, err := k.FormatPublicKey(publicKey) |
| 124 |
if err == nil { |
| 125 |
k.PublicKey = key |
| 126 |
} |
| 127 |
return err |
| 128 |
} |
| 129 |
|
| 130 |
// SetPrivateKey sets the private key after formatting to PEM. |
| 131 |
// Accepts base64-encoded DER of PKCS#8 PrivateKeyInfo. |
| 132 |
func (k *Sm2KeyPair) SetPrivateKey(privateKey []byte) error { |
| 133 |
key, err := k.FormatPrivateKey(privateKey) |
| 134 |
if err == nil { |
| 135 |
k.PrivateKey = key |
| 136 |
} |
| 137 |
return err |
| 138 |
} |
| 139 |
|
| 140 |
// ParsePublicKey parses the PEM-encoded public key and returns *sm2.PublicKey. |
| 141 |
func (k *Sm2KeyPair) ParsePublicKey() (*ecdsa.PublicKey, error) { |
| 142 |
publicKey := k.PublicKey |
| 143 |
if len(publicKey) == 0 { |
| 144 |
return nil, EmptyPublicKeyError{} |
| 145 |
} |
| 146 |
if len(publicKey) == 65 { |
| 147 |
pub, err := bitStringPublicKeyParser(publicKey) |
| 148 |
if err != nil { |
| 149 |
return nil, InvalidPublicKeyError{Err: err} |
| 150 |
} |
| 151 |
return pub, nil |
| 152 |
} |
| 153 |
block, _ := pem.Decode(publicKey) |
| 154 |
if block == nil || block.Type != "PUBLIC KEY" { |
| 155 |
return nil, InvalidPublicKeyError{} |
| 156 |
} |
| 157 |
pub, err := sm2.ParseSPKIPublicKey(block.Bytes) |
| 158 |
if err != nil { |
| 159 |
return nil, InvalidPublicKeyError{Err: err} |
| 160 |
} |
| 161 |
return pub, nil |
| 162 |
} |
| 163 |
|
| 164 |
// ParsePrivateKey parses the PEM-encoded private key and returns *sm2.PrivateKey. |
| 165 |
func (k *Sm2KeyPair) ParsePrivateKey() (*ecdsa.PrivateKey, error) { |
| 166 |
privateKey := k.PrivateKey |
| 167 |
if len(privateKey) == 0 { |
| 168 |
return nil, EmptyPrivateKeyError{} |
| 169 |
} |
| 170 |
if len(privateKey) == 32 { |
| 171 |
pri, err := bitStringPrivateKeyParser(privateKey) |
| 172 |
if err != nil { |
| 173 |
return nil, InvalidPrivateKeyError{Err: err} |
| 174 |
} |
| 175 |
return pri, nil |
| 176 |
} |
| 177 |
block, _ := pem.Decode(privateKey) |
| 178 |
if block == nil || block.Type != "PRIVATE KEY" { |
| 179 |
return nil, InvalidPrivateKeyError{} |
| 180 |
} |
| 181 |
pri, err := sm2.ParsePKCS8PrivateKey(block.Bytes) |
| 182 |
if err != nil { |
| 183 |
return nil, InvalidPrivateKeyError{Err: err} |
| 184 |
} |
| 185 |
return pri, nil |
| 186 |
} |
| 187 |
|
| 188 |
// FormatPublicKey formats base64-encoded der public key into the specified PEM format. |
| 189 |
func (k *Sm2KeyPair) FormatPublicKey(publicKey []byte) ([]byte, error) { |
| 190 |
if len(publicKey) == 0 { |
| 191 |
return []byte{}, EmptyPublicKeyError{} |
| 192 |
} |
| 193 |
decoder := coding.NewDecoder().FromBytes(publicKey).ByBase64() |
| 194 |
if decoder.Error != nil { |
| 195 |
return []byte{}, InvalidPublicKeyError{Err: decoder.Error} |
| 196 |
} |
| 197 |
return pem.EncodeToMemory(&pem.Block{ |
| 198 |
Type: "PUBLIC KEY", |
| 199 |
Bytes: decoder.ToBytes(), |
| 200 |
}), nil |
| 201 |
} |
| 202 |
|
| 203 |
// FormatPrivateKey formats base64-encoded der private key into the specified PEM format. |
| 204 |
func (k *Sm2KeyPair) FormatPrivateKey(privateKey []byte) ([]byte, error) { |
| 205 |
if len(privateKey) == 0 { |
| 206 |
return []byte{}, EmptyPrivateKeyError{} |
| 207 |
} |
| 208 |
decoder := coding.NewDecoder().FromBytes(privateKey).ByBase64() |
| 209 |
if decoder.Error != nil { |
| 210 |
return []byte{}, InvalidPrivateKeyError{Err: decoder.Error} |
| 211 |
} |
| 212 |
return pem.EncodeToMemory(&pem.Block{ |
| 213 |
Type: "PRIVATE KEY", |
| 214 |
Bytes: decoder.ToBytes(), |
| 215 |
}), nil |
| 216 |
} |
| 217 |
|
| 218 |
// CompressPublicKey strips headers/footers and whitespace from the PEM public key. |
| 219 |
func (k *Sm2KeyPair) CompressPublicKey(publicKey []byte) []byte { |
| 220 |
keyStr := utils.Bytes2String(publicKey) |
| 221 |
keyStr = strings.ReplaceAll(keyStr, "-----BEGIN PUBLIC KEY-----", "") |
| 222 |
keyStr = strings.ReplaceAll(keyStr, "-----END PUBLIC KEY-----", "") |
| 223 |
keyStr = strings.ReplaceAll(keyStr, "\n", "") |
| 224 |
keyStr = strings.ReplaceAll(keyStr, "\r", "") |
| 225 |
keyStr = strings.ReplaceAll(keyStr, " ", "") |
| 226 |
keyStr = strings.ReplaceAll(keyStr, "\t", "") |
| 227 |
keyStr = strings.TrimSpace(keyStr) |
| 228 |
return utils.String2Bytes(keyStr) |
| 229 |
} |
| 230 |
|
| 231 |
// CompressPrivateKey strips headers/footers and whitespace from the PEM private key. |
| 232 |
func (k *Sm2KeyPair) CompressPrivateKey(privateKey []byte) []byte { |
| 233 |
keyStr := utils.Bytes2String(privateKey) |
| 234 |
keyStr = strings.ReplaceAll(keyStr, "-----BEGIN PRIVATE KEY-----", "") |
| 235 |
keyStr = strings.ReplaceAll(keyStr, "-----END PRIVATE KEY-----", "") |
| 236 |
keyStr = strings.ReplaceAll(keyStr, "-----BEGIN ENCRYPTED PRIVATE KEY-----", "") |
| 237 |
keyStr = strings.ReplaceAll(keyStr, "-----END ENCRYPTED PRIVATE KEY-----", "") |
| 238 |
keyStr = strings.ReplaceAll(keyStr, "\n", "") |
| 239 |
keyStr = strings.ReplaceAll(keyStr, "\r", "") |
| 240 |
keyStr = strings.ReplaceAll(keyStr, " ", "") |
| 241 |
keyStr = strings.ReplaceAll(keyStr, "\t", "") |
| 242 |
keyStr = strings.TrimSpace(keyStr) |
| 243 |
return utils.String2Bytes(keyStr) |
| 244 |
} |