概念
- 加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的内容。
- 加密作用:防止重要敏感信息,被人获取。防看
- 加密一般指的是双向加密
分类
算法
- 对称:DES、3DES
- 非对称:RSA
- RSA加密异常:javax.crypto.IllegalBlockSizeException: Data must not be longer than 117bytes
- RSA非对称加密内容长度有限制,1024位key的最多只能加密117位数据,否则就会报错
代码
DES加密
SecureRandom sr = new SecureRandom();
byte[] keyByte = key.getBytes("UTF-8");
byte[] plainByte = plaintext.getBytes("UTF-8");
SecretKey securekey = new SecretKeySpec(keyByte, algorithmDES);
Cipher cipher = Cipher.getInstance(algorithmDES);
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
byte[] cipherByte = cipher.doFinal(plainByte);
cipherText = Base64.encode(cipherByte);
System.out.println(cipherText);
DES解密
SecureRandom sr = new SecureRandom();
byte[] keyByte = key.getBytes("UTF-8");
byte[] cipherByte = Base64.decode(cipherText);
SecretKey securekey = new SecretKeySpec(keyByte, algorithmDES);
Cipher cipher = Cipher.getInstance(algorithmDES);
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
byte[] plaintByte = cipher.doFinal(cipherByte);
plaintext = new String(plaintByte);
System.out.println(plaintext);
RSA加密
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithmRSA);
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
publicKey = keyPair.getPublic();
privateKey = keyPair.getPrivate();
Cipher cipher = Cipher.getInstance(algorithmRSA);
byte[] plainByte = plaintext.getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherByte = cipher.doFinal(plainByte);
cipherText = Base64.encode(cipherByte);
System.out.println(cipherText);
RSA解密
byte[] cipherByte = Base64.decode(cipherText);
Cipher cipher = Cipher.getInstance(algorithmRSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plaintByte = cipher.doFinal(cipherByte);
plaintext = new String(plaintByte);
System.out.println(plaintext);