使用Java进行SHA2密码存储

我正在尝试进行XML-RPC调用,该调用需要对特定字符串进行HmacSHA-256哈希处理。 我目前正在使用带有以下代码的Jasypt库:

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

在尝试使用sha256.encrypt(string)时出现此错误:

 线程“main”中的exceptionorg.jasypt.exceptions.EncryptionInitializationException:java.security.NoSuchAlgorithmException:PBEWithHmacAndSHA256 SecretKeyFactory不可用
     在org.jasypt.encryption.pbe.StandardPBEByteEncryptor.initialize(StandardPBEByteEncryptor.java:597)
     在org.jasypt.encryption.pbe.StandardPBEStringEncryptor.initialize(StandardPBEStringEncryptor.java:488)
      at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.encrypt(StandardPBEStringEncryptor.java:541)
     在nysenateapi.XmlRpc.main(XmlRpc.java:52)
    引起:java.security.NoSuchAlgorithmException:PBEWithHmacAndSHA256 SecretKeyFactory不可用
     在javax.crypto.SecretKeyFactory。(DashoA13 * ..)
     在javax.crypto.SecretKeyFactory.getInstance(DashoA13 * ..)
      at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.initialize(StandardPBEByteEncryptor.java:584)
      ......还有3个

我下载了JCE Cryptography扩展并将jar放在我的buildpath中,但这似乎没有做任何事情。 我尝试在上面的setAlgorithm中使用了许多组合,包括“PBE”,“PBEWithSha”(1 | 2 | 128 | 256)?,“PBEWithHmacSha”等。

我也尝试过使用BouncyCastle,但我也没有运气。 任何帮助或指导赞赏!

正如@Rook正确指出的那样,您需要指定包含加密算法的PBE算法。 其中两个例子是SunJCE提供商支持的"PBEWithSHA1AndDESede"和Bouncycastle JCE提供商支持的"PBEWITHSHA256AND128BITAES-CBC-BC"

评论很有​​帮助,但我想我问的是错误的问题。 我想要做的是模仿PHP函数hash_hmac(’sha256’,string,key)…

我最终使用以下代码:

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

不过,谢谢你的指导。 将来肯定会帮助我。