/** * Decrypts TTN data_raw payload to data according to the TTN REST API. * * @param rawText encrypted message payload from ttn mqtt message * @param K the TTN application key * @param IV * @return decrypted payload * @throws Exception */ public static String decrypt(String rawText, byte[] K, byte[] IV) throws Exception { byte[] pld = Base64.getDecoder().decode(rawText); byte[] devAddr = getDevAddr(pld); byte[] frameCounter = getFrameCounter(pld); byte[] result = initializeResult(pld); byte[] Ai = new byte[16]; byte[] Si = null; for (int i = 0; i < result.length; i += 16) { int blockSeqCnt = (i >> 4) + 1; computeAi(Ai, devAddr, frameCounter, blockSeqCnt); Si = encryptAES(Ai, K, IV); for (int j = 0; j < 16 && i + j < result.length; j++) { result[i + j] ^= Si[j]; } } return Base64.getEncoder().encodeToString(result); }