· 9 years ago · Feb 03, 2017, 05:00 PM
1 @SuppressWarnings("unused")
2 class PaymentJSRequest implements Serializable {
3 private static final long serialVersionUID = -5700536203930375150L;
4 private final String clientId;
5 private final String merchantId;
6 private final String merchantKey;
7 private final String requestType;
8 private final String orderNumber;
9 private final String amount;
10 private final transient IvParameterSpec iv;
11 private final String salt;
12
13 public PaymentJSRequest(String amount, String orderNumber) throws NoSuchAlgorithmException {
14 clientId = configuration.getSagepayApplicationId();
15 merchantId = configuration.getSagepayMerchantId();
16 merchantKey = configuration.getSagepayMerchantKey();
17 requestType = "payment";
18 this.orderNumber = orderNumber;
19 this.amount = amount;
20 SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
21 byte[] ivBytes = new byte[16];
22 random.nextBytes(ivBytes);
23 iv = new IvParameterSpec(ivBytes);
24 salt = Base64.encodeBase64String(Hex.encodeHexString(iv.getIV()).getBytes());
25 }
26
27 public String toAuthKey() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {
28 KeySpec keySpec = new PBEKeySpec(merchantKey.toCharArray(), salt.getBytes(), 1500, 32 * Byte.SIZE);
29 SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
30 SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
31 Key aesKey = new SecretKeySpec(secretKey.getEncoded(), "AES");
32 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
33 cipher.init(Cipher.ENCRYPT_MODE, aesKey, iv);
34 String jsonString = new Gson().toJson(this);
35 return Base64.encodeBase64String(cipher.doFinal(jsonString.getBytes()));
36 }
37
38 public String getSalt() {
39 return salt;
40 }
41 }