83f8c44587e08ec975f7d538252dd82c5c8652b7.svn-base 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * 对开发平台送给公众账号的消息加解密示例代码.
  3. */
  4. // ------------------------------------------------------------------------
  5. package com.yihu.utils.aes;
  6. import java.security.MessageDigest;
  7. import java.util.Arrays;
  8. /**
  9. * SHA1 class
  10. *
  11. * 计算公众平台的消息签名接口.
  12. */
  13. class SHA1 {
  14. /**
  15. * 用SHA1算法生成安全签名
  16. * @param token 票据
  17. * @param timestamp 时间戳
  18. * @param nonce 随机字符串
  19. * @param encrypt 密文
  20. * @return 安全签名
  21. * @throws AesException
  22. */
  23. public static String getSHA1( String timestamp, String encrypt) throws AesException
  24. {
  25. try {
  26. String[] array = new String[] { timestamp, encrypt };
  27. StringBuffer sb = new StringBuffer();
  28. // 字符串排序
  29. Arrays.sort(array);
  30. for (int i = 0; i < 2; i++) {
  31. sb.append(array[i]);
  32. }
  33. String str = sb.toString();
  34. // SHA1签名生成
  35. MessageDigest md = MessageDigest.getInstance("SHA-1");
  36. md.update(str.getBytes());
  37. byte[] digest = md.digest();
  38. StringBuffer hexstr = new StringBuffer();
  39. String shaHex = "";
  40. for (int i = 0; i < digest.length; i++) {
  41. shaHex = Integer.toHexString(digest[i] & 0xFF);
  42. if (shaHex.length() < 2) {
  43. hexstr.append(0);
  44. }
  45. hexstr.append(shaHex);
  46. }
  47. return hexstr.toString();
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. throw new AesException(AesException.ComputeSignatureError);
  51. }
  52. }
  53. }