【发布时间】:2019-01-31 05:49:46
【问题描述】:
我的任务是构建 API 的使用者,该使用者需要具有 UNIX 时间种子值的加密令牌。我展示的示例是使用我不熟悉的 Java 实现的,并且在阅读文档和其他堆栈文章后无法找到解决方案。
使用javax.crypto.SecretKey、javax.crypto.SecretKeyFactory、javax.crypto.spec.PBEKeySpec 和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 吗?对于模糊的问题,我很抱歉,我不熟悉加密过程,并且觉得即使知道正确的构造函数是什么,也是朝着正确方向迈出的一步。
【问题讨论】:
-
几年前写的,应该是一个OK的起点:gist.github.com/is/13a519282e676dca861e
-
请注意:代码中的盐不应该与密钥相同。要么生成一个确定的非重复序列,要么使用 SecureRandom 生成它;然后将其与加密消息一起传输。
标签: java python pbkdf2 hmacsha1 hashlib