base64形式
import org.apache.commons.codec.binary.Base64;import java.nio.charset.StandardCharsets;public class bybase64 { private static String str = "guomz"; public static void main(String[] args) { byte[] encodeBytes = Base64.encodeBase64(str.getBytes(StandardCharsets.UTF_8)); System.out.println(new String(encodeBytes)); byte[] decodeBytes = Base64.decodeBase64(encodeBytes); System.out.println(new String(decodeBytes)); }}
base64形式比较简单,因为密码本是公开的所以安全性比拟低,用该形式传输数据能够避免乱码、防止明文间接传输。
AES加解密
import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets;import java.security.Key;public class byaes { //须要加密的信息 private static String str = "guomz"; /** * aes对称加密 * @param args */ public static void main(String[] args) { aesByRandomKey(); System.out.println("--------------------------"); aesByUsingKey("1234567812345678"); } /** * 应用随机生成的key加密 */ private static void aesByRandomKey(){ try { //生成密钥 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); //初始化密钥长度 keyGenerator.init(128); SecretKey secretKey = keyGenerator.generateKey(); //生成后base64加密 byte[] encodedKey = secretKey.getEncoded(); System.out.println("key: " + new String(encodedKey)); //key转换,下面的key能够间接指定一个随机字符串,而后base64加密传入上面办法 Key key = new SecretKeySpec(encodedKey, "AES"); //进行加密,指定模式 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptBytes = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)); System.out.println(new String(encryptBytes)); //进行解密 cipher.init(Cipher.DECRYPT_MODE, key); byte[] decryptBytes = cipher.doFinal(encryptBytes); System.out.println(new String(decryptBytes)); }catch (Exception e){ e.printStackTrace(); } } /** * 应用自定义的key加密 * @param keyStr */ private static void aesByUsingKey(String keyStr){ try { //key转换,下面的key能够间接指定一个随机字符串,而后base64加密传入上面办法 Key key = new SecretKeySpec(keyStr.getBytes(StandardCharsets.UTF_8), "AES"); //进行加密,指定模式 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptBytes = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)); System.out.println(new String(encryptBytes)); //进行解密 cipher.init(Cipher.DECRYPT_MODE, key); byte[] decryptBytes = cipher.doFinal(encryptBytes); System.out.println(new String(decryptBytes)); }catch (Exception e){ e.printStackTrace(); } }}
AES属于对称加密,是DES加密的升级版,目前宽泛应用,原理是加解密的密钥用的是一个,须要把密钥提供给解密方。