1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| public class TuRingRequestEncrypted { private String secret = Secret.secret; private String apiKey = Secret.apiKey; private String timestamp; private String data;
private String md5Key; private String paramStr;
public TuRingRequestEncrypted(TuRingRequest tuRingRequest) { this.paramStr = JSON.toJSONString(tuRingRequest); this.timestamp = "" + System.currentTimeMillis(); this.md5Key = processKey(secret, timestamp, apiKey); this.data = AES_Encrypted(this.paramStr, md5Key); }
private String AES_Encrypted(String paramStr, String md5Key) { Cipher cipher = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(md5Key.getBytes(StandardCharsets.UTF_8)); byte[] tmp = messageDigest.digest(); Key key = new SecretKeySpec(tmp, "AES"); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); byte[] encryptedData = cipher.doFinal(paramStr.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encryptedData); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); } return null; }
private String processKey(String secret, String timestamp, String apiKey) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); return byte2HexStr(messageDigest.digest((secret + timestamp + apiKey).getBytes(StandardCharsets.UTF_8))); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
private String byte2HexStr(byte[] digest) { String str = "0123456789abcdef"; StringBuilder stringBuilder = new StringBuilder(2 * digest.length); for (int i = 0; i < digest.length; i++) { byte high = (byte) ((byte) 0x0f & (digest[i] >> 4)); stringBuilder.append(str.charAt(high)); byte low = (byte) (digest[i] & 0x0f); stringBuilder.append(str.charAt(low)); } return stringBuilder.toString(); }
public String getTimestamp() { return timestamp; }
public String getData() { return data; }
public String getKey() { return apiKey; } }
|