针对数据进行签名、签名验证

        String privateKey = "1234567";
        String publicKey = "123";

        //使用私钥进行签名
        byte[] byteKey = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(byteKey);
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec);
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(privateKey);
        sign.update("{\"1\":\"2\"}".getBytes());
        byte[] signed = sign.sign();
        String key = Base64.encodeBase64String(signed);
        System.out.println(key);

        //使用公钥进行签名验证
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(keySpec);
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initVerify(pubKey);
        signature.update("{\"1\":\"2\"}".getBytes());
        boolean verify = signature.verify(Base64.decodeBase64(key));
        System.out.println(verify);
最后修改:2022 年 04 月 28 日 02 : 03 PM