Sample Codes of Encryption
This document provides sample codes for encrypting credit card information using Java functions and JavaScript files, including `encryptText`, `HPM2Security.js`, and `RsaEncrypter.encrypt`.
Option 1: The following sample code uses the encryptText Java function and HPM2Security.js to encrypt credit card information directly on the web page.
The HPM2Security.js file can be loaded on your web page from the websites with the URLs in the <Zuora_Data_Center_URL>/apps/Hosted/lite2/js/HPM2Security.js format, such as https://sandbox.na.zuora.com/apps/Hosted/lite2/js/HPM2Security.js .
Some open source libraries are referenced by HPM2Security.js . Zuora does not maintain these open source libraries thus cannot guarantee they work correctly with your system.
function buildEncryptedValues(...) {
// 1) Construct credit card data to a string in the desired format
var unencrypted_values = "#" + creditCardNumber + "#" +
cardSecurityCode + "#" + creditCardExpirationMonth + "#" +
creditCardExpirationYear;
// 2) Base64 encode the string, 3) Encrypt the Base64 string
// and 4) Base64 encode the encrypted data
return encryptText(unencrypted_values, publicKey);
}
/**
* encrypt the text using the specified public key.
* @param text the text to be encrypted.
* @param key the public key.
* @returns Base64 encoded encrypted data.
*/
function encryptText(text, key) {
if (key) {
try {
var key = pidCryptUtil.decodeBase64(key);
var rsa = new pidCrypt.RSA();
//ASN1 parsing
var asn = pidCrypt.ASN1.decode(pidCryptUtil.toByteArray(key));
var tree = asn.toHexTree();
//setting the public key for encryption with retrieved ASN.1 tree
rsa.setPublicKeyFromASN(tree);
// Base64 encode and encrypt the string
var crypted = rsa.encrypt(text);
return pidCryptUtil.encodeBase64(pidCryptUtil.convertFromHex(crypted));
} catch(e) {
console.info(e);
}
}
// return origin text if unable to encrypt
return text;
}
Option 2: The following sample code uses the RsaEncrypter.encrypt Java function to encrypt credit card information on a Java backend. The code below depends on several libraries. You can find those libraries in the Payment Pages 2.0 sample code suite on Zuora GitHub site.
import com.zuora.rsa.security.encrypt.RsaEncrypter;
import org.apache.commons.codec.binary.Base64;
public class HPMUtils {
public static String buildEncryptedValues(...) {
// 1) Construct the credit card data to a string in the desired format
String unencrypted_values = "#" + creditCardNumber + "#" +
cardSecurityCode + "#" + creditCardExpirationMonth + "#" +
creditCardExpirationYear;
// 2) Base64 encode the string
String base64Data = new String(Base64.encodeBase64(unencrypted_values.getBytes()));
// 3) Encrypt the Base64 data and 4) Base64 encode the encrypted data
return RsaEncrypter.encrypt(base64Data, publicKey);
}
}