|
| 1 | +/** |
| 2 | + * Copyright (c) 2017 by CyberSource |
| 3 | + * Governing licence: https://github.com/CyberSource/cybersource-flex-samples/blob/master/LICENSE.md |
| 4 | + */ |
| 5 | +package com.cybersource.example; |
| 6 | + |
| 7 | +import java.io.BufferedReader; |
| 8 | +import javax.servlet.http.HttpSession; |
| 9 | +import java.io.IOException; |
| 10 | +import java.io.InputStream; |
| 11 | +import java.io.InputStreamReader; |
| 12 | +import java.io.OutputStreamWriter; |
| 13 | +import java.net.HttpURLConnection; |
| 14 | +import java.net.URL; |
| 15 | +import java.nio.charset.StandardCharsets; |
| 16 | +import java.security.KeyFactory; |
| 17 | +import java.security.MessageDigest; |
| 18 | +import java.security.NoSuchAlgorithmException; |
| 19 | +import java.security.PublicKey; |
| 20 | +import java.security.Signature; |
| 21 | +import java.security.spec.X509EncodedKeySpec; |
| 22 | +import java.text.SimpleDateFormat; |
| 23 | +import java.util.Calendar; |
| 24 | +import java.util.LinkedHashMap; |
| 25 | +import java.util.Locale; |
| 26 | +import java.util.Map; |
| 27 | +import java.util.TimeZone; |
| 28 | +import javax.crypto.Mac; |
| 29 | +import javax.crypto.spec.SecretKeySpec; |
| 30 | +import org.apache.commons.codec.binary.Base64; |
| 31 | +import org.json.JSONObject; |
| 32 | + |
| 33 | +public class FlexKeyProvider { |
| 34 | + |
| 35 | + private static final String HOST = "testflex.cybersource.com"; |
| 36 | + private final MerchantCredentials merchantCredentials; |
| 37 | + |
| 38 | + FlexKeyProvider(InputStream resource) { |
| 39 | + try { |
| 40 | + merchantCredentials = new MerchantCredentials(resource); |
| 41 | + } catch (IOException e) { |
| 42 | + throw new RuntimeException(e); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public String bindFlexKeyToSession(HttpSession session) { |
| 47 | + try { |
| 48 | + final JSONObject request = new JSONObject(); |
| 49 | + request.put("encryptionType", "RsaOaep256"); |
| 50 | + request.put("targetOrigin", "http://localhost:8080"); // the origin of web page that renders flex microform iframe. |
| 51 | + final String body = request.toString(); |
| 52 | + final String date = getServerTime(); |
| 53 | + |
| 54 | + final Map<String, String> signedHeaders = new LinkedHashMap<String, String>(); |
| 55 | + signedHeaders.put("host", HOST); |
| 56 | + signedHeaders.put("date", date); |
| 57 | + signedHeaders.put("(request-target)", "post /flex/v1/keys"); |
| 58 | + signedHeaders.put("digest", getDigest(body)); |
| 59 | + signedHeaders.put("v-c-merchant-id", merchantCredentials.getMerchantId()); |
| 60 | + |
| 61 | + final String signature = generateSignature(signedHeaders, merchantCredentials.getKeyId(), merchantCredentials.getSharedSecret()); |
| 62 | + signedHeaders.put("signature", signature); |
| 63 | + signedHeaders.remove("(request-target)"); |
| 64 | + |
| 65 | + String response = post(signedHeaders, body); |
| 66 | + JSONObject flexPublicKey = new JSONObject(response); |
| 67 | + session.setAttribute("flexPublicKey", flexPublicKey); |
| 68 | + |
| 69 | + return flexPublicKey.getJSONObject("jwk").toString(); |
| 70 | + } catch (IOException ioe) { |
| 71 | + throw new RuntimeException("Error receiving Flex public key", ioe); |
| 72 | + } |
| 73 | + |
| 74 | + } |
| 75 | + |
| 76 | + public boolean verifyTokenResponse(HttpSession session, String flexResponse) { |
| 77 | + try { |
| 78 | + JSONObject flexPublicKey = (JSONObject) session.getAttribute("flexPublicKey"); |
| 79 | + byte[] keyBytes = Base64.decodeBase64(flexPublicKey.getJSONObject("der").getString("publicKey")); |
| 80 | + PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(keyBytes)); |
| 81 | + |
| 82 | + JSONObject token = new JSONObject(flexResponse); |
| 83 | + |
| 84 | + String[] signedFieldKeys = token.getString("signedFields").split(","); |
| 85 | + StringBuilder signedValues = new StringBuilder(); |
| 86 | + for (String key : signedFieldKeys) { |
| 87 | + signedValues.append(",").append(token.get(key).toString()); |
| 88 | + } |
| 89 | + signedValues.deleteCharAt(0); |
| 90 | + |
| 91 | + final Signature signInstance = Signature.getInstance("SHA512withRSA"); |
| 92 | + signInstance.initVerify(publicKey); |
| 93 | + signInstance.update(signedValues.toString().getBytes()); |
| 94 | + return signInstance.verify(Base64.decodeBase64(token.getString("signature"))); |
| 95 | + } catch (Exception e) { |
| 96 | + return false; |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + private static String getServerTime() { |
| 101 | + Calendar calendar = Calendar.getInstance(); |
| 102 | + SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); |
| 103 | + dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); |
| 104 | + return dateFormat.format(calendar.getTime()); |
| 105 | + } |
| 106 | + |
| 107 | + private static String getDigest(String body) { |
| 108 | + try { |
| 109 | + final MessageDigest digester = MessageDigest.getInstance("SHA-256"); |
| 110 | + final byte[] digest = digester.digest(body.getBytes(StandardCharsets.UTF_8)); |
| 111 | + return String.format("SHA-256=%s", Base64.encodeBase64String(digest)); |
| 112 | + } catch (NoSuchAlgorithmException nsae) { |
| 113 | + throw new IllegalStateException(nsae); // never thrown unless SHA-256 is not provided. |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + public static String generateSignature(Map<String, String> headers, final String keyId, final byte[] sharedSecret) { |
| 118 | + try { |
| 119 | + final Mac sha256HMAC = Mac.getInstance("HmacSHA256"); |
| 120 | + final SecretKeySpec secretKey = new SecretKeySpec(Base64.decodeBase64(sharedSecret), "HmacSHA256"); |
| 121 | + sha256HMAC.init(secretKey); |
| 122 | + |
| 123 | + final StringBuilder signatureString = new StringBuilder(); |
| 124 | + final StringBuilder headersString = new StringBuilder(); |
| 125 | + |
| 126 | + for (Map.Entry<String, String> e : headers.entrySet()) { |
| 127 | + signatureString.append('\n').append(e.getKey()).append(": ").append(e.getValue()); |
| 128 | + headersString.append(' ').append(e.getKey()); |
| 129 | + } |
| 130 | + signatureString.delete(0, 1); |
| 131 | + headersString.delete(0, 1); |
| 132 | + |
| 133 | + final StringBuilder signature = new StringBuilder(); |
| 134 | + sha256HMAC.update(signatureString.toString().getBytes(StandardCharsets.UTF_8)); |
| 135 | + final byte[] hashBytes = sha256HMAC.doFinal(); |
| 136 | + |
| 137 | + signature.append("keyid=\"").append(keyId).append("\", ") |
| 138 | + .append("algorithm=\"HmacSHA256\", ") |
| 139 | + .append("headers=\"").append(headersString).append("\", ") |
| 140 | + .append("signature=\"").append(Base64.encodeBase64String(hashBytes)).append('\"'); |
| 141 | + |
| 142 | + return signature.toString(); |
| 143 | + } catch (Exception e) { |
| 144 | + throw new RuntimeException(e); |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + public static String post(Map<String, String> headers, String payload) throws IOException { |
| 149 | + HttpURLConnection connection = (HttpURLConnection) new URL("https://testflex.cybersource.com/flex/v1/keys").openConnection(); |
| 150 | + connection.setRequestMethod("POST"); |
| 151 | + connection.setDoOutput(true); |
| 152 | + connection.setConnectTimeout(5000); |
| 153 | + connection.setReadTimeout(5000); |
| 154 | + |
| 155 | + // HEADERS |
| 156 | + connection.setRequestProperty("Accept", "application/json; charset=utf-8"); |
| 157 | + connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); |
| 158 | + connection.setRequestProperty("User-Agent", "URLConnection Java JSP GitHub Example"); |
| 159 | + for (Map.Entry<String, String> header : headers.entrySet()) { |
| 160 | + connection.setRequestProperty(header.getKey(), header.getValue()); |
| 161 | + } |
| 162 | + |
| 163 | + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8); |
| 164 | + try { |
| 165 | + out.write(payload); |
| 166 | + } finally { |
| 167 | + out.close(); |
| 168 | + } |
| 169 | + |
| 170 | + StringBuilder result = new StringBuilder(); |
| 171 | + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)); |
| 172 | + try { |
| 173 | + final char[] buffer = new char[4096]; |
| 174 | + int bytesRead; |
| 175 | + |
| 176 | + while ((bytesRead = reader.read(buffer)) != -1) { |
| 177 | + result.append(buffer, 0, bytesRead); |
| 178 | + } |
| 179 | + } finally { |
| 180 | + reader.close(); |
| 181 | + } |
| 182 | + return result.toString(); |
| 183 | + } |
| 184 | +} |
0 commit comments