|
| 1 | +package example; |
| 2 | + |
| 3 | +import java.io.FileInputStream; |
| 4 | +import java.security.InvalidKeyException; |
| 5 | +import java.security.KeyFactory; |
| 6 | +import java.security.NoSuchAlgorithmException; |
| 7 | +import java.security.PublicKey; |
| 8 | +import java.security.Signature; |
| 9 | +import java.security.SignatureException; |
| 10 | +import java.security.spec.X509EncodedKeySpec; |
| 11 | + |
| 12 | +import org.apache.commons.codec.binary.Base64; |
| 13 | + |
| 14 | +/** |
| 15 | + * Created by sunkai on 15/5/19. webhooks 验证签名示例 |
| 16 | + */ |
| 17 | +public class WebHooksVerifyExample { |
| 18 | + private static String filePath = "src/my-server.pub"; |
| 19 | + private static String eventPath = "src/charge"; |
| 20 | + private static String signPath = "src/sign"; |
| 21 | + |
| 22 | + public static void main(String[] args) throws Exception { |
| 23 | + |
| 24 | + boolean result = verifyData(getByteFromFile(eventPath, false), getByteFromFile(signPath, true), getPubKey()); |
| 25 | + System.out.println("验签结果:"+result); |
| 26 | + } |
| 27 | + |
| 28 | + public static byte[] getByteFromFile(String file, boolean base64) throws Exception { |
| 29 | + FileInputStream in = new FileInputStream(file); |
| 30 | + byte[] fileBytes = new byte[in.available()]; |
| 31 | + in.read(fileBytes); |
| 32 | + in.close(); |
| 33 | + String pubKey = new String(fileBytes, "UTF-8"); |
| 34 | + if (base64) { |
| 35 | + fileBytes = Base64.decodeBase64(pubKey); |
| 36 | + } |
| 37 | + return fileBytes; |
| 38 | + } |
| 39 | + |
| 40 | + public static PublicKey getPubKey() throws Exception { |
| 41 | + // read key bytes |
| 42 | + FileInputStream in = new FileInputStream(filePath); |
| 43 | + byte[] keyBytes = new byte[in.available()]; |
| 44 | + in.read(keyBytes); |
| 45 | + in.close(); |
| 46 | + |
| 47 | + String pubKey = new String(keyBytes, "UTF-8"); |
| 48 | + pubKey = pubKey.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", ""); |
| 49 | + |
| 50 | + keyBytes = Base64.decodeBase64(pubKey); |
| 51 | + |
| 52 | + // generate public key |
| 53 | + X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); |
| 54 | + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); |
| 55 | + PublicKey publicKey = keyFactory.generatePublic(spec); |
| 56 | + return publicKey; |
| 57 | + } |
| 58 | + |
| 59 | + public static boolean verifyData(byte[] data, byte[] sigBytes, PublicKey publicKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { |
| 60 | + Signature signature = Signature.getInstance("SHA256withRSA"); |
| 61 | + signature.initVerify(publicKey); |
| 62 | + signature.update(data); |
| 63 | + return signature.verify(sigBytes); |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments