1
当我将PBKDF2WithHmacSHA1传递给getInstance()时,我不断收到NoSuchAlgorithmExeception。NoSuchAlgorithmException与SecretKeyFactory
为什么会发生这种情况。我是否缺少一些进口产品?
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?
你使用Oracle JDK或OpenJDK的? –
可能需要安装Java加密扩展http://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html#SunJCEProvider – pedrofb