gpt4 book ai didi

java - SecretKeyFactory 的 NoSuchAlgorithmException

转载 作者:太空宇宙 更新时间:2023-11-04 12:05:20 29 4
gpt4 key购买 nike

当我将 PBKDF2WithHmacSHA1 传递给 getInstance() 时,我不断收到 NoSuchAlgorithmException。

为什么会发生这种情况。我错过了一些进口吗?

import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.SecureRandom;
import java.util.Scanner;
import java.security.spec.*;
import java.security.AlgorithmParameters;
import javax.crypto.SecretKeyFactory.*;

class AES
{
static public String encrypt(String input, String password)
{
SecureRandom random = new SecureRandom();
byte salt[] = new byte[8];
random.nextBytes(salt);

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal(input.getBytes("UTF-8"));

String text = new String(ciphertext, "UTF-8");
return text;
}
}

还有没有办法使用 SHA2 代替 SHA1 ?

最佳答案

如果您使用的是 OpenJDK,则 this可能是你的情况。接受的答案指出:

The OpenJDK implementation does only provide a PBKDF2HmacSHA1Factory.java which has the "HmacSHA1" digest harcoded. As far as I tested, the Oracle JDK is not different in that sense.

What you have to do is derive the PBKDF2HmacSHA1Factory (come on, it is open!) and add a parameter to its constructor. You may avoid the mess of creating your own Provider, and just initialize and use your factory as follows:

PBKDF_SecretKeyFactory kf = new PBKDF_SecretKeyFactory("HmacSHA512");
KeySpec ks = new PBEKeySpec(password,salt,iterations,bitlen);
byte key[] = kf.engineGenerateSecret(ks).getEncoded();

关于使用 SHA2,this post可能有您正在寻找的东西。使用此代码片段:

public byte[] hash(String password) throws NoSuchAlgorithmException
{
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] passBytes = password.getBytes();
byte[] passHash = sha256.digest(passBytes);
return passHash;
}

关于java - SecretKeyFactory 的 NoSuchAlgorithmException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40427139/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com