在当今数字化的时代,数据的安全性成为至关重要的问题。Java语言提供了丰富的加密库,使得各种加密技术可以轻松应用于实际开发中。本文将深入探讨Java中对称加密、非对称加密、哈希函数以及混合加密的实现方式,并通过简单的示例演示其基本用法。
对称加密使用相同的密钥进行加密和解密,是处理大量数据时的理想选择。Java中,我们可以使用Cipher类实现AES对称加密。
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
public class SymmetricEncryptionExample {
public static void main(String[] args) throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey secretKey = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES");
// 加密
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal("Hello, Symmetric Encryption!".getBytes());
String encryptedBase64 = Base64.getEncoder().encodeToString(encryptedData);
System.out.println("Encrypted: " + encryptedBase64);
// 解密
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedBase64));
System.out.println("Decrypted: " + new String(decryptedData));
}
}
非对称加密使用一对密钥,公钥和私钥,分别用于加密和解密。在Java中,我们可以使用KeyPairGenerator和Cipher类实现RSA非对称加密。
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import java.util.Base64;
public class AsymmetricEncryptionExample {
public static void main(String[] args) throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
Cipher cipher = Cipher.getInstance("RSA");
// 加密
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal("Hello, Asymmetric Encryption!".getBytes());
String encryptedBase64 = Base64.getEncoder().encodeToString(encryptedData);
System.out.println("Encrypted: " + encryptedBase64);
// 解密
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedBase64));
System.out.println("Decrypted: " + new String(decryptedData));
}
}
国密sm2
public class SM2EncryptionDecryptionExample {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
// Generate SM2 key pair
AsymmetricCipherKeyPair keyPair = generateSM2KeyPair();
ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate();
ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic();
String plainText = "Hello, SM2!";
byte[] encryptedData = encryptSM2(plainText.getBytes(), publicKey);
byte[] decryptedData = decryptSM2(encryptedData, privateKey);
System.out.println("Original Text: " + plainText);
System.out.println("Encrypted Data: " + Hex.toHexString(encryptedData));
System.out.println("Decrypted Text: " + new String(decryptedData));
}
// Generate SM2 key pair
public static AsymmetricCipherKeyPair generateSM2KeyPair() throws NoSuchAlgorithmException {
ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("sm2p256v1");
ECDomainParameters ecParams = new ECDomainParameters(
ecSpec.getCurve(), ecSpec.getG(), ecSpec.getN(), ecSpec.getH());
ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(ecParams, SecureRandom.getInstance("SHA1PRNG"));
ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
keyPairGenerator.init(keyGenParams);
return keyPairGenerator.generateKeyPair();
}
// Encrypt using SM2
public static byte[] encryptSM2(byte[] data, ECPublicKeyParameters publicKey) throws Exception {
SM2Engine engine = new SM2Engine();
engine.init(true, new ParametersWithRandom(publicKey, new SecureRandom()));
return engine.processBlock(data, 0, data.length);
}
// Decrypt using SM2
public static byte[] decryptSM2(byte[] data, ECPrivateKeyParameters privateKey) throws Exception {
SM2Engine engine = new SM2Engine();
engine.init(false, privateKey);
return engine.processBlock(data, 0, data.length);
}
public static byte[] encryptSM2X(byte[] data, ECPrivateKeyParameters publicKey) throws Exception {
SM2Engine engine = new SM2Engine();
engine.init(false, publicKey);
return engine.processBlock(data, 0, data.length);
}
// Decrypt using SM2
public static byte[] decryptSM2X(byte[] data, ECPublicKeyParameters privateKey) throws Exception {
SM2Engine engine = new SM2Engine();
engine.init(true, privateKey);
return engine.processBlock(data, 0, data.length);
}
}
哈希函数用于生成数据的固定长度摘要,通常用于密码存储和数据完整性验证。在Java中,我们可以使用MessageDigest类实现哈希函数。
import java.security.MessageDigest;
import java.util.Base64;
public class HashFunctionExample {
public static void main(String[] args) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// 计算哈希值
byte[] hashedData = digest.digest("Hello, Hash Function!".getBytes());
String hashedBase64 = Base64.getEncoder().encodeToString(hashedData);
System.out.println("Hashed: " + hashedBase64);
}
}
混合加密结合对称和非对称加密,以实现更强大的安全性。在实际应用中,可能涉及更复杂的协议和流程。
以上示例提供了基本的加密操作,实际应用中需要根据具体场景和需求进行更详细的配置和处理。在开发中,务必注意密钥的安全存储和传输,以确保整个加密系统的健壮性。通过理解和合理应用这些加密技术,我们可以为Java应用程序建立强大的数字安全堡垒。