当前位置:   article > 正文

非对称密钥:应用场景

非对称密钥:应用场景

在这里插入图片描述
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", "");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/667874
推荐阅读
相关标签
  

闽ICP备14008679号