数据加密技术篇

本文深入解析了加密领域的核心算法,包括对称加密如DES、3DES、Blowfish,非对称加密如RSA、ECC,以及摘要算法MD5、SHA-1。通过Java代码示例,详细阐述了这些算法的工作原理及实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	 这几年接触了一些加密技术,在这里做个总结,主要是加密算法(对称加密和非对称加密)和摘要算法。这里主要是结合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;
		        else
		            hs = 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);
		}
		
		//测试方法main
		public 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(); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值