当前位置:网站首页>Encryption, decryption and signature verification

Encryption, decryption and signature verification

2022-06-10 00:24:00 Feifei can't fly

Encryption, decryption and signature verification

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.0</version>
</dependency>
public class EncodeSign {
    
    public static void main(String[] args) {
    
        //  Generate key pair 
        KeyPair rsa = SecureUtil.generateKeyPair("RSA");
        PrivateKey privateKey = rsa.getPrivate();
        PublicKey publicKey = rsa.getPublic();

        //  Data transmitted 
        String data = "{\"result\": \"SUCCESS\"}";

        //  Set the signature algorithm and the private key of the signature 
        Sign signOne = SecureUtil.sign(SignAlgorithm.MD5withRSA);
        signOne.setPrivateKey(privateKey);

        //  Signature 
        byte[] signData = signOne.sign(data.getBytes(StandardCharsets.UTF_8));

        //  Will sign the result Base64 Encrypted into string transmission 
        String signDataStr = Base64.encode(signData);
        System.out.println("signDataStr = " + signDataStr);

        RSA rsaForDataEncode = new RSA();
        rsaForDataEncode.setPrivateKey(privateKey);
        byte[] encrypt = rsaForDataEncode.encrypt(data.getBytes(StandardCharsets.UTF_8), KeyType.PrivateKey);
        String encodeData = Base64.encode(encrypt);
        System.out.println(encodeData);



        //  attestation 
        Sign signTwo = SecureUtil.sign(SignAlgorithm.MD5withRSA);
        //  Set the signature algorithm and the public key of the signature 
        signTwo.setPublicKey(publicKey);
        //  Restore signature as byte Array 
        byte[] signDataOrigin = Base64.decode(signDataStr);
        boolean verify = signTwo.verify(data.getBytes(StandardCharsets.UTF_8), signDataOrigin);
        System.out.println(verify);

        //  Decrypt 
        RSA rsaForDataDecode = new RSA();
        rsaForDataDecode.setPublicKey(publicKey);
        byte[] decodeData = Base64.decode(encodeData);
        byte[] decrypt = rsaForDataDecode.decrypt(decodeData, KeyType.PublicKey);
        String dataOrgin = new String(decrypt, StandardCharsets.UTF_8);
        System.out.println("dataOrgin = " + dataOrgin);


    }
}

原网站

版权声明
本文为[Feifei can't fly]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206092348033251.html