| | |
| | | /** |
| | | * RSA加密 |
| | | * |
| | | * @param data 待加密数据 |
| | | * @param key 密钥 |
| | | * @param bodyJson 待加密数据 |
| | | * @return |
| | | */ |
| | | public static String encrypt(String data, Key key) throws Exception { |
| | | public static String encrypt(String bodyJson) throws Exception { |
| | | Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); |
| | | cipher.init(Cipher.ENCRYPT_MODE, key); |
| | | int inputLen = data.getBytes().length; |
| | | cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(PUBLIC_KEY)); |
| | | JSONObject object = new JSONObject(); |
| | | object.put("body",bodyJson); |
| | | object.put("sign",sign(bodyJson,RSAUtils.getPrivateKey(PRIVATE_KEY))); |
| | | String json = object.toString(); |
| | | int inputLen = json.getBytes().length; |
| | | ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| | | int offset = 0; |
| | | byte[] cache; |
| | |
| | | // 对数据分段加密 |
| | | while (inputLen - offset > 0) { |
| | | if (inputLen - offset > MAX_ENCRYPT_BLOCK) { |
| | | cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK); |
| | | cache = cipher.doFinal(json.getBytes(), offset, MAX_ENCRYPT_BLOCK); |
| | | } else { |
| | | cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset); |
| | | cache = cipher.doFinal(json.getBytes(), offset, inputLen - offset); |
| | | } |
| | | out.write(cache, 0, cache.length); |
| | | i++; |
| | |
| | | return decryptVerify(jsonBody.getString(key)); |
| | | } |
| | | public static String decryptVerify(String body) throws Exception{ |
| | | String decrypted = RSAUtils.decrypt(body, RSAUtils.getPrivateKey(RSAUtils.PRIVATE_KEY)); |
| | | String decrypted = RSAUtils.decrypt(body, getPrivateKey(RSAUtils.PRIVATE_KEY)); |
| | | JSONObject json = new JSONObject(decrypted); |
| | | //服务端公钥验证加签是否正确 |
| | | String decryptBody = json.getString("body"); |