SHA2 password storage with Java

左心房为你撑大大i 提交于 2019-12-04 14:33:42

问题


I'm attempting to make a XML-RPC call that requires HmacSHA-256 hashing of a particular string. I'm currently using the Jasypt library with the following code:

StandardPBEStringEncryptor sha256 = new StandardPBEStringEncryptor();
          sha256.setPassword(key);
          sha256.setAlgorithm("PBEWithHmacSHA2");

On trying to use sha256.encrypt(string) I get this error:

Exception in thread "main" org.jasypt.exceptions.EncryptionInitializationException: java.security.NoSuchAlgorithmException: PBEWithHmacAndSHA256 SecretKeyFactory not available
     at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.initialize(StandardPBEByteEncryptor.java:597)
     at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.initialize(StandardPBEStringEncryptor.java:488)
     at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.encrypt(StandardPBEStringEncryptor.java:541)
     at nysenateapi.XmlRpc.main(XmlRpc.java:52)
    Caused by: java.security.NoSuchAlgorithmException: PBEWithHmacAndSHA256 SecretKeyFactory not available
     at javax.crypto.SecretKeyFactory.(DashoA13*..)
     at javax.crypto.SecretKeyFactory.getInstance(DashoA13*..)
     at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.initialize(StandardPBEByteEncryptor.java:584)
     ... 3 more

I downloaded the JCE Cryptography extension and placed the jars in my buildpath, but that doesn't seem to have done anything. I've tried using a number of combinations in setAlgorithm above, including "PBE", "PBEWithSha"(1|2|128|256)?, "PBEWithHmacSha", etc.

I also tried using BouncyCastle but I didn't have any luck there either. Any help or guidance appreciated!


回答1:


As correctly noted by @Rook you need to specify a PBE algorithm that includes an encryption algorithm. Two examples out of many are "PBEWithSHA1AndDESede" which is supported by the SunJCE provider and "PBEWITHSHA256AND128BITAES-CBC-BC" which is supported by the Bouncycastle JCE provider.




回答2:


The comments were helpful but I guess I was asking the wrong question. What I was looking to do was mimic the PHP function hash_hmac('sha256',string,key)...

I ended up using the following code:

Mac mac = Mac.getInstance("HmacSha256");
SecretKeySpec secret = new SecretKeySpec(key.getBytes(), "HmacSha256");
mac.init(secret);
byte[] shaDigest = mac.doFinal(phrase.getBytes());
String hash = "";
for(byte b:shaDigest) {
    hash += String.format("%02x",b);
}

Thanks for the guidance, though. Will surely help me in the future.



来源:https://stackoverflow.com/questions/3982502/sha2-password-storage-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!