问题
Shiro 的md5+salt 加密时出现的错误.
Exception in thread "main" org.apache.shiro.codec.CodecException: The org.apache.shiro.crypto.hash.Md5Hash implementation only supports conversion to byte[] if the source is of type byte[], char[], String, org.apache.shiro.util.ByteSource File or InputStream. The instance provided as a method argument is of type [java.util.UUID]. If you would like to convert this argument type to a byte[], you can 1) convert the argument to one of the supported types yourself and then use that as the method argument or 2) subclass org.apache.shiro.crypto.hash.Md5Hashand override the objectToBytes(Object o) method.
at org.apache.shiro.codec.CodecSupport.objectToBytes(CodecSupport.java:308)
at org.apache.shiro.codec.CodecSupport.toBytes(CodecSupport.java:212)
at org.apache.shiro.crypto.hash.SimpleHash.toByteSource(SimpleHash.java:223)
at org.apache.shiro.crypto.hash.SimpleHash.convertSaltToBytes(SimpleHash.java:206)
at org.apache.shiro.crypto.hash.SimpleHash.<init>(SimpleHash.java:174)
at org.apache.shiro.crypto.hash.SimpleHash.<init>(SimpleHash.java:139)
at org.apache.shiro.crypto.hash.Md5Hash.<init>(Md5Hash.java:48)
at com.wei.TestShiroMD5.main(TestShiroMD5.java:31)
原因
错误代码如下
// 使用md5
Md5Hash md5Hash = new Md5Hash("123");
System.out.println(md5Hash.toHex()); //202cb962ac59075b964b07152d234b70
UUID uuid = UUID.randomUUID();
Md5Hash md5Hash2 = new Md5Hash("123", uuid);
System.out.println(uuid);
System.out.println(md5Hash2.toHex());
本例中 传递了UUID 对象,作为Md5Hash的第二个参数.
解决
修改成如下代码即可:
Md5Hashmd5Hash = new Md5Hash("123");
System.out.println(md5Hash.toHex()); //202cb962ac59075b964b07152d234b70
String uuid = UUID.randomUUID().toString().replace("-", "");
Md5Hash md5Hash2 = new Md5Hash("123", uuid);
System.out.println(uuid);
System.out.println(md5Hash2.toHex());