🔐 Asymmetric Encryption Tool
Generate key pairs, encrypt/decrypt data, and create digital signatures using RSA, ECC, SM2, and other public-key cryptography algorithms
What is Asymmetric Encryption?
Asymmetric encryption, also known as public-key cryptography, uses a pair of mathematically related keys: a public key and a private key. The public key can be freely shared and is used to encrypt data; the private key must be kept secret and is used to decrypt data. This design solves the key distribution problem in symmetric encryption.
Key Features
- Uses public-private key pairs
- Public key can be shared, private key must be secret
- Supports digital signatures for identity verification
- Common algorithms: RSA, ECC, SM2, etc.
Main Use Cases
- HTTPS/TLS website security
- Digital certificates and PKI systems
- Email encryption and digital signatures
- Blockchain and cryptocurrency
Security Note
The security of private keys is crucial. Once compromised, it can lead to serious security issues. It is recommended to use strong random number generators for key generation, properly secure private keys, regularly update key pairs, and consider using Hardware Security Modules (HSM) to protect high-value private keys.
Algorithm Settings
Output
Key Management
Algorithm Details & Implementation Examples
Algorithm Basic Information
Algorithm Characteristics
• RSA algorithm based on large integer factorization mathematical problem
• Supports both encryption/decryption and digital signature operations
• Longer key length provides higher security but lower performance
• Widely used in HTTPS, SSH, email encryption and other scenarios
• Mature and stable, but relatively large key size and lower performance
Use Cases & Examples
HTTPS Certificates
Website SSL/TLS certificate signing and key exchange
SSH Key Authentication
Server remote login public key authentication
Code Signing
Software release and update digital signatures
Code Implementation Examples
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);
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}")
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(); } } }
Ferramentas JSON Relacionadas
Explore mais ferramentas poderosas de processamento JSON
Hash Generator
Description
Symmetric Encryption Tool
Encrypt and decrypt data using symmetric encryption algorithms like AES, SM4, and ChaCha20
Formatador JSON
Formate, embeleze e comprima dados JSON com verificação de sintaxe em tempo real e detecção de erros
Validador JSON
Valide a sintaxe e a estrutura do JSON com relatórios e análises de erros detalhados
Editor JSON
Um poderoso editor JSON online que suporta formatação, embelezamento, validação, compressão, visualizações em árvore/tabela/visual, análise online, exportação CSV/Excel, download e muito mais.
Conversor de JSON para XML
Converta dados JSON para XML bem formatado com mapeamento automático de estrutura e tratamento de tipo