1.import io.netty.util.CharsetUtil;
2.import org.apache.commons.codec.binary.Base64;
3.import javax.crypto.Cipher;
4.import java.nio.charset.StandardCharsets;
5.import java.security.*;
6.import java.security.spec.PKCS8EncodedKeySpec;
7.import java.security.spec.X509EncodedKeySpec;
8.
9.public class Demo {
10.
11. /**
12. * For creating signature for an request
13. *
14. * @param data request data, request body e.g."{\"msgId\":\"999\",\"mchId\":\"1234567\", ....}"
15. * @param priKey the pair of the one (sign pub key) you uploaded, create signed public key uploaded by merchant to correspond the private key
16. * @return signature of the request data, you should set it into "signature" field, check our example on document
17. */
18. public static String signBySHA256WithRSA(String data, String priKey) throws Exception {
19. try {
20. Signature signature = Signature.getInstance("SHA256WithRSA");
21. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKey));
22. PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);
23. signature.initSign(privateKey);
24. signature.update(data.getBytes("UTF-8"));
25. return Base64.encodeBase64String(signature.sign());
26. } catch (Exception e) {
27. throw new Exception("RSA signature creating error");
28. }
29. }
30.
31.
32. /**
33. * For verifying signature for an request / response
34. *
35. * @param data all contents in "response" or "request" field, e.g. "response":{"code":"200","message":"Success", ...}
36. * @param sign all contents in "signature" field
37. * @param pubKey the public signing key provided by Wallyt
38. * @return true if valid,
39. */
40. public static boolean verifyBySHA256WithRSA(String data, String sign, String pubKey) throws Exception {
41. try {
42. Signature signature = Signature.getInstance("SHA256WithRSA");
43. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubKey));
44. PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec);
45. signature.initVerify(publicKey);
46. signature.update(data.getBytes(StandardCharsets.UTF_8));
47. return signature.verify(Base64.decodeBase64(sign.getBytes(StandardCharsets.UTF_8)));
48. } catch (Exception e) {
49. throw new Exception("RSA signature verifying error");
50. }
51. }
52.}