关于密钥的简介:
简单的加密与解密: 用到了异或操作(两次异或操作得到原来的信息,异或:不同为1,相同为0)
package NO2;
public class Test29 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 10;
x = x ^ 25;
System.out.println(x);
x = x ^ 25;
System.out.println(x);
}
}
输出:19
10
对称加密:DES,AES
不对称加密:RSA
package NO2;
//简单加密
public class Test30 {
public static void main(String[] args) throws Exception{
String s ="我们的abc";//原文
byte[] buf = s.getBytes("utf-8");
String key = "xyz"; //密钥
byte[] key_buf = key.getBytes("utf-8");
//加密
for(int i = 0; i < s.length();i++){
buf[i] ^=key_buf[i % key_buf.length];//此处%:防止出现密钥的byte数组长度长度<原文byte数组长度的情况
}
//解密
for(int i = 0; i < s.length();i++){
buf[i] ^=key_buf[i % key_buf.length];//此处%:防止出现密钥的byte数组长度长度<原文byte数组长度的情况
}
System.out.println(new String(buf,"utf-8"));
}
}
输出:我们的abc
package NO2;
import java.io.IOException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
//AES加密
public class Test31 {
public static String encrypt(String src,String pwd){
try {
//处理密钥
byte[] bKey = pwd.getBytes("utf-8");
byte[] buf = new byte[16];//创建一个16字节的数组,默认值为0
for(int i = 0;i < buf.length && i < bKey.length ;i++){ //bkey中过长则舍弃,过短则采用默认值0
buf[i] = bKey[i];
}
SecretKeySpec key = new SecretKeySpec(buf, "AES");
//加密
Cipher cipher = Cipher.getInstance("AES");//创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] out = cipher.doFinal(src.getBytes("utf-8"));
//转化为串
return new BASE64Encoder().encode(out);//Encoder编码器
} catch (Exception e) {
// TODO: handle exception
}
return "";
}
public static String decrypt(String src,String pwd) {
//处理密钥
try {
byte[] bkey = pwd.getBytes("utf-8");
byte[] buf = new byte[16];
for(int i = 0; i < bkey.length && i < buf.length;i++){
buf[i] = bkey[i];
}
SecretKeySpec key = new SecretKeySpec(buf, "AES");
//密码还原成byte
buf = new BASE64Decoder().decodeBuffer(src);
//解密
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] out = cipher.doFinal(buf);
return new String(out,"utf-8");
} catch (Exception e) {
// TODO: handle exception
}
return "";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String string= "我们ABC";
String s1 = encrypt(string, "xyz");
System.out.println(s1);
System.out.println(decrypt(s1, "xyz"));
}
}
输出:
3D4Dt5UwgxxiUrp4wwjd8Q==
我们ABC