Skip to content

Instantly share code, notes, and snippets.

@emoran
Created March 10, 2022 11:58
Show Gist options
  • Save emoran/1aeeea75b6866c214fc023eb932127c8 to your computer and use it in GitHub Desktop.
Save emoran/1aeeea75b6866c214fc023eb932127c8 to your computer and use it in GitHub Desktop.
Walmart Header Signature snippet. Allows to generate the WM_SEC.AUTH_SIGNATURE header to authenticate in Walmart API services.
import org.apache.commons.codec.binary.Base64;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
public class WalmartHeaderSignature {
private static String consumerId = "CONSUMER_ID"; // Trimmed for security reason
private static String baseUrl = "URL";
/*You need to convert your .pem private key to PK8 format using this command: openssl pkcs8 -topk8 -nocrypt -in key.pem -outform PEM
* you need to paste the text between -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY-----*/
private static String privateEncodedStr = "XXXX";
public static void main(String[] args) {
String httpMethod = "POST";
String privateKeyVersion = "1";
String timestamp = String.valueOf(System.currentTimeMillis());
String stringToSign = consumerId + "\n" + timestamp + "\n" + privateKeyVersion + "\n";
String signedString = WalmartHeaderSignature.signData(stringToSign, privateEncodedStr);
System.out.println("timestamp: "+timestamp+ " Signed String: " + signedString);
}
public static String signData(String stringToBeSigned, String encodedPrivateKey) {
String signatureString = null;
try {
byte[] encodedKeyBytes = Base64.decodeBase64(encodedPrivateKey);
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(encodedKeyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey myPrivateKey = kf.generatePrivate(privSpec);
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(myPrivateKey);
byte[] data = stringToBeSigned.getBytes("UTF-8");
signature.update(data);
byte[] signedBytes = signature.sign();
signatureString = Base64.encodeBase64String(signedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return signatureString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment