java 需要帮助创建有效的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32400844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need help creating a valid nonce
提问by Amy
I am trying to consume a web service that uses Password Digest mode, and I have these functions in my Java application to generate a random nonce, creation date and password digest. I can't get past the Authentication Failed error, and the documentation isn't overly clear on whether they want SHA-1 or MD5, as it mentions both in passing. I've tried MD5 instead of SHA-1 and I am getting the same result. I managed to get the requests to work via a test on SoapUI, but I have no idea how that application is generating the digest / nonce. Any help is appreciated.
我正在尝试使用使用密码摘要模式的 Web 服务,并且我的 Java 应用程序中有这些函数来生成随机随机数、创建日期和密码摘要。我无法克服“身份验证失败”错误,并且文档并不太清楚他们是否需要 SHA-1 或 MD5,因为它顺便提到了两者。我已经尝试过 MD5 而不是 SHA-1 并且我得到了相同的结果。我设法通过对 SoapUI 的测试使请求工作,但我不知道该应用程序如何生成摘要/随机数。任何帮助表示赞赏。
Here's the code I am using to generate the nonce and the password digest:
这是我用来生成随机数和密码摘要的代码:
private static SOAPMessage createSOAPRequest() throws Exception
{
String password = "FakePassword";
String nonce = generateNonce();
System.out.println("Nonce = " + nonce);
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date today = Calendar.getInstance().getTime();
String created = dateFormatter.format(today);
System.out.println("Created = " + created);
String passwordDigest = buildPasswordDigest(nonce, created, password);
System.out.println("Password Digest = " + passwordDigest);
}
private static String buildPasswordDigest(String nonce, String created, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException
{
MessageDigest sha1;
String passwordDigest = null;
try
{
sha1 = MessageDigest.getInstance("SHA-1");
sha1.update(Base64.decodeBase64(nonce));
sha1.update(created.getBytes("UTF-8"));
passwordDigest = new String(Base64.encodeBase64(sha1.digest(password.getBytes("UTF-8"))));
sha1.reset();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return passwordDigest;
}
private static String generateNonce() throws NoSuchAlgorithmException, NoSuchProviderException, UnsupportedEncodingException
{
String dateTimeString = Long.toString(new Date().getTime());
byte[] nonceByte = dateTimeString.getBytes();
return Base64.encodeBase64String(nonceByte);
}
采纳答案by F. Stephen Q
The solution was to replace the line sha1.update(nonce.getBytes("UTF-8"));
with sha1.update(Base64.decodeBase64(nonce));
解决方案是sha1.update(nonce.getBytes("UTF-8"));
用sha1.update(Base64.decodeBase64(nonce));