#StackBounty: #java #python #pbkdf2 #hmacsha1 #hashlib Python equivalent of java PBKDF2WithHmacSHA1

Bounty: 50

I’m tasked with building a consumer of an API that requires an encrypted token with a seed value that is the UNIX time. The example I was shown was implemented using Java which I’m unfamiliar with, and after reading through documentation and other stack articles have been unable to find a solution.

Using the javax.crypto.SecretKey, javax.crypto.SecretKeyFactory, javax.crypto.spec.PBEKeySpec, and javax.crypto.spec.SecretKeySpec protocols, I need to generate a token similar to the below:

public class EncryptionTokenDemo {

public static void main(String args[]) {
    long millis = System.currentTimeMillis();
    String time = String.valueOf(millis);
    String secretKey = "somekeyvalue";
    int iterations = 12345;
    String iters = String.valueOf(iterations);
    String strToEncrypt_acctnum = "somevalue|" + time + "|" + iterations;

    try {

        byte[] input = strToEncrypt_acctnum.toString().getBytes("utf-8");
        byte[] salt = secretKey.getBytes("utf-8");
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        SecretKey tmp = factory.generateSecret(new PBEKeySpec(secretKey.toCharArray(), salt, iterations, 256));
        SecretKeySpec skc = new SecretKeySpec(tmp.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skc);
        byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
        int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
        ctLength += cipher.doFinal(cipherText, ctLength);
        String query = Base64.encodeBase64URLSafeString(cipherText);
        // String query = cipherText.toString();
        System.out.println("The unix time in ms is :: " + time);
        System.out.println("Encrypted Token is :: " + query);
    } catch (Exception e) {
        System.out.println("Error while encrypting :" + e);




Should I be using the built-in library hashlib to implement something like this? I can’t really find documentation for implementing a PBKDF2 encryption with iterations/salt as inputs. Should I be using pbkdf2? Sorry for the vague questions, I’m unfamiliar with the encryption process and feel like even just knowing what the correct constructor would be is a step in the right direction.

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.