Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。Base64编码可用于在HTTP环境下传递较长的标识信息。采用Base64编码具有不可读性,即所编码的数据不会被人用肉眼所直接看到。今天用Base64实现加密解密:
准备工具
所需依赖jar包 Apache的 commons-codec-1.9.jar
详细过程
工程目录架构
java代码类
Decryption.java
package www.o6c.com;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* 解密
* @author jiangfengcheng
*
*/
public class Decryption {
/**
* 解密
* 江风成 2016-10-21 10:51:21
* @param encStr 解密
* @param raw 解密key
* @return
* @throws Exception
*/
public static String decodeMessage(String encStr,byte[] raw) throws Exception {Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS5Padding”);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(raw, “AES”), new IvParameterSpec(raw));
byte[] encrypted = Base64.decodeBase64(encStr);
byte[] msgs = cipher.doFinal(encrypted);
return new String(msgs);
}}
Encrypted.java
package www.o6c.com;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* 加密
* @author jiangfengcheng
*
*/
public class Encrypted {/**
* 加密
* 江风成 2016-10-21 10:51:21
* @param srcStr 加密内容
* @param raw key
* @return
* @throws Exception
*/
public static String encodeMessage(String srcStr,byte[] raw) throws Exception {
Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS5Padding”);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(raw, “AES”), new IvParameterSpec(raw));
byte[] encrypted = cipher.doFinal(srcStr.getBytes());
String msgs = Base64.encodeBase64String(encrypted);
return msgs;
}}
Test.java 测试类
package www.o6c.com;
public class Test {
//加密解密的key
private static final byte[] raw = “www.o6c.com@love”.getBytes();
//需要加密的文本
private static String text =”江风成我爱你”;public static void main(String[] args) {
//加密内容
try {
System.out.println(“加密密文:”+Encrypted.encodeMessage(text, raw));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//解密内容
try {
System.err.println(“解密密文:”+Decryption.decodeMessage(Encrypted.encodeMessage(text, raw), raw));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
结果
好厉害,你居然回调用各种包了诶,大神啊