Notification Verification Examples

The following are code examples for how to use the public key to verify the notifications you receive from the Samsung In-App Purchase (IAP) Instant Server Notification (ISN) service.

Java

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

public void verifyJwt() throws Exception {
	String publicKeyPem = new String(Files.readAllBytes(Paths.get("./publicKey.pem")), StandardCharsets.UTF_8);

	String receivedJwt = "RECEIVED_INSTANT_SERVER_NOTIFICATION";

	Jws<Claims> jws = Jwts.parser()
			.verifyWith(getPublicKeyFromPem(publicKeyPem))
			.build()
			.parseSignedClaims(receivedJwt);

	Claims payload = jws.getPayload();
	System.out.println(payload);
}

private RSAPublicKey getPublicKeyFromPem(String publicKeyPem) throws Exception {
	byte [] encoded = Base64.decodeBase64(publicKeyPem
			.replace("-----BEGIN PUBLIC KEY-----", "")
			.replace("-----END PUBLIC KEY-----", "")
			.replaceAll("\\s", "")
			.getBytes(StandardCharsets.UTF_8));
	X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encoded);
	return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec);
}

Javascript

const jwt = require('jsonwebtoken');
const fs = require("fs");

const publicKey = fs.readFileSync("./publicKey.pem", { encoding: "utf8" });

const receivedJwt = 'RECEIVED_INSTANT_SERVER_NOTIFICATION';

const verifyToken = jwt.verify(receivedJwt, publicKey);
console.log(verifyToken);

Python

import jwt
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization

with open('./publicKey.pem', 'r') as pem_file:
    public_key_pem = pem_file.read().encode('UTF-8')
    public_key = serialization.load_pem_public_key(public_key_pem, backend=default_backend())

received_jwt = b'RECEIVED_INSTANT_SERVER_NOTIFICATION'

try:
    decoded_payload = jwt.decode(jwt=received_jwt, key=public_key, algorithms=['RS256'], options= {'verify_aud' : False})
    print ("Decoded verified payload:", decoded_payload)
except jwt.InvalidTokenError as e:
    print ("Invalid token : " +  str(e))
except Exception as e:
    print ("Exception : " +  str(e))