java端使用了AES SHA1PRNG进行数据传输加密工具类
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import org.apache.commons.codec.binary.Base64;
public class AESEncryptionUtil {
public static String encrypt(String seed, byte[] original) {
try {
return new String(Base64.encodeBase64(getCipher(seed, Cipher.ENCRYPT_MODE).doFinal(original)));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
public static byte[] decrypt(String seed, byte[] encrypted) {
try {
return getCipher(seed, Cipher.DECRYPT_MODE).doFinal(Base64.decodeBase64(encrypted));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
private static Cipher getCipher(String seed, int encryptMode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
//生成加密随机数
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
//并设置seed
random.setSeed(seed.getBytes());
//创建AES生产者
KeyGenerator generator = KeyGenerator.getInstance("AES");
//初始化生产者,128位
generator.init(128, random);
// 返回基本编码格式的密钥,如果此密钥不支持编码,则返回null。
byte[] enCodeFormat = generator.generateKey().getEncoded();
// 转换为AES专用密钥
SecretKey key = new SecretKeySpec(enCodeFormat, "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES");
//初始化解码器,这里根据是加密模式还是解码模式
cipher.init(encryptMode, key);
return cipher;
}
}