1.异或运算,是在二进制运算中,相同的位上,如果值相同得0,不相同的1
2. 异或运算还有一个特殊的性质,就是逆运算,就拿刚才的例子来说,2^3=1,无论2、3、1中哪二个数做异或,结果永远只会等于另一个数。
2^3=1
2^1=3
3^1=2,通过异或这种特殊的运算性质,用它来做对称加密是比较好的选择。
即当我有一个值是3,这时的秘钥是2,当我们对3进行加密时,传过去的值就是1,
然后把密文1和秘钥2进行^运算就可以得到原来的值3,这个就是对称加密的基本原理
3.对称加密使用的是同一个秘钥,也可以叫单钥加密:
根据上面的到的结论,我们做一个简单的对称加密例子
public class Test {
public static void main(String[] args) {
String content = "1234"; //需要加密的字符
String key = "abc"; //密钥
byte[] result = encryption(content, key);
System.out.println("1234加密后的值:" + new String(result));
System.out.println("---------------");
System.out.println("1234解密后的值:" +new String(decipher(new String(result), key)));
}
//加密过程
public static byte[] encryption(String content,String key){
//把加密数据转为字节数组
byte[] contentBytes = content.getBytes();
//把秘钥转为二进制字节数组,即ASCII码
byte[] keyBytes = key.getBytes();
//初始值给一个0,因为0^ 任何值都等于任何值
byte dkey = 0;
for(byte b : keyBytes){
dkey ^= b;
}
byte salt = 0; //随机盐值
//创建Byte数组来存储加密后的ASCII码
byte[] result = new byte[contentBytes.length];
for(int i = 0 ; i < contentBytes.length; i++){
salt = (byte)(contentBytes[i] ^ dkey ^ salt);
//原文对应ASCII码加密时除第一个使用初始化值0,其他的使用的都是原文对应的ASCII码来做盐值
result[i] = salt;
}
return result;
}
//解密数据
public static byte[] decipher(String content,String key){
//要解密的二进制二进制码即ASCII码存储在这里
byte[] contentBytes = content.getBytes();
//把秘钥的二进制码存储这里
byte[] keyBytes = key.getBytes();
byte dkey = 0;
for(byte b : keyBytes){
dkey ^= b;
}
byte salt = 0; //随机盐值
byte[] result = new byte[contentBytes.length];
//从后向前解密,因为我们初始值的盐值是0,所以这里当第一字节解码时盐值也应该是0
for(int i = contentBytes.length - 1 ; i >= 0 ; i--){
if(i == 0){
salt = 0;
}else{
salt = contentBytes[i - 1];
}
//密文^dkey^salt 就的到原文
result[i] = (byte)(contentBytes[i] ^ dkey ^ salt);
}
return result;
}
}
非对称加密有点复杂参考:https://blog.csdn.net/jijianshuai/article/details/80582187
4.非对称加密的例子及使用场景:
附一个我用过的非对称加密的工具类和使用场景:
package com.newtranx.vcas.util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAEncryptUtil {
/**
* 指定加密算法为RSA
*/
private static String ALGORITHM = "RSA";
/**
* 指定key的大小
*/
private static int KEYSIZE = 1024;
/**
* 指定公钥存放文件
*/
private static String PUBLIC_KEY_FILE = "PublicKey";
/**
* 指定私钥存放文件
*/
private static String PRIVATE_KEY_FILE = "PrivateKey";
public static final String KEY_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
* 生成密钥对
*/
public static void generateKeyPair() throws Exception {
/** RSA算法要求有一个可信任的随机数源 */
SecureRandom sr = new SecureRandom();
/** 为RSA算法创建一个KeyPairGenerator对象 */
KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
/** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
kpg.initialize(KEYSIZE, sr);
/** 生成密匙对 */
KeyPair kp = kpg.generateKeyPair();
/** 得到公钥 */
Key publicKey = kp.getPublic();
/** 得到私钥 */
Key privateKey = kp.getPrivate();
/** 用对象流将生成的密钥写入文件 */
ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
oos1.writeObject(publicKey);
oos2.writeObject(privateKey);
/** 清空缓存,关闭文件输出流 */
oos1.close();
oos2.close();
}
/**
* 产生签名
*
* @param data
* @param privateKey
* @return
* @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
// 解密由base64编码的私钥
byte[] keyBytes = decryptBASE64(privateKey);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取私钥对象
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data);
return encryptBASE64(signature.sign());
}
/**
* 验证签名
*
* @param data
* @param publicKey
* @param sign
* @return
* @throws Exception
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
// 解密由base64编码的公钥
byte[] keyBytes = decryptBASE64(publicKey);
// 构造X509EncodedKeySpec对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取公钥匙对象
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);
// 验证签名是否正常
return signature.verify(decryptBASE64(sign));
}
/**
* BASE64解密
*
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}
/**
* BASE64加密
*
* @param key
* @return
* @throws Exception
*/
public static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}
/**
* 加密方法 source: 源数据
*/
public static String encrypt(String source) {
//generateKeyPair();
String mi = "";
try {
/** 将文件中的公钥对象读出 */
ObjectInputStream ois = new ObjectInputStream(RSAEncryptUtil.class.getResourceAsStream("/rsa/" + PUBLIC_KEY_FILE));
Key key = (Key) ois.readObject();
ois.close();
/** 得到Cipher对象来实现对源数据的RSA加密 */
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
int MaxBlockSize = KEYSIZE / 8;
String[] datas = splitString(source, MaxBlockSize - 11);
for (String s : datas) {
mi += bcd2Str(cipher.doFinal(s.getBytes()));
}
} catch (Exception e) {
e.printStackTrace();
}
return mi;
}
/**
*/
public static String[] splitString(String string, int len) {
int x = string.length() / len;
int y = string.length() % len;
int z = 0;
if (y != 0) {
z = 1;
}
String[] strings = new String[x + z];
String str = "";
for (int i = 0; i < x + z; i++) {
if (i == x + z - 1 && y != 0) {
str = string.substring(i * len, i * len + y);
} else {
str = string.substring(i * len, i * len + len);
}
strings[i] = str;
}
return strings;
}
/**
*/
public static String bcd2Str(byte[] bytes) {
char temp[] = new char[bytes.length * 2], val;
for (int i = 0; i < bytes.length; i++) {
val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
val = (char) (bytes[i] & 0x0f);
temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
}
return new String(temp);
}
/**
* 解密算法 cryptograph:密文
*/
public static String decrypt(String cryptograph) {
String ming = "";
try {
/** 将文件中的私钥对象读出 */
ObjectInputStream ois = new ObjectInputStream(RSAEncryptUtil.class.getResourceAsStream("/rsa/" + PRIVATE_KEY_FILE));
Key key = (Key) ois.readObject();
/** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
int key_len = KEYSIZE / 8;
byte[] bytes = cryptograph.getBytes();
byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
System.err.println(bcd.length);
byte[][] arrays = splitArray(bcd, key_len);
for (byte[] arr : arrays) {
ming += new String(cipher.doFinal(arr));
}
} catch (Exception e) {
e.printStackTrace();
}
return ming;
}
/**
*
*/
public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {
byte[] bcd = new byte[asc_len / 2];
int j = 0;
for (int i = 0; i < (asc_len + 1) / 2; i++) {
bcd[i] = asc_to_bcd(ascii[j++]);
bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));
}
return bcd;
}
public static byte asc_to_bcd(byte asc) {
byte bcd;
if ((asc >= '0') && (asc <= '9'))
bcd = (byte) (asc - '0');
else if ((asc >= 'A') && (asc <= 'F'))
bcd = (byte) (asc - 'A' + 10);
else if ((asc >= 'a') && (asc <= 'f'))
bcd = (byte) (asc - 'a' + 10);
else
bcd = (byte) (asc - 48);
return bcd;
}
/**
*/
public static byte[][] splitArray(byte[] data, int len) {
int x = data.length / len;
int y = data.length % len;
int z = 0;
if (y != 0) {
z = 1;
}
byte[][] arrays = new byte[x + z][];
byte[] arr;
for (int i = 0; i < x + z; i++) {
arr = new byte[len];
if (i == x + z - 1 && y != 0) {
System.arraycopy(data, i * len, arr, 0, y);
} else {
System.arraycopy(data, i * len, arr, 0, len);
}
arrays[i] = arr;
}
return arrays;
}
public static String getpublickey() throws Exception {
/** 将文件中的公钥对象读出 */
ObjectInputStream ois = new ObjectInputStream(RSAEncryptUtil.class.getResourceAsStream("/rsa/" + PUBLIC_KEY_FILE));
Key key = (Key) ois.readObject();
String publickey = encryptBASE64(key.getEncoded());
return publickey;
}
public static String getprivatekey() throws Exception {
/** 将文件中的私钥对象读出 */
ObjectInputStream ois = new ObjectInputStream(RSAEncryptUtil.class.getResourceAsStream("/rsa/" + PRIVATE_KEY_FILE));
Key key = (Key) ois.readObject();
String privatekey = encryptBASE64(key.getEncoded());
return privatekey;
}
public static void main(String[] args)throws Exception {
// RSA_Encrypt.generateKeyPair();
String source ="1fgdgdg";// 要加密的字符串
String cryptograph = RSAEncryptUtil.encrypt(source);// 生成的密文
System.out.println("加密的秘文" + cryptograph);
String target = RSAEncryptUtil.decrypt(cryptograph);// 解密密文
System.out.println("解密之后的明文是:"+target);
// byte[]bytes =source.getBytes();
// // 产生签名
// String sign = RSAEncryptUtil.sign(bytes, RSAEncryptUtil.getprivatekey());
// System.err.println("签名:" +sign);
// // 验证签名
// boolean status = RSAEncryptUtil.verify(bytes, RSAEncryptUtil.getpublickey(),sign);
// System.err.println("状态:" +status);
}
}
场景:是在登录时使用的:
//登录时加密得到令牌:
String token = RSAEncryptUtil.encrypt(result.getAccount());
//访问时在切面上解密,并在数据库中查询对应账户是否存在:
String accountDe = RSAEncryptUtil.decrypt(accountEny);
User user = userService.selectById(Long.valueOf(accountDe));
注意:在使用时应该先生成秘钥对