本文主要是介绍数据加密技术篇,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这几年接触了一些加密技术,在这里做个总结,主要是加密算法(对称加密和非对称加密)和摘要算法。这里主要是结合Java代码讲解常见的 对称加密(DES)、非对称加密(RSA)、摘要算法(MD5)
对称加密:DES,3DES,TDEA,Blowfish,RC5,IDEA等。
非对称加密:RSA、Elgamal、背包算法、Rabin、D-H、ECC等
摘要算法:MD5算法和SHA-1算法等
对称加密(DES):对称加密算法是应用较早的加密算法,技术成熟。在对称加密算法中,使用的密钥只有一个,发收信双方都使用这个密钥对数据进行加密和解密,这就要求解密方事先必须知道加密密钥。
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;public class DesUtils { private static final String DES = "DES";private static final String ***KEY*** = "3YxxxxxxxxxZF"; //自定义private DesUtils() {}private static byte[] encrypt(byte[] src, byte[] key) throws Exception {SecureRandom sr = new SecureRandom();DESKeySpec dks = new DESKeySpec(key);SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);SecretKey secretKey = keyFactory.generateSecret(dks);Cipher cipher = Cipher.getInstance(DES);cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);return cipher.doFinal(src);}private static byte[] decrypt(byte[] src, byte[] key) throws Exception {SecureRandom sr = new SecureRandom();DESKeySpec dks = new DESKeySpec(key);SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);SecretKey secretKey = keyFactory.generateSecret(dks);Cipher cipher = Cipher.getInstance(DES);cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);return cipher.doFinal(src);}private static String byte2hex(byte[] b) {String hs = "";String temp = "";for (int n = 0; n < b.length; n++) {temp = (java.lang.Integer.toHexString(b[n] & 0XFF));if (temp.length() == 1)hs = hs + "0" + temp;elsehs = hs + temp;}return hs.toUpperCase();}private static byte[] hex2byte(byte[] b) {if ((b.length % 2) != 0)throw new IllegalArgumentException("length not even");byte[] b2 = new byte[b.length / 2];for (int n = 0; n < b.length; n += 2) {String item = new String(b, n, 2);b2[n / 2] = (byte) Integer.parseInt(item, 16);}return b2;}private static String decode(String src, String key) {String decryptStr = "";try {byte[] decrypt = decrypt(hex2byte(src.getBytes()), key.getBytes());decryptStr = new String(decrypt);} catch (Exception e) {e.printStackTrace();}return decryptStr;}private static String encode(String src, String key){byte[] bytes = null;String encryptStr = "";try {bytes = encrypt(src.getBytes(), key.getBytes());} catch (Exception ex) {ex.printStackTrace();}if (bytes != null)encryptStr = byte2hex(bytes);return encryptStr;}/*** 解密*/public static String decode(String src) {return decode(src, KEY);}/*** 加密*/public static String encode(String src) {return encode(src, KEY);}//测试方法mainpublic static void main(String[] args) {String ss = "dawng";String encodeSS = encode(ss);System.out.println(encodeSS);String decodeSS = decode(encodeSS);System.out.println(decodeSS);}
}
非对称加密(RSA):非对称加密算法需要两个密钥:公开密钥(publickey:简称公钥)和私有密钥(privatekey:简称私钥)。公钥与私钥是一对,如果用公钥对数据进行加密,只有用对应的私钥才能解密。
注:RSA加密除了公钥私钥,还有秘钥的长度有关。
(如果不想用签名可以注释掉签名部分即可)
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;public class RSAUtils{public static final String KEY_ALGORITHM="RSA";public static final String SIGNATURE_ALGORITHM="MD5withRSA";private static final int KEY_SIZE=1024; //长度和加密时一致private static final String PUBLIC_KEY="RSAPublicKey";private static final String PRIVATE_KEY="RSAPrivateKey";public static String str_pubK = "MIGxxxxxxxxxxxxx8="; //和前端加密的私钥对应起来/*** 使用getPublicKey得到公钥,返回类型为PublicKey* @param base64 String to PublicKey* @throws Exception*/public static PublicKey getPublicKey(String key) throws Exception {byte[] keyBytes;keyBytes = (new BASE64Decoder()).decodeBuffer(key);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PublicKey publicKey = keyFactory.generatePublic(keySpec);return publicKey;}/*** 转换私钥* @param base64 String to PrivateKey* @throws Exception*/public static PrivateKey getPrivateKey(String key) throws Exception {byte[] keyBytes;keyBytes = (new BASE64Decoder()).decodeBuffer(key);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PrivateKey privateKey = keyFactory.generatePrivate(keySpec);return privateKey;}//***************************签名和验证*******************************public static byte[] sign(byte[] data) throws Exception{PrivateKey priK = getPrivateKey(str_priK);Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initSign(priK);sig.update(data);return sig.sign();}public static boolean verify(byte[] data,byte[] sign) throws Exception{PublicKey pubK = getPublicKey(str_pubK);Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);sig.initVerify(pubK);sig.update(data);return sig.verify(sign);}//************************加密解密**************************public static byte[] encrypt(byte[] bt_plaintext)throws Exception{PublicKey publicKey = getPublicKey(str_pubK);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] bt_encrypted = cipher.doFinal(bt_plaintext);return bt_encrypted;}public static byte[] decrypt(byte[] bt_encrypted)throws Exception{PrivateKey privateKey = getPrivateKey(str_priK);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] bt_original = cipher.doFinal(bt_encrypted);return bt_original;}//********************main函数:加密解密和签名验证*********************public static void main(String[] args) throws Exception {String str_plaintext = "这是一段用来测试密钥转换的明文";System.err.println("明文结果:"+str_plaintext);byte[] bt_cipher = encrypt(str_plaintext.getBytes());System.out.println("加密后结果:"+Base64.encodeBase64String(bt_cipher));byte[] bt_original = decrypt(bt_cipher);String str_original = new String(bt_original);System.out.println("解密结果:"+str_original);String str="被签名的内容";System.err.println("\n原文:"+str);byte[] signature=sign(str.getBytes());System.out.println("产生签名值:"+Base64.encodeBase64String(signature));boolean status=verify(str.getBytes(), signature);System.out.println("验证结果:"+status);}}
摘要加密(MD5):消息摘要算法的主要特征是加密过程不需要密钥,并且经过加密的数据无法被解密,目前可以被解密逆向的只有CRC32算法,只有输入相同的明文数据经过相同的消息摘要算法才能得到相同的密文。
注:项目配置一个shiro的jar即可
导入 import org.apache.shiro.crypto.hash.Md5Hash;注册时对用户输入的密码继续MD5加密,将加密的密码存入数据库// 密码 盐值 搅拌次数
Md5Hash mh = new Md5Hash(Password,"yanzhi",3);
Password = mh.toString(); 登录时对用户登录的密码进行相同加密,用加密后的值与数据库中加密的密码继续匹配
Md5Hash mh = new Md5Hash(Password,"yanzhi",3);
Password = mh.toString();
这篇关于数据加密技术篇的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!