我的任务是构建一个 API 的使用者,该 API 需要带有 UNIX 时间种子值的加密令牌。我看到的示例是使用我不熟悉的 Java 实现的,在阅读文档和其他堆栈文章后一直无法找到解决方案。
使用javax.crypto.SecretKey
, javax.crypto.SecretKeyFactory
, javax.crypto.spec.PBEKeySpec
, and javax.crypto.spec.SecretKeySpec
协议,我需要生成类似于以下内容的令牌:
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);
}
}
}
我应该使用内置库吗hashlib
实施这样的事情?我真的找不到实现的文档PBKDF2
以迭代/盐作为输入的加密。我应该使用pbkdf2
?抱歉,我的问题含糊不清,我不熟悉加密过程,感觉即使知道正确的构造函数是什么也是朝着正确方向迈出的一步。