根据加密字符串生成加密密钥
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
private static SecretKeySpec getKeyBytes(String key){ SecretKeySpec secretKeySpec = null; try { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom sha1PRNG = SecureRandom.getInstance("SHA1PRNG"); sha1PRNG.setSeed(key.getBytes(StandardCharsets.UTF_8));
keyGenerator.init(128, sha1PRNG);
SecretKey secretKey = keyGenerator.generateKey(); secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return secretKeySpec; }
|
不过使用以上生成加密密钥的方式我还是出现了错误,在Android端和Linux服务器端生成的加密密钥不一致,最后是迫不得已用了这种方式
1 2 3 4
| private static SecretKeySpec getKeyBytes(String key) throws UnsupportedEncodingException { SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); return secretKeySpec; }
|
字节组转换为Base64编码
1 2 3 4 5 6 7 8
|
private static String bytesToBase64(byte[] bytes) { return Base64.getEncoder().encodeToString(bytes); }
|
base64编码转换为字节组
1 2 3 4 5 6 7 8 9
|
private static byte[] base64ToBytes(String base64) throws IOException { return Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8)); }
|
加密方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public static String encrypt(String text, String key){ String encryptValue = null; try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, getKeyBytes(key));
byte[] textBytes = text.getBytes(StandardCharsets.UTF_8);
byte[] doFinal = cipher.doFinal(textBytes);
encryptValue = bytesToBase64(doFinal); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); } return encryptValue; }
|
解密方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public static String decrypt(String text, String key){ String decryptValue = null; try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, getKeyBytes(key));
byte[] doFinal = cipher.doFinal(base64ToBytes(text)); decryptValue = new String(doFinal); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IOException e) { e.printStackTrace(); } return decryptValue; }
|