public class EncryptionAndSignatureExample {
public static void main(String[] args) throws Exception {
// 生成公私钥对
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
System.out.println("公钥:" + publicKey);
System.out.println("私钥:" + privateKey);
// 私钥加密、公钥验签示例
String message = "Test message for signature";
byte[] signature = sign(privateKey, message);
boolean isVerified = verify(publicKey, message, signature);
System.out.println("私钥加密、公钥验签结果: " + isVerified);
// 公钥加密、私钥解密示例
String encryptedMessage = encrypt(publicKey, "Secret message");
String decryptedMessage = decrypt(privateKey, encryptedMessage);
System.out.println("公钥加密、私钥解密后的消息: " + decryptedMessage);
}
public static byte[] sign(PrivateKey privateKey, String message) throws Exception {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(message.getBytes());
return signature.sign();
}
public static boolean verify(PublicKey publicKey, String message, byte[] signature) throws Exception {
Signature verification = Signature.getInstance("SHA256withRSA");
verification.initVerify(publicKey);
verification.update(message.getBytes());
return verification.verify(signature);
}
public static String encrypt(PublicKey publicKey, String message) throws Exception {
// 这里简单模拟加密,实际应用中需使用更完善的加密逻辑
return message + "_encrypted";
}
public static String decrypt(PrivateKey privateKey, String encryptedMessage) throws Exception {
// 这里简单模拟解密,实际应用中需使用更完善的解密逻辑
return encryptedMessage.replace("_encrypted", "");
}
}