fork(6) download
  1. import java.io.UnsupportedEncodingException;
  2. import java.security.Key;
  3.  
  4. import javax.crypto.Cipher;
  5. import javax.crypto.spec.IvParameterSpec;
  6. import javax.crypto.spec.SecretKeySpec;
  7.  
  8. import sun.misc.BASE64Encoder;
  9.  
  10. class AES {
  11. static Cipher cipher;
  12. static final String KEY_ALGORITHM = "AES";
  13. static final String CIPHER_ALGORITHM_CBC = "AES/CBC/PKCS5Padding";
  14. static final String CIPHER_ALGORITHM_ECB = "AES/ECB/PKCS5Padding";
  15. static Key secretKey;
  16. static IvParameterSpec iv;
  17.  
  18. public static void main(String[] args) throws Exception {
  19. // 用户信息
  20. String customerData = "{\"uid\":\"test@youhaosuda.com\",\"type\":\"email\",\"name\":\"test\"}";
  21. // 接入密钥
  22. String strKey = "F789BF878B624AE3BA6A99B33BBCCFF6";
  23. // 店铺主域名
  24. String shopDomain = "youhaosuda.com";
  25. String strEncrypt = aesEncrypt(strKey, customerData);
  26. String redirectUrl = "http://" + shopDomain + "/account/multipass/login/" + strEncrypt;
  27.  
  28. System.out.println("customerData: " + customerData);
  29. System.out.println("customerDataEncrypt: " + strEncrypt);
  30. System.out.println("redirectUrl: " + redirectUrl);
  31. }
  32.  
  33. /**
  34.   * 使用AES 算法 加密,默认模式 AES/CBC/PKCS5Padding
  35.   */
  36. static String aesEncrypt(String strKey, String strData) throws Exception {
  37. cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
  38. secretKey = getKey(strKey);
  39. iv = getIV(strKey);
  40.  
  41. cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
  42. byte[] encrypt = cipher.doFinal(strData.getBytes());
  43. return urlsafeBase64(new BASE64Encoder().encode(encrypt));
  44. }
  45.  
  46. static IvParameterSpec getIV(String strIv) throws UnsupportedEncodingException {
  47. byte[] arrBTmp = strIv.getBytes("UTF-8");
  48. byte[] arrB = new byte[16];
  49. for (int i = 0; i + 16 < arrBTmp.length && i < arrB.length; i++) {
  50. arrB[i] = arrBTmp[i + 16];
  51. }
  52. return new IvParameterSpec(arrB);
  53. }
  54.  
  55. static Key getKey(String strKey) throws Exception {
  56. byte[] arrBTmp = strKey.getBytes("UTF-8");
  57. byte[] arrB = new byte[16];
  58. for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
  59. arrB[i] = arrBTmp[i];
  60. }
  61. return new SecretKeySpec(arrB, "AES");
  62. }
  63.  
  64. static String urlsafeBase64(String source) throws Exception {
  65. return source.replace("+", "-").replace("/", "_");
  66. }
  67. }
Success #stdin #stdout 0.5s 321600KB
stdin
Standard input is empty
stdout
customerData: {"uid":"test@youhaosuda.com","type":"email","name":"test"}
customerDataEncrypt: 17FErOXQwR8IC2FFxESVkFcdUra_eFXyDpjYuKcP6MgrVsJxv4_dmu5HzgtqROup6YzVAMXakItC
IhN7_gIoFA==
redirectUrl: http://y...content-available-to-author-only...a.com/account/multipass/login/17FErOXQwR8IC2FFxESVkFcdUra_eFXyDpjYuKcP6MgrVsJxv4_dmu5HzgtqROup6YzVAMXakItC
IhN7_gIoFA==