對於某個程式實現方法的好奇.抱著學習的心態.
研究了一下.得出了以下的結論.順道筆記一下.
測試金鑰方法 (TOKEN)
1
| curl -I "http://mobile.u****x.hk/mobile?language=en_US&mobileToken=[TOKEN]"
|
生成金鑰代碼 (TOKEN)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import java.util.Date;
class Th0z { public static void main(String args[]) { String encryptKey = "Zs****J**t*****e"; String targetVesion = "1.0.1";
StringBuilder temp = new StringBuilder(); temp.append(new RandomString(6).nextString()).append("_"); temp.append(targetVesion).append("_"); temp.append(Long.valueOf(new Date().getTime()));
System.out.println("Content: " + temp.toString()); System.out.println("Token : " + Encryptor.encryptByKey( temp.toString(), Encryptor.generateKey(encryptKey) )); } }
|
加密和解密工具
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import java.util.Base64; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec;
class Encryptor { public static String encryptByKey(String content, Key theKey) { try { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, theKey); return Base64.getEncoder().encodeToString(cipher.doFinal( content.getBytes("UTF-8")) ); }catch(Exception e) {} return content; }
public static Key generateKey(String content) { try { byte[] contentBytes = content.getBytes("UTF-8"); SecretKeySpec secretKeySpec = new SecretKeySpec( contentBytes, 0, contentBytes.length, "AES" ); return secretKeySpec; }catch (Exception localException) {} return null; } }
|
生成隨機數工具
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import java.util.Random;
public class RandomString { private static char[] symbols; private final char[] buf; private final Random random = new Random();
static { StringBuilder temp = new StringBuilder(); for (char ch = '0'; ch <= '9'; ++ch) temp.append(ch); for (char ch = 'a'; ch <= 'z'; ++ch) temp.append(ch); symbols = temp.toString().toCharArray(); }
public RandomString(int theLength) { if (theLength < 1) { throw new IllegalArgumentException( "length < 1: " + theLength ); }else{ buf = new char[theLength]; } }
public String nextString() { for (int idx = 0; idx < buf.length; ++idx) buf[idx] = symbols[random.nextInt(symbols.length)]; return new String(buf); }
}
|