我在 Play Framework 1.2.4 中遇到 session 问题。当我将特定字符串(“testDude5”)的 SHA256 哈希添加到 session 并随后检索它时,值不相同。对于“testDude1”等其他字符串,不会发生这种情况。这是重现结果的示例代码。
package controllers;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import play.mvc.Controller;
public class ExampleController extends Controller
{
public static final String test1 = "testDude1";
public static final String test2 = "testDude5";
public static void set()
{
session.put("test1", getHash(test1));
session.put("test2", getHash(test2));
}
public static void get()
{
String output = "";
output += "Test 1 compare: ";
output += session.get("test1").equals(getHash(test1)) ? "success" : "failed";
output += "\n";
output += "Test 2 compare: ";
output += session.get("test2").equals(getHash(test2)) ? "success" : "failed";
output += "\n";
renderText(output);
}
/**
* Generates the hash value for a password.
*
* @param password
* @return hash
*/
public static String getHash(String password)
{
// Create an digest object
MessageDigest md;
try
{
// Try to get sha-265
md = MessageDigest.getInstance("SHA-256");
// Encrypt the password
md.update(password.getBytes("UTF-8"));
// Get the encrypted password
byte[] digest = md.digest();
// Convert byte array to String
String str = new String(digest);
// Return encrypted password
return str;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return null;
}
}
我对此感到非常困惑。有谁知道那里发生了什么。感谢您的任何建议。
干杯
最佳答案
问题出在您的 getHash 函数中。 play框架 session 没有任何问题。
public static String getHash(String password) {
....
// Get the encrypted password
byte[] digest = md.digest();
// Convert byte array to String
String str = new String(digest); // DON'T do this with digest!
// The behavior is unspecified.
根据 Java API 文档,此构造函数“通过使用平台的默认字符集解码指定的字节数组来构造新字符串...当给定字节在默认字符集中无效时此构造函数的行为未指定”。但是,您的哈希摘要可能包含默认字符集中无效的内容。
Play框架提供了一个很好的实用函数Codec.byteToHeString()来将byte[]中的摘要转换为十六进制字符串。这可能正是您所需要的。
// Codec resides in play.libs
String str = Codec.byteToHexString(digest);
关于session - play 框架 session 使用 sha256 返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13851923/