提示:如果你用properties,請記得linux跟windows的換行.......
原理:
每個都要有一個KEY,把字串(密碼)用sha-256 來Hash之後,當作KEY
然後加解密
參考:http://magiclen.org/aes/ public static String DataENCryptDECryptProcess(int ENDNMode, String messages, String keyString) { String ALGORITHM = "AES"; String TRANSFORMATION = "AES/CBC/PKCS5Padding"; Cipher cipher; String IvString = "1234567890ABCDEF"; IvParameterSpec DEFAULT_IV = new IvParameterSpec(IvString.getBytes("UTF-8")); byte[] data=keyString.getBytes("UTF-8"); final MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(data); byte[] keyBytes = new byte[32]; System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length); Skeyspec = new SecretKeySpec(keyBytes, ALGORITHM); cipher = Cipher.getInstance(TRANSFORMATION); switch (ENDNMode) { case ENCRYPT: decryptFrom = messages.getBytes("UTF-8"); cipher.init(Cipher.ENCRYPT_MODE, Skeyspec,DEFAULT_IV); result = cipher.doFinal(decryptFrom); return new String(alonaBase64.getEncoder().encode(result),"UTF-8"); case DECRYPT: decryptFrom = alonaBase64.getDecoder().decode(messages); cipher.init(Cipher.DECRYPT_MODE, Skeyspec,DEFAULT_IV); result = cipher.doFinal(decryptFrom); return new String(result, "UTF-8"); default: return "ERROR"; } } |
找過另外一種解法,但是在windows與LINUX上面搭配有問題的解法:
經過測試,還是沒辦法解決win與linux上的KEY不同
原因: SecureRandom 實現完全隨操作系統本身的內部狀態,除非調用方在調用 getInstance 方法之後又調用了 setSeed 方法;該實現在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系統上則不同。
if (detectPlatform("Android")) { secureRandom = SecureRandom.getInstance("SHA1PRNG", "Crypto"); } else { System.out.println("iswindows=" + detectPlatform("windows")); System.out.println("isLinux=" + detectPlatform("linux")); secureRandom = SecureRandom.getInstance("SHA1PRNG"); } secureRandom.setSeed(keyString.getBytes("UTF-8")); kgen.init(keysize,secureRandom); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); System.out.println("enCodeFormat="+parseByte2HexStr(enCodeFormat)); Skeyspec = new SecretKeySpec(enCodeFormat, ALGORITHM); |
沒有留言:
張貼留言