RSA加密/解密

less than 1 minute read

RSA加密/解密

public static void main(String[] args) throws Exception {
    // 获取私钥
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    // 获取公钥
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    // 待签名数据
    String data = "e160189b8467499c0579797300e17adcc07783ea918487321ac9f35a25176611";

    // 创建消息摘要
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] hash = digest.digest(data.getBytes(StandardCharsets.UTF_8));

    // 使用私钥签名
    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initSign(privateKey);
    signature.update(hash);
    byte[] signedData = signature.sign();

    // Base64编码签名结果
    String base64Signature = Base64.getEncoder().encodeToString(signedData);
    System.out.println(base64Signature);
    // ... (将签名结果传输给验证方)

    // 验证签名
    Signature verifySignature = Signature.getInstance("SHA256withRSA");
    verifySignature.initVerify(publicKey);
    verifySignature.update(hash);
    boolean verified = verifySignature.verify(signedData);

    System.out.println("签名验证结果:" + verified);
}

Comments