阐述Java服务端DES加解密规则, 可兼容iOS自带DES加密方式
先定义其加密参数规则,如下:
private static final String KEY_ALGORITHM = "DES";
private static final String CIPHER_TRANSFORMATION = "DES/CBC/PKCS5Padding";
private static final String CHARSET = "UTF-8";private static final byte[] SPECIFICATION = { 1, 2, 3, 4, 5, 6, 7, 8 };
加密方式:
try {
byte[] data = content.getBytes(CHARSET);
IvParameterSpec parameterSpec = new IvParameterSpec(SPECIFICATION);
SecretKeySpec sKey = new SecretKeySpec(key.getBytes(),
KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, sKey, parameterSpec);
byte[] results = cipher.doFinal(data);
return Base64.encode(results);
} catch (Throwable t) {
t.printStackTrace();
}
解密方式:
try {
byte[] prepares = Base64.decode(content);
IvParameterSpec parameterSpec = new IvParameterSpec(SPECIFICATION);
SecretKeySpec sKey = new SecretKeySpec(key.getBytes(),
KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, sKey, parameterSpec);
byte[] results = cipher.doFinal(prepares);
return new String(results, CHARSET);
} catch (Throwable t) {
t.printStackTrace();
}
这里的SPECIFICATION数组长度为8