在Java中,我们可以使用Java Cryptography Extension (JCE) 来实现加密和解密工具和技术。以下是一些常见的加密和解密技术及其示例代码:
1.使用AES加密和解密
package org.example.Test05;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Base64;
public class AESEncryption {
private static final String ALGORITHM = "AES";
public static String encrypt(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedData, String key) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedBytes);
}
public static void main(String[] args) throws Exception {
String originKey = "zhegeshikey";
byte[] extendedKey = Arrays.copyOf(originKey.getBytes("UTF-8"), 16); // 扩展到16字节
String key = new String(extendedKey, "UTF-8");
String encrypt = encrypt("test测试", key);
System.out.println(encrypt);
String decrypt = decrypt(encrypt, key);
System.out.println(decrypt);
}
}
2. 使用RSA加密和解密
package org.example.Test05;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class RSAEncryption {
private static final String ALGORITHM = "RSA";
public static String encryptWithPublicKey(String data, String publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey))));
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decryptWithPrivateKey(String encryptedData, String privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey))));
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedBytes);
}
public static void generateKeyPair() throws Exception {
try {
// 初始化KeyPairGenerator对象,并设置密钥对的算法
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对的生成,设置密钥大小为2048位
keyPairGenerator.initialize(2048);
// 生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 获取公钥
PublicKey publicKey = keyPair.getPublic();
// 获取私钥
PrivateKey privateKey = keyPair.getPrivate();
// 打印公钥和私钥
System.out.println("Public Key: " + Base64.getEncoder().encodeToString(publicKey.getEncoded()));
System.out.println("Private Key: " + Base64.getEncoder().encodeToString(privateKey.getEncoded()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
//generateKeyPair();
String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjVxl+xGBFVo5Y8UESbtdPk1HmY8M2u6B9OEbTYVmaPu7jOLBrcthEy4twr9zfJ36/wB9DCrnPng6NU1ZICD7fIn4/ni8OwyPaXSsiF3KZGx/KXK2PgMeMq/Bor+4gH4C5OZVZc2+ocdi0lK4mzab593bwibmFBwGmgdt1Rn1c+dEr3pD3t47OnxSMcPjQlqQjWD90bxyOWqZGf0WxNxTMTClgPEzJMbjGKlwMtHGxsxwruXeuwfVZALn1/TdcuF1DwYQOR0Qak4OuYgTIKv5puQIhG/EF68ZiRhEwzj1eOn8bm0ThLXX/wuBdrlSwbXsrFzS60wuWJ19DvmeUYWF+wIDAQAB";
String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKc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1pQbOBW+GMKwGVpg8jhHNKgvQLpAKk+JSHsP+5gCSpU+YjYzxGCs4f9BYhXOlvCyNWKfcG/Rgv/ojaDBT9GkJyV3xlZ3qsC6y+AmiKbDtRXYQOuUaRtLXsFhLyhwgdtH2oezWy8FZiAA/RIF2X2hC+cx5Uw/AoGBAIaieNvRk76zO4EC3colpgu9MXiV4OkUeX5fhemhfVbjgvHWUaCKjkhjt0eHghdRi7A+nPF8cBIUmDrmPBWGGp91q1ONHKfBvkkRHPopliKr63ciZ+Ax7hYF40orv82b03WksYoRab2FTr5Iioa9ojwRaaG7X9Mo9TGTON9nSWJ9AoGAZ7PS5fYkzkFrH13MZEwZZ2bHMCfIrGGuRVmp4H8jNy1jwKKcI8tFTP2szYcKNslRB7CU5RxFL56en+oX8fY44CJITWq1QbQ11l9x4q+FzMw8AT3JOVkNpb9xhJPhEi2ApjSdDdGsRS4a9/EUeQRKjAGaZSBgN7STsEWyFy5EBak=";
String encrypt = encryptWithPublicKey("test测试。。。", publicKey);
System.out.println(encrypt);
String decrypt = decryptWithPrivateKey(encrypt, privateKey);
System.out.println(decrypt);
}
}
3. 使用MessageDigest生成哈希值
package org.example.Test05;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Hashing {
public static String generateSHA256Hash(String data) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data.getBytes());
byte[] digest = md.digest();
return bytesToHex(digest);
}
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println(generateSHA256Hash("123"));
}
}