Python相当于java PBKDF2WithHmacSHA1

mbu*_*e05 1 python java hashlib pbkdf2 hmacsha1

我的任务是构建一个API的使用者,该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);

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

我应该使用内置库hashlib来实现这样的东西吗?我无法找到实现PBKDF2加密的文档,迭代/ salt作为输入.我应该用pbkdf2吗?对于模糊的问题很抱歉,我对加密过程不熟悉,甚至只知道正确的构造函数是朝着正确方向迈出的一步.

t.m*_*dam 7

是的,Python的等价物是hashlib.pbkdf2_hmac.例如这段代码:

from hashlib import pbkdf2_hmac

key = pbkdf2_hmac(
    hash_name = 'sha1', 
    password = b"somekeyvalue", 
    salt = b"somekeyvalue", 
    iterations = 12345, 
    dklen = 32
)

print(key)
Run Code Online (Sandbox Code Playgroud)

生成与Java代码相同的密钥.

但是,此代码的问题(在备忘录的评论中提到)是使用salt.对于每个密码,盐应该是随机且唯一的.您可以使用创建安全随机字节os.urandom,因此更好的示例是:

from hashlib import pbkdf2_hmac
from os import urandom

salt = urandom(16)
key = pbkdf2_hmac('sha1', b"somekeyvalue", salt, 12345, 32)
Run Code Online (Sandbox Code Playgroud)

您可能还想增加迭代次数(我认为建议的最小数量是10,000).


其余的代码很容易"翻译".

  • 对于时间戳,用于time.time获取当前时间并乘以1000.

    import time
    
    milliseconds = str(round(time.time() * 1000))
    
    Run Code Online (Sandbox Code Playgroud)
  • 对于编码,您可以使用base64.urlsafe_b64encode(它包括填充,但您可以删除它.rstrip(b'=')).

  • 现在,对于加密部分,Python没有内置加密模块,因此您必须使用第三方库.我推荐pycryptodomecryptography.
    在这一点上,我必须警告你,你使用的AES模式非常弱.请考虑使用CBC或CTR,或者更好地使用经过身份验证的加密算法.