- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
359 lines
10 KiB
Go
359 lines
10 KiB
Go
// Shared cryptographic primitives for security connector
|
|
// Implements ECDH P-256, ECDSA P-256, AES-256-GCM, SHA-256
|
|
|
|
package crypto
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/ecdsa"
|
|
"crypto/elliptic"
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/x509"
|
|
"encoding/base64"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math/big"
|
|
|
|
"golang.org/x/crypto/hkdf"
|
|
)
|
|
|
|
var (
|
|
// CurveP256 is the P-256 elliptic curve
|
|
CurveP256 = elliptic.P256()
|
|
|
|
// Key sizes
|
|
AES256KeySize = 32
|
|
AES256NonceSize = 12 // GCM standard nonce size
|
|
SHA256Size = 32
|
|
|
|
// HKDF info strings
|
|
HKDFInfoKEK = "KEK derivation"
|
|
HKDFInfoDEK = "DEK derivation"
|
|
HKDFInfoSession = "Session key derivation"
|
|
)
|
|
|
|
// Errors
|
|
var (
|
|
ErrInvalidKeySize = errors.New("invalid key size")
|
|
ErrInvalidCurve = errors.New("invalid elliptic curve")
|
|
ErrInvalidSignature = errors.New("invalid signature")
|
|
ErrInvalidNonce = errors.New("invalid nonce size")
|
|
ErrDecryptionFailed = errors.New("decryption failed")
|
|
ErrEncryptionFailed = errors.New("encryption failed")
|
|
)
|
|
|
|
// GenerateNonce generates a random nonce of the specified size
|
|
func GenerateNonce(size int) ([]byte, error) {
|
|
nonce := make([]byte, size)
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, fmt.Errorf("failed to generate nonce: %w", err)
|
|
}
|
|
return nonce, nil
|
|
}
|
|
|
|
// GenerateECDSAKey generates a new ECDSA P-256 key pair
|
|
func GenerateECDSAKey() (*ecdsa.PrivateKey, error) {
|
|
return ecdsa.GenerateKey(CurveP256, rand.Reader)
|
|
}
|
|
|
|
// ECDH derives a shared secret using ECDH P-256
|
|
func ECDH(privateKey *ecdsa.PrivateKey, publicKey *ecdsa.PublicKey) ([]byte, error) {
|
|
if privateKey.Curve != publicKey.Curve {
|
|
return nil, ErrInvalidCurve
|
|
}
|
|
|
|
// Get shared secret point
|
|
sharedX, _ := privateKey.Curve.ScalarMult(publicKey.X, publicKey.Y, privateKey.D.Bytes())
|
|
if sharedX == nil {
|
|
return nil, errors.New("ECDH failed: shared point is at infinity")
|
|
}
|
|
|
|
// Derive key using HKDF
|
|
return DeriveKey(sharedX.Bytes(), nil, HKDFInfoKEK, AES256KeySize)
|
|
}
|
|
|
|
// DeriveKey derives a key using HKDF-SHA256
|
|
func DeriveKey(salt, ikm []byte, info string, length int) ([]byte, error) {
|
|
h := hkdf.New(sha256.New, ikm, salt, []byte(info))
|
|
out := make([]byte, length)
|
|
if _, err := io.ReadFull(h, out); err != nil {
|
|
return nil, fmt.Errorf("HKDF failed: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Sign signs data using ECDSA P-256
|
|
func Sign(privateKey *ecdsa.PrivateKey, data []byte) ([]byte, error) {
|
|
hash := sha256.Sum256(data)
|
|
sig, err := ecdsa.SignASN1(rand.Reader, privateKey, hash[:])
|
|
if err != nil {
|
|
return nil, fmt.Errorf("ECDSA sign failed: %w", err)
|
|
}
|
|
return sig, nil
|
|
}
|
|
|
|
// Verify verifies an ECDSA P-256 signature
|
|
func Verify(publicKey *ecdsa.PublicKey, data []byte, sig []byte) bool {
|
|
hash := sha256.Sum256(data)
|
|
return ecdsa.VerifyASN1(publicKey, hash[:], sig)
|
|
}
|
|
|
|
// SignWithKDF signs data after deriving key using HKDF
|
|
func SignWithKDF(privateKey *ecdsa.PrivateKey, data []byte, salt []byte, info string) ([]byte, error) {
|
|
derivedKey, err := DeriveKey(salt, nil, info, 32)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Create new private key with derived scalar
|
|
newPrivateKey := &ecdsa.PrivateKey{
|
|
PublicKey: ecdsa.PublicKey{
|
|
Curve: privateKey.Curve,
|
|
X: privateKey.X,
|
|
Y: privateKey.Y,
|
|
},
|
|
D: new(big.Int).SetBytes(derivedKey),
|
|
}
|
|
|
|
return Sign(newPrivateKey, data)
|
|
}
|
|
|
|
// EncryptAES256GCM encrypts data using AES-256-GCM
|
|
func EncryptAES256GCM(key, plaintext, aad []byte) ([]byte, error) {
|
|
if len(key) != AES256KeySize {
|
|
return nil, ErrInvalidKeySize
|
|
}
|
|
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create cipher: %w", err)
|
|
}
|
|
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := rand.Read(nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
out := gcm.Seal(nonce, nonce, plaintext, aad)
|
|
return out, nil
|
|
}
|
|
|
|
// DecryptAES256GCM decrypts data using AES-256-GCM
|
|
func DecryptAES256GCM(key, ciphertext, aad []byte) ([]byte, error) {
|
|
if len(key) != AES256KeySize {
|
|
return nil, ErrInvalidKeySize
|
|
}
|
|
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create cipher: %w", err)
|
|
}
|
|
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if len(ciphertext) < gcm.NonceSize() {
|
|
return nil, ErrDecryptionFailed
|
|
}
|
|
|
|
nonce, ct := ciphertext[:gcm.NonceSize()], ciphertext[gcm.NonceSize():]
|
|
plaintext, err := gcm.Open(nil, nonce, ct, aad)
|
|
if err != nil {
|
|
return nil, ErrDecryptionFailed
|
|
}
|
|
|
|
return plaintext, nil
|
|
}
|
|
|
|
// ComputeHMAC computes HMAC-SHA256
|
|
func ComputeHMAC(key, data []byte) []byte {
|
|
h := hmac.New(sha256.New, key)
|
|
h.Write(data)
|
|
return h.Sum(nil)
|
|
}
|
|
|
|
// VerifyHMAC verifies HMAC-SHA256
|
|
func VerifyHMAC(key, data, expectedMAC []byte) bool {
|
|
mac := ComputeHMAC(key, data)
|
|
return hmac.Equal(mac, expectedMAC)
|
|
}
|
|
|
|
// HashSHA256 computes SHA-256 hash
|
|
func HashSHA256(data []byte) []byte {
|
|
h := sha256.New()
|
|
h.Write(data)
|
|
return h.Sum(nil)
|
|
}
|
|
|
|
// PQCKeyDerive is a placeholder for future PQC key derivation (ML-KEM)
|
|
// This interface allows for future PQC algorithm integration
|
|
type PQCKeyDerive interface {
|
|
KeyGen() ([]byte, []byte, error) // Returns public key, private key
|
|
Encapsulate(publicKey []byte) ([]byte, []byte, error) // Returns ciphertext, shared secret
|
|
Decapsulate(ciphertext, privateKey []byte) ([]byte, error) // Returns shared secret
|
|
}
|
|
|
|
// KeyBundle represents an encrypted key bundle
|
|
type KeyBundle struct {
|
|
EncryptedKEK []byte `json:"encrypted_kek"`
|
|
KEKVersion int `json:"kek_version"`
|
|
EncryptedDEK []byte `json:"encrypted_dek"`
|
|
Nonce []byte `json:"nonce"`
|
|
AuthTag []byte `json:"auth_tag"`
|
|
}
|
|
|
|
// EncodePublicKey encodes an ECDSA public key to bytes
|
|
func EncodePublicKey(key *ecdsa.PublicKey) ([]byte, error) {
|
|
return x509.MarshalPKIXPublicKey(key)
|
|
}
|
|
|
|
// ParsePublicKey parses an ECDSA public key from bytes
|
|
func ParsePublicKey(data []byte) (*ecdsa.PublicKey, error) {
|
|
key, err := x509.ParsePKIXPublicKey(data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ecdsaKey, ok := key.(*ecdsa.PublicKey)
|
|
if !ok {
|
|
return nil, ErrInvalidCurve
|
|
}
|
|
return ecdsaKey, nil
|
|
}
|
|
|
|
// EncodePrivateKey encodes an ECDSA private key to PEM bytes
|
|
func EncodePrivateKey(key *ecdsa.PrivateKey) ([]byte, error) {
|
|
return x509.MarshalECPrivateKey(key)
|
|
}
|
|
|
|
// ParsePrivateKey parses an ECDSA private key from PEM bytes
|
|
func ParsePrivateKey(data []byte) (*ecdsa.PrivateKey, error) {
|
|
return x509.ParseECPrivateKey(data)
|
|
}
|
|
|
|
// Base64StdEncode encodes bytes to base64
|
|
func Base64StdEncode(data []byte) string {
|
|
return base64.StdEncoding.EncodeToString(data)
|
|
}
|
|
|
|
// Base64StdDecode decodes base64 to bytes
|
|
func Base64StdDecode(s string) ([]byte, error) {
|
|
return base64.StdEncoding.DecodeString(s)
|
|
}
|
|
|
|
// IncrementUint64 increments a uint64 in little-endian byte order
|
|
func IncrementUint64(b []byte) {
|
|
if len(b) < 8 {
|
|
return
|
|
}
|
|
c := binary.LittleEndian.Uint64(b)
|
|
c++
|
|
binary.LittleEndian.PutUint64(b, c)
|
|
}
|
|
|
|
// DeriveSessionKeys derives multiple session keys using HKDF
|
|
func DeriveSessionKeys(masterSecret []byte, sessionID []byte, count int) [][]byte {
|
|
keys := make([][]byte, count)
|
|
|
|
for i := 0; i < count; i++ {
|
|
info := fmt.Sprintf("session key %d", i)
|
|
key, err := DeriveKey(nil, masterSecret, info, AES256KeySize)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
keys[i] = key
|
|
}
|
|
|
|
return keys
|
|
}
|
|
|
|
// EncryptWithECDH encrypts data using ECDH key exchange
|
|
// The sender generates an ephemeral key pair, derives shared secret via ECDH,
|
|
// and encrypts with AES-256-GCM. The recipient can decrypt using their private key.
|
|
func EncryptWithECDH(plaintext []byte, recipientPubKey *ecdsa.PublicKey, senderPrivKey *ecdsa.PrivateKey) ([]byte, error) {
|
|
// Generate ephemeral key pair
|
|
ephemeralKey, err := ecdsa.GenerateKey(CurveP256, rand.Reader)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to generate ephemeral key: %w", err)
|
|
}
|
|
|
|
// Derive shared secret via ECDH
|
|
sharedX, _ := recipientPubKey.Curve.ScalarMult(recipientPubKey.X, recipientPubKey.Y, ephemeralKey.D.Bytes())
|
|
if sharedX == nil {
|
|
return nil, errors.New("ECDH failed: shared point is at infinity")
|
|
}
|
|
|
|
// Derive AES key from shared secret
|
|
aesKey, err := DeriveKey(sharedX.Bytes(), nil, "ECDH-Encryption", AES256KeySize)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to derive AES key: %w", err)
|
|
}
|
|
|
|
// Encrypt with AES-256-GCM
|
|
// Include ephemeral public key at the beginning for recipient to reconstruct
|
|
ephemeralPubBytes, err := EncodePublicKey(&ephemeralKey.PublicKey)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to encode ephemeral public key: %w", err)
|
|
}
|
|
|
|
ciphertext, err := EncryptAES256GCM(aesKey, plaintext, ephemeralPubBytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("encryption failed: %w", err)
|
|
}
|
|
|
|
// Prepend ephemeral public key to ciphertext
|
|
result := make([]byte, 0, len(ephemeralPubBytes)+len(ciphertext))
|
|
result = append(result, ephemeralPubBytes...)
|
|
result = append(result, ciphertext...)
|
|
|
|
return result, nil
|
|
}
|
|
|
|
// DecryptWithECDH decrypts data encrypted with ECDH
|
|
func DecryptWithECDH(ciphertext []byte, recipientPrivKey *ecdsa.PrivateKey) ([]byte, error) {
|
|
// Parse ephemeral public key from the beginning of ciphertext
|
|
// First 91 bytes for P-256 compressed/uncompressed public key
|
|
pubKeySize := 91 // uncompressed P-256 public key (0x04 || X || Y)
|
|
if len(ciphertext) < pubKeySize {
|
|
return nil, errors.New("ciphertext too short")
|
|
}
|
|
|
|
ephemeralPubBytes := ciphertext[:pubKeySize]
|
|
actualCiphertext := ciphertext[pubKeySize:]
|
|
|
|
ephemeralPubKey, err := ParsePublicKey(ephemeralPubBytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to parse ephemeral public key: %w", err)
|
|
}
|
|
|
|
// Derive shared secret via ECDH
|
|
sharedX, _ := ephemeralPubKey.Curve.ScalarMult(ephemeralPubKey.X, ephemeralPubKey.Y, recipientPrivKey.D.Bytes())
|
|
if sharedX == nil {
|
|
return nil, errors.New("ECDH failed: shared point is at infinity")
|
|
}
|
|
|
|
// Derive AES key from shared secret
|
|
aesKey, err := DeriveKey(sharedX.Bytes(), nil, "ECDH-Encryption", AES256KeySize)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to derive AES key: %w", err)
|
|
}
|
|
|
|
// Decrypt with AES-256-GCM
|
|
plaintext, err := DecryptAES256GCM(aesKey, actualCiphertext, ephemeralPubBytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("decryption failed: %w", err)
|
|
}
|
|
|
|
return plaintext, nil
|
|
} |