自定义加密工具类 EncryptionUtils.java

自定义加密工具类 EncryptionUtils.java

简介

  • 包括 RSAUtil.java 、UUIDUtil.java 、MD5Util.java

api

MD5Util

  • 明文加密 md5(String text);
  • 带密钥加密 md5(String text, String key);
  • MD5验证方法,根据传入的密钥进行验证 verify(String text, String key, String md5);

UUIDUtil

  • 返回32位UUID createUUID();

RSAUtil

  • 获取密钥对 getKeyPair();
  • 获取私钥 getPrivateKey(String privateKey);
  • 获取公钥 getPublicKey(String publicKey);
  • RSA加密 encrypt(String data, PublicKey publicKey);
  • RSA解密 decrypt(String data, PrivateKey privateKey);
  • 签名 sign(String data, PrivateKey privateKey);
  • 验签 verify(String srcData, PublicKey publicKey, String sign);

源码

  • import java.io.ByteArrayOutputStream;
    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.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.UUID;
     
    import javax.crypto.Cipher;
     
    import org.apache.commons.codec.binary.Base64;
    import org.apache.commons.codec.digest.DigestUtils;
     
    /**
     * @说明:加密技术
     */
    public class EncryptionUtils {
    	
    	public static void main(String[] args) throws Exception {
    //        // 生成密钥对
            KeyPair keyPair = RSAUtil.getKeyPair();
            String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
            String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            System.out.println("私钥: " + privateKey);
            System.out.println("公钥: " + publicKey);
            // RSA加密
    //        String data = "待加密的文字内容[love]";
    //        String encryptData = RSAUtil.encrypt(data, RSAUtil.getPublicKey(publicKey));
    //        System.out.println("加密后内容: " + encryptData);
    //        // RSA解密
    //        String decryptData = RSAUtil.decrypt(encryptData, RSAUtil.getPrivateKey(privateKey));
    //        System.out.println("解密后内容: " + decryptData);
    //
    //        // RSA签名
    //        String sign = RSAUtil.sign(data, RSAUtil.getPrivateKey(privateKey));
    //        // RSA验签
    //        boolean result = RSAUtil.verify(data, RSAUtil.getPublicKey(publicKey), sign);
    //        System.out.print("验签结果:" + result);
    		
    //		System.out.println(UUIDUtil.createUUID());
    //		System.out.println(UUIDUtil.createUUID());
        }
    	
    	/** 依赖 rt.jar、commons-codec.jar */
    	public static class RSAUtil {
    		//公钥加密、私钥解密、私钥签名、公钥验签
    		
    	    /** RSA最大加密明文大小 */
    	    private static final int MAX_ENCRYPT_BLOCK = 117;
     
    	    /** RSA最大解密密文大小 */
    	    private static final int MAX_DECRYPT_BLOCK = 128;
     
    	    /**
    	     * 方法功能说明:@1.获取密钥对
    	     */
    	    public static KeyPair getKeyPair() throws Exception {
    	        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
    	        generator.initialize(1024);
    	        return generator.generateKeyPair();
    	    }
     
    	    /**
    	     * 方法功能说明:@1.获取私钥
    	     * @参数: @param privateKey 私钥字符串
    	     */
    	    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
    	        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    	        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
    	        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
    	        return keyFactory.generatePrivate(keySpec);
    	    }
     
    	    /**
    	     * 方法功能说明:@1.获取公钥
    	     * @参数: @param publicKey 公钥字符串
    	     */
    	    public static PublicKey getPublicKey(String publicKey) throws Exception {
    	        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    	        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
    	        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
    	        return keyFactory.generatePublic(keySpec);
    	    }
     
    	    /**
    	     * 方法功能说明:@1.RSA加密
    	     * @参数: @param data 待加密数据
    	     * @参数: @param publicKey 公钥
    	     */
    	    public static String encrypt(String data, PublicKey publicKey) throws Exception {
    	        Cipher cipher = Cipher.getInstance("RSA");
    	        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    	        int inputLen = data.getBytes().length;
    	        ByteArrayOutputStream out = new ByteArrayOutputStream();
    	        int offset = 0;
    	        byte[] cache;
    	        int i = 0;
    	        // 对数据分段加密
    	        while (inputLen - offset > 0) {
    	            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
    	                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
    	            } else {
    	                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
    	            }
    	            out.write(cache, 0, cache.length);
    	            i++;
    	            offset = i * MAX_ENCRYPT_BLOCK;
    	        }
    	        byte[] encryptedData = out.toByteArray();
    	        out.close();
    	        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
    	        // 加密后的字符串
    	        return new String(Base64.encodeBase64String(encryptedData));
    	    }
     
    	    /**
    	     * 方法功能说明:@1.RSA解密
    	     * @参数: @param data 待解密数据
    	     * @参数: @param privateKey 私钥
    	     */
    	    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
    	        Cipher cipher = Cipher.getInstance("RSA");
    	        cipher.init(Cipher.DECRYPT_MODE, privateKey);
    	        byte[] dataBytes = Base64.decodeBase64(data);
    	        int inputLen = dataBytes.length;
    	        ByteArrayOutputStream out = new ByteArrayOutputStream();
    	        int offset = 0;
    	        byte[] cache;
    	        int i = 0;
    	        // 对数据分段解密
    	        while (inputLen - offset > 0) {
    	            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
    	                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
    	            } else {
    	                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
    	            }
    	            out.write(cache, 0, cache.length);
    	            i++;
    	            offset = i * MAX_DECRYPT_BLOCK;
    	        }
    	        byte[] decryptedData = out.toByteArray();
    	        out.close();
    	        // 解密后的内容
    	        return new String(decryptedData, "UTF-8");
    	    }
     
    	    /**
    	     * 方法功能说明:@1. 签名
    	     * @参数: @param data 待签名数据
    	     * @参数: @param privateKey 私钥
    	     */
    	    public static String sign(String data, PrivateKey privateKey) throws Exception {
    	        byte[] keyBytes = privateKey.getEncoded();
    	        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    	        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    	        PrivateKey key = keyFactory.generatePrivate(keySpec);
    	        Signature signature = Signature.getInstance("MD5withRSA");
    	        signature.initSign(key);
    	        signature.update(data.getBytes());
    	        return new String(Base64.encodeBase64(signature.sign()));
    	    }
     
    	    /**
    	     * 方法功能说明:@1.验签
    	     * @参数: @param srcData 原始字符串
    	     * @参数: @param publicKey 公钥
    	     * @参数: @param sign 签名
    	     */
    	    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
    	        byte[] keyBytes = publicKey.getEncoded();
    	        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    	        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    	        PublicKey key = keyFactory.generatePublic(keySpec);
    	        Signature signature = Signature.getInstance("MD5withRSA");
    	        signature.initVerify(key);
    	        signature.update(srcData.getBytes());
    	        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    	    }
     
    	}
    	
    	/** 依赖 rt.jar */
    	public static class UUIDUtil {
    		
    		/**
    		 * 方法功能说明:@1.返回32位UUID
    		 */
    		public static String createUUID() {
    			return UUID.randomUUID().toString().replace("-", "");
    		}
    		
    	}
    	
    	/** 依赖 commons-codec.jar */
    	public static class MD5Util {
    		
    		/**
    		 * 方法功能说明:@1.带秘钥加密
    		 * @param text明文
    		 * @param key密钥
    		 * @return 32位密文
    		 */
    		public static String md5(String text, String key) throws Exception {
    			if (key == null) { key = ""; }
    			return DigestUtils.md5Hex(text + key);
    		}
     
    		/**
    		 * 方法功能说明:@1.明文加密
    		 * @param text明文
    		 * @return 32位密文
    		 * 创建时间:2020年8月31日 上午10:51:40 --lud
    		 */
    		public static String md5(String text) throws Exception {
    			return DigestUtils.md5Hex(text);
    		}
     
    		/**
    		 * 方法功能说明:@1.MD5验证方法,根据传入的密钥进行验证
    		 * @param text明文
    		 * @param key密钥
    		 * @param md5密文
    		 */
    		public static boolean verify(String text, String key, String md5) throws Exception {
    			String md5str = md5(text, key);
    			if (md5str.equalsIgnoreCase(md5)) {
    				return true;
    			}
    			return false;
    		}
     
    	}
    
    }
    

你可能感兴趣的:(JAVA基础工作中实际总结,编程学习,软件,java,python,开发语言)