NoSuchAlgorithmException 与 SecretKeyFactory

NoSuchAlgorithmException with SecretKeyFactory

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

为什么会这样。我错过了一些进口商品吗?

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;
}