开发者

SHA2 password storage with Java

I'm attempting to make a XML-RPC call that requires HmacSHA-256 hashing of a particular string. I'm currently using t开发者_Go百科he 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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜