2016-11-04 29 views
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?

+0

你使用Oracle JDK或OpenJDK的? –

+0

可能需要安装Java加密扩展http://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html#SunJCEProvider – pedrofb

回答

0

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

OpenJDK的实现并不只提供一个 PBKDF2HmacSHA1Factory.java它具有“HMACSHA1”消化harcoded。 据我测试,Oracle JDK在这个意义上并没有什么不同。

你需要做的是派生PBKDF2HmacSHA1Factory(来吧,它是开放!),并添加一个参数到它的构造函数。您可避免 混乱创建自己的供应商,而只是初始化和使用你的 工厂如下:

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; 
} 
相关问题