Grails 1.1 onwards 开发者_如何学Gohas 'encodeAsMD5' available on Strings -- is there a way to provide a salt for the function?
Typical usage:
${myString.encodeAsMD5()}
Another option would be to use the Apache DigestUtils class.
I'm not using this to do password hashing -- instead, I'm using it for a verification mechanism to determine when a request was created and how much time elapsed when the response was received.
To start out, I encrypt the date/time of when a request was initially created and pass it over to the client. Later when the client sends some data back, it includes the original hash value which is then used in determining how much time has passed.
Are you wanting to have a salt because you're trying to do password hashing? If so, please consider jBCrypt, a secure, really easy-to-use, password hashing library. You can probably easily hook it in as a Groovy string metamethod. :-P
And if you're not doing password hashing, I'm not sure where a salt would come in; please feel free to elaborate in that case. :-)
Example of how to use HMAC to do keyed hashing (I used HmacMD5
in my example, but you can use HmacSHA1
, HmacSHA256
, HmacSHA384
, or HmacSHA512
also):
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public byte[] hmacMD5(byte[] key, byte[] data) {
Mac mac = Mac.getInstance("HmacMD5");
mac.init(new SecretKeySpec(key, "HmacMD5"));
mac.update(data);
return mac.doFinal();
}
I'm sorry that this is in Java and not Groovy, but hopefully it'll be easy enough for you to adapt. :-) Anyway, in this example, your constant value would be the key, and the incoming data would be the data.
If your data is sizeable (unlikely from what you've described), you can call update
multiple times, and the hash would work as though the data from those calls were all concatenated together.
Can't you use MessageDigest (Example)? You'll have to cache the original timestamp/hash, or better yet, store the inbound and outbound transmissions in some sort of auditing table.
精彩评论