🔐 非对称加密工具

使用RSA、ECC、SM2等公钥密码算法生成密钥对、加密解密数据和创建数字签名

什么是非对称加密?

非对称加密,也称为公钥密码学,使用一对数学相关的密钥:公钥和私钥。公钥可以公开分享,用于加密数据;私钥必须保密,用于解密数据。这种设计解决了对称加密中密钥分发的难题。

核心特点

  • 使用公钥-私钥对
  • 公钥可公开分享,私钥必须保密
  • 支持数字签名验证身份
  • 常用算法:RSA、ECC、SM2等

主要应用场景

  • HTTPS/TLS网站安全
  • 数字证书和PKI体系
  • 邮件加密和数字签名
  • 区块链和加密货币

安全提示

私钥的安全性至关重要,一旦泄露将导致严重的安全问题。建议使用强随机数生成器生成密钥,妥善保管私钥,定期更新密钥对,并考虑使用硬件安全模块(HSM)来保护高价值的私钥。

算法设置

输出结果

输出长度: 0

密钥管理

算法详情与实现示例

算法基本信息

算法名称:RSA-2048
算法类别:传统标准
密钥长度:2048 bits
密钥格式:PKCS#1
安全等级:良好
性能表现:中等

算法特点

RSA算法基于大整数分解的数学难题

支持加密解密和数字签名两种操作

密钥长度越长安全性越高,但性能越低

广泛用于HTTPS、SSH、邮件加密等场景

成熟稳定,但密钥长度较大,性能相对较低

使用场景与案例

HTTPS证书

网站SSL/TLS证书签名和密钥交换

SSH密钥认证

服务器远程登录公钥认证

代码签名

软件发布和更新的数字签名

代码实现示例

JavaScript (Node.js + crypto)
const crypto = require('crypto');

// RSA 非对称加密示例
class AsymmetricCrypto {
  constructor() {
    this.keySize = 2048; // RSA密钥长度
  }
  
  // 生成RSA密钥对
  generateKeyPair() {
    const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
      modulusLength: this.keySize,
      publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
      },
      privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem'
      }
    });
    
    return { publicKey, privateKey };
  }
  
  // 使用公钥加密
  encrypt(plaintext, publicKey) {
    const buffer = Buffer.from(plaintext, 'utf8');
    const encrypted = crypto.publicEncrypt(publicKey, buffer);
    return encrypted.toString('base64');
  }
  
  // 使用私钥解密
  decrypt(encryptedData, privateKey) {
    const buffer = Buffer.from(encryptedData, 'base64');
    const decrypted = crypto.privateDecrypt(privateKey, buffer);
    return decrypted.toString('utf8');
  }
  
  // 使用私钥签名
  sign(data, privateKey) {
    const sign = crypto.createSign('SHA256');
    sign.update(data);
    sign.end();
    return sign.sign(privateKey, 'base64');
  }
  
  // 使用公钥验证签名
  verify(data, signature, publicKey) {
    const verify = crypto.createVerify('SHA256');
    verify.update(data);
    verify.end();
    return verify.verify(publicKey, signature, 'base64');
  }
}

// 使用示例
const cryptoInstance = new AsymmetricCrypto();
const { publicKey, privateKey } = cryptoInstance.generateKeyPair();

const plaintext = "Hello, RSA!";

// 加密
const encrypted = cryptoInstance.encrypt(plaintext, publicKey);
console.log('加密结果:', encrypted);

// 解密
const decrypted = cryptoInstance.decrypt(encrypted, privateKey);
console.log('解密结果:', decrypted);

// 签名
const signature = cryptoInstance.sign(plaintext, privateKey);
console.log('数字签名:', signature);

// 验证签名
const isValid = cryptoInstance.verify(plaintext, signature, publicKey);
console.log('签名验证:', isValid);
Python (cryptography库)
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.backends import default_backend
import base64

class AsymmetricCrypto:
    def __init__(self):
        self.key_size = 2048  # RSA密钥长度
        self.backend = default_backend()
    
    def generate_key_pair(self):
        """生成RSA密钥对"""
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=self.key_size,
            backend=self.backend
        )
        public_key = private_key.public_key()
        
        # 序列化密钥为PEM格式
        private_pem = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        )
        
        public_pem = public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
        
        return private_pem.decode(), public_pem.decode()
    
    def encrypt(self, plaintext, public_key_pem):
        """使用公钥加密"""
        public_key = serialization.load_pem_public_key(
            public_key_pem.encode(),
            backend=self.backend
        )
        
        ciphertext = public_key.encrypt(
            plaintext.encode(),
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )
        
        return base64.b64encode(ciphertext).decode()
    
    def decrypt(self, ciphertext_b64, private_key_pem):
        """使用私钥解密"""
        private_key = serialization.load_pem_private_key(
            private_key_pem.encode(),
            password=None,
            backend=self.backend
        )
        
        ciphertext = base64.b64decode(ciphertext_b64)
        plaintext = private_key.decrypt(
            ciphertext,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )
        
        return plaintext.decode()
    
    def sign(self, message, private_key_pem):
        """使用私钥签名"""
        private_key = serialization.load_pem_private_key(
            private_key_pem.encode(),
            password=None,
            backend=self.backend
        )
        
        signature = private_key.sign(
            message.encode(),
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA256()),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            hashes.SHA256()
        )
        
        return base64.b64encode(signature).decode()
    
    def verify(self, message, signature_b64, public_key_pem):
        """使用公钥验证签名"""
        public_key = serialization.load_pem_public_key(
            public_key_pem.encode(),
            backend=self.backend
        )
        
        signature = base64.b64decode(signature_b64)
        try:
            public_key.verify(
                signature,
                message.encode(),
                padding.PSS(
                    mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH
                ),
                hashes.SHA256()
            )
            return True
        except Exception:
            return False

# 使用示例
crypto_instance = AsymmetricCrypto()
private_key, public_key = crypto_instance.generate_key_pair()

message = "Hello, RSA!"

# 加密
encrypted = crypto_instance.encrypt(message, public_key)
print(f"加密结果: {encrypted}")

# 解密
decrypted = crypto_instance.decrypt(encrypted, private_key)
print(f"解密结果: {decrypted}")

# 签名
signature = crypto_instance.sign(message, private_key)
print(f"数字签名: {signature}")

# 验证签名
is_valid = crypto_instance.verify(message, signature, public_key)
print(f"签名验证: {is_valid}")
Java (javax.crypto)
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class AsymmetricCrypto {
    private static final int KEY_SIZE = 2048;
    private static final String ALGORITHM = "RSA";
    private static final String TRANSFORMATION = "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING";
    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
    
    public static class KeyPair {
        public final String publicKey;
        public final String privateKey;
        
        public KeyPair(String publicKey, String privateKey) {
            this.publicKey = publicKey;
            this.privateKey = privateKey;
        }
    }
    
    /**
     * 生成RSA密钥对
     */
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE);
        java.security.KeyPair keyPair = keyPairGenerator.generateKeyPair();
        
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        
        String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        
        return new KeyPair(publicKeyStr, privateKeyStr);
    }
    
    /**
     * 使用公钥加密
     */
    public static String encrypt(String plaintext, String publicKeyStr) throws Exception {
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(spec);
        
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
    
    /**
     * 使用私钥解密
     */
    public static String decrypt(String ciphertext, String privateKeyStr) throws Exception {
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(spec);
        
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        
        byte[] ciphertextBytes = Base64.getDecoder().decode(ciphertext);
        byte[] decryptedBytes = cipher.doFinal(ciphertextBytes);
        return new String(decryptedBytes, "UTF-8");
    }
    
    /**
     * 使用私钥签名
     */
    public static String sign(String message, String privateKeyStr) throws Exception {
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(spec);
        
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateKey);
        signature.update(message.getBytes("UTF-8"));
        
        byte[] signatureBytes = signature.sign();
        return Base64.getEncoder().encodeToString(signatureBytes);
    }
    
    /**
     * 使用公钥验证签名
     */
    public static boolean verify(String message, String signatureStr, String publicKeyStr) 
            throws Exception {
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(spec);
        
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicKey);
        signature.update(message.getBytes("UTF-8"));
        
        byte[] signatureBytes = Base64.getDecoder().decode(signatureStr);
        return signature.verify(signatureBytes);
    }
    
    // 使用示例
    public static void main(String[] args) {
        try {
            AsymmetricCrypto crypto = new AsymmetricCrypto();
            KeyPair keyPair = crypto.generateKeyPair();
            
            String message = "Hello, RSA!";
            
            // 加密
            String encrypted = crypto.encrypt(message, keyPair.publicKey);
            System.out.println("加密结果: " + encrypted);
            
            // 解密
            String decrypted = crypto.decrypt(encrypted, keyPair.privateKey);
            System.out.println("解密结果: " + decrypted);
            
            // 签名
            String signatureStr = crypto.sign(message, keyPair.privateKey);
            System.out.println("数字签名: " + signatureStr);
            
            // 验证签名
            boolean isValid = crypto.verify(message, signatureStr, keyPair.publicKey);
            System.out.println("签名验证: " + isValid);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}