编解码base64、对称加密aes和非对称加密rsa

base64 :(兼容所有bit8位的字符,然后用64种字符进行转码,达到一致性)

      意思就是:考虑到多语言原因,有的特殊字符传输不兼容,因为很多都是只支持ASSIC码,那么特殊字符就会找不到对应的ASSIC码,所以采用BASE64 可以叫全天下所有字符用 64中字符表示,而且这64种字符都在 ASSIC 中,所以在网络传输中很流行。

   特点:

      首先这算法是编码, 不是压缩, 编码后只会增加字节数;

      算法简单, 几乎不会影响效率;

      算法可逆, 解码很方便, 不用于私密信息通信;

      虽然解码方便, 但毕竟编码了, 肉眼还是不能直接看出原始内容;

      加密后的字符串只有[0-9a-zA-Z+/=], 不可打印字符(包括转移字符)也可传输;

 

AES 对称加密算法

      这是加密算法,base64只是编码,不是加密,AES 加密和解密效率高,双方必须使用同一个秘钥,如果不考虑秘钥被偷窃,那么AES 是很安全的

代码:

private static final String PRIVATE_KEY = "P9F4D5AGV214D56AFD231AF5D6SA4FDS";

private static final String ARITHMETIC = "AES";

// 秘钥自定义,算法必须是关键字 AES 或者 AES/ECB/PKCS5Padding,还没有找到第三种

public static String AESEncode(String privateKey,String content){

try {

// 根据密钥生成AES密钥

SecretKey key = new SecretKeySpec(privateKey.getBytes(), ARITHMETIC);

// 获取密码器实例

Cipher cipher = Cipher.getInstance(ARITHMETIC);

// 初始化 AES 密码器

cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] doFinal = cipher.doFinal(content.getBytes(UTF_8));

return new BASE64Encoder().encode(doFinal);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

 

public static String AESDecode(String privateKey, String content){

try {

// 根据密钥生成AES密钥

SecretKey key = new SecretKeySpec(privateKey.getBytes(), ARITHMETIC);

// 获取密码器实例

Cipher cipher = Cipher.getInstance(ARITHMETIC);

// 初始化

你可能感兴趣的:(java基础,编解码,对称加密,非对称加密)