常见加密算法比较与学习,工具类

1.散列算法

名称安全性速度
SHA-1
MD5

2.对称加密算法

名称秘钥名称速度安全性资源消耗
DES56位较快
3DES112位或168位
AES128、192、256位

3.非对称加密算法

名称成熟度安全性速度资源消耗
RSA
ECC

4.SnowFlake算法id生成算法

JAVA SHA1

/**
* SHA1不可逆加密工具
*/
public class Sha1Util {

	public static String getSha1(byte[] input) throws NoSuchAlgorithmException{
		MessageDigest mDigest = MessageDigest.getInstance("SHA1");
        byte[] result = mDigest.digest(input);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < result.length; i++) {
            sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
	}

}

JAVA MD5

/**
 * MD5不可逆加密工具类
 * 
 */
public class Md5Utils {

	/** 全局数组 **/
	private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
			"E", "F" };

	/**
	 * 返回形式为数字跟字符串
	 * 
	 * @param bByte
	 * @return
	 */
	private static String byteToArrayString(byte bByte) {
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return strDigits[iD1] + strDigits[iD2];
	}

	/**
	 * 转换字节数组为16进制字串
	 * 
	 * @param bByte
	 * @return
	 */
	private static String byteToString(byte[] bByte) {
		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < bByte.length; i++) {
			sBuffer.append(byteToArrayString(bByte[i]));
		}
		return sBuffer.toString();
	}

	/**
	 * MD5加密
	 * 
	 * @param str
	 *            待加密的字符串
	 * @return
	 */
	public static String GetMD5Code(String str) {
		String result = null;
		try {
			result = new String(str);
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byteToString(md.digest(str.getBytes()));
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
		return result;
	}

	/**
	 * MD5加密
	 * 
	 * @param str
	 *            待加密的字符串
	 * @param lowerCase
	 *            大小写
	 * @return
	 */
	public static String GetMD5Code(String str, boolean lowerCase) {
		String result = null;
		try {
			result = new String(str);
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byteToString(md.digest(str.getBytes()));
			if (lowerCase) {
				result = result.toLowerCase();
			}
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
		return result;
	}

}

JAVA AES

/**
 * AES加密工具  模式:ECB  补码方式:PKCS5Padding
 * @author Administrator
 *
 */
public class AESUtils {

	private static Logger log = LoggerFactory.getLogger(AESUtils.class);
	private static String Algorithm = "AES";
	private static String AlgorithmProvider = "AES/ECB/PKCS5Padding"; // 算法/模式/补码方式
	/**
	 * 得到转换为16进制字符串的加密字符串
	 * @param src
	 * @param key  必须为16个字符(1234567887654321)
	 * @return
	 * @throws InvalidKeyException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 * @throws UnsupportedEncodingException
	 * @throws InvalidAlgorithmParameterException
	 */
	public static String getHexStr(String src, byte[] key)
			throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException,
			BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
		return parseByte2HexStr(encrypt(src, key));
	}
	/**
	 * 转换16进制加密字符串变为未加密字符串
	 * @param src
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String getSrcStr(String src, byte[] key) throws Exception {
		return new String(decrypt(src, key), "utf-8");
	}

	public static byte[] encrypt(String src, byte[] key)
			throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
			BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
		SecretKey secretKey = new SecretKeySpec(key, Algorithm);
		// IvParameterSpec ivParameterSpec = getIv();
		Cipher cipher = Cipher.getInstance(AlgorithmProvider);
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8")));
		return cipherBytes;
	}

	public static byte[] decrypt(String src, byte[] key) throws Exception {
		SecretKey secretKey = new SecretKeySpec(key, Algorithm);

		// IvParameterSpec ivParameterSpec = getIv();
		Cipher cipher = Cipher.getInstance(AlgorithmProvider);
		cipher.init(Cipher.DECRYPT_MODE, secretKey);
		byte[] hexBytes = parseHexStr2Byte(src);
		byte[] plainBytes = cipher.doFinal(hexBytes);
		return plainBytes;
	}

	/**
	 * 将二进制转换成十六进制
	 * 
	 * @param buf
	 * @return
	 */
	private static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将十六进制转换为二进制
	 * 
	 * @param hexStr
	 * @return
	 */
	private static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1) {
			return null;
		} else {
			byte[] result = new byte[hexStr.length() / 2];
			for (int i = 0; i < hexStr.length() / 2; i++) {
				int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
				int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
				result[i] = (byte) (high * 16 + low);
			}
			return result;
		}
	}
}

/**
 * AES加密工具  模式:CBC  补码方式:PKCS5Padding
 * @author Administrator
 *
 */
public class AESCBCUtils {
	// 加密
	public static String encrypt(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		byte[] raw = sKey.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(sSrc.getBytes(encodingFormat));
		return parseByte2HexStr(encrypted);// 此处使用BASE64做转码。
	}
	
	 public static String decrypt(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
	        try {
	            byte[] raw = sKey.getBytes("utf-8");
	            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
	            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
	            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
	            byte[] encrypted1 = parseHexStr2Byte(sSrc);//先用base64解密
	            byte[] original = cipher.doFinal(encrypted1);
	            String originalString = new String(original,encodingFormat);
	            return originalString;
	        } catch (Exception ex) {
	            return null;
	        }
	}

	/**
	 * 将二进制转换成十六进制
	 * 
	 * @param buf
	 * @return
	 */
	private static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}
	
	/**
	 * 将十六进制转换为二进制
	 * 
	 * @param hexStr
	 * @return
	 */
	private static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1) {
			return null;
		} else {
			byte[] result = new byte[hexStr.length() / 2];
			for (int i = 0; i < hexStr.length() / 2; i++) {
				int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
				int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
				result[i] = (byte) (high * 16 + low);
			}
			return result;
		}
	}
}

JAVA SnowFlake算法id生成算法

/**
 * twitter的snowflake算法 -- java实现
 * 
 */
public class SnowFlake {

    /**
     * 起始的时间戳
     */
    private final static long START_STMP = 1480166465631L;

    /**
     * 每一部分占用的位数
     */
    private final static long SEQUENCE_BIT = 12; //序列号占用的位数
    private final static long MACHINE_BIT = 5;   //机器标识占用的位数
    private final static long DATACENTER_BIT = 5;//数据中心占用的位数

    /**
     * 每一部分的最大值
     */
    private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
    private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);

    /**
     * 每一部分向左的位移
     */
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    private long datacenterId =2L;  //数据中心
    private long machineId= 3L;     //机器标识
    private long sequence = 0L; //序列号
    private long lastStmp = -1L;//上一次时间戳

    public SnowFlake(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
    }

    /**
     * 产生下一个ID
     *
     * @return
     */
    public synchronized long nextId() {
        long currStmp = getNewstmp();
        if (currStmp < lastStmp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }

        if (currStmp == lastStmp) {
            //相同毫秒内,序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStmp = getNextMill();
            }
        } else {
            //不同毫秒内,序列号置为0
            sequence = 0L;
        }

        lastStmp = currStmp;

        return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
                | datacenterId << DATACENTER_LEFT       //数据中心部分
                | machineId << MACHINE_LEFT             //机器标识部分
                | sequence;                             //序列号部分
    }

    private long getNextMill() {
        long mill = getNewstmp();
        while (mill <= lastStmp) {
            mill = getNewstmp();
        }
        return mill;
    }

    private long getNewstmp() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {
        SnowFlake snowFlake = new SnowFlake(2, 3);
        long currentTimeMillis = System.currentTimeMillis();
       
        for (int i = 0; i < 10000; i++) {
            System.out.println(String.valueOf(snowFlake.nextId()));
        }
        System.out.println(System.currentTimeMillis()-currentTimeMillis);
    }
}

JAVA RSA非对称加解密 原理没看并且对相同字符串加密每次都不同但是都能解出来需看原理去理解

public class H5RSAUtil {

    /**
     * 密钥长度(bit)
     */
    public static final int KEY_LENGTH = 1024;

    public static final int MAX_ENCRYPT_BLOCK = 117;
    /**
     * <p>
     * 单次解密最大密文长度,这里仅仅指1024bit 长度密钥
     * </p>
     *
     * @see #MAX_ENCRYPT_BLOCK
     */
    public static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 加密
     */
    // public static final String SIGN_TYPE_RSA = "RSA";

    /**
     * 加密算法
     */
    public static final String ALGORITHM_RSA = "RSA";

    /**
     * 算法/模式/填充
     */
    public static final String CIPHER_TRANSFORMATION_RSA = "RSA/ECB/PKCS1Padding";

    /**
     * 签名算法
     */
    public static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    /** UTF-8字符集 **/
    public static final String CHARSET_UTF8 = "UTF-8";

    /** GBK字符集 **/
    public static final String CHARSET_GBK = "GBK";

    public static final String CHARSET = CHARSET_UTF8;

    /**
     * 得到公钥
     *
     * @param key
     *            密钥字符串(经过base64编码)
     * @param charset
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key, String charset)
            throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key.getBytes(charset));

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 得到私钥
     *
     * @param key
     *            密钥字符串(经过base64编码)
     * @param charset
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String key, String charset)
            throws Exception {
        byte[] keyBytes;
        keyBytes = Base64.decodeBase64(key.getBytes(charset));

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * 得到密钥字符串(经过base64编码)
     *
     * @return
     */
    public static String getKeyString(Key key) throws Exception {
        byte[] keyBytes = key.getEncoded();
        String s = new String(Base64.encodeBase64(keyBytes), CHARSET);
        return s;
    }

    /**
     *
     * 公钥加密
     *
     * @param content
     *            待加密内容
     * @param publicKey
     *            公钥
     * @param charset
     *            字符集,如UTF-8, GBK, GB2312
     * @return 密文内容
     * @throws Exception
     */
    public static String rsaEncrypt(String content, String publicKey,
                                    String charset) throws Exception {
        try {
            PublicKey pubKey = getPublicKey(publicKey, charset);
            Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION_RSA);
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] data = StringUtils.isEmpty(charset) ? content.getBytes()
                    : content.getBytes(charset);
            int inputLen = data.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, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = Base64.encodeBase64(out.toByteArray());
            out.close();

            return StringUtils.isEmpty(charset) ? new String(encryptedData)
                    : new String(encryptedData, charset);
        } catch (Exception e) {
            throw new Exception(
                    "error occured in rsaEncrypt: EncryptContent = " + content
                            + ",charset = " + charset, e);
        }
    }

    /**
     *
     * 公钥加密
     *
     * @param content
     *            待加密内容
     * @param publicKey
     *            公钥
     * @return 密文内容
     * @throws Exception
     */
    public static String rsaEncrypt(String content, String publicKey)
            throws Exception {
        return rsaEncrypt(content, publicKey, H5RSAUtil.CHARSET);
    }

    /**
     * 私钥解密
     *
     * @param content
     *            待解密内容
     * @param privateKey
     *            私钥
     * @param charset
     *            字符集,如UTF-8, GBK, GB2312
     * @return 明文内容
     * @throws Exception
     */
    public static String rsaDecrypt(String content, String privateKey,
                                    String charset) throws Exception {
        try {
            PrivateKey priKey = getPrivateKey(privateKey, charset);
            Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION_RSA);
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            byte[] encryptedData = StringUtils.isEmpty(charset) ? Base64
                    .decodeBase64(content.getBytes()) : Base64
                    .decodeBase64(content.getBytes(charset));
            int inputLen = encryptedData.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(encryptedData, offSet,
                            MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen
                            - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();

            return StringUtils.isEmpty(charset) ? new String(decryptedData)
                    : new String(decryptedData, charset);
        } catch (Exception e) {
            throw new Exception("error occured in rsaDecrypt: EncodeContent = "
                    + content + ",charset = " + charset, e);
        }
    }

    /**
     * 私钥解密
     *
     * @param content
     *            待解密内容
     * @param privateKey
     *            私钥
     * @return 明文内容
     * @throws Exception
     */
    public static String rsaDecrypt(String content, String privateKey)
            throws Exception {
        return rsaDecrypt(content, privateKey, H5RSAUtil.CHARSET);
    }

    /**
     * 获得密钥对
     *
     * @Title creatKeyPair
     * @Description TODO
     * @return
     * @throws NoSuchAlgorithmException
     *             KeyPair
     */
    public static KeyPair creatKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(H5RSAUtil.ALGORITHM_RSA);
        // 密钥位数
        keyPairGen.initialize(KEY_LENGTH);
        // 密钥对
        KeyPair keyPair = keyPairGen.generateKeyPair();
        return keyPair;
    }

    public static void main(String[] args) throws Exception{
        KeyPair keyPair = creatKeyPair();
        System.out.println("生成公钥");
        PublicKey publicKey = getPublicKey(new BASE64Encoder().encode(keyPair.getPublic().getEncoded()), "utf-8");
        String publicKeyStr = new BASE64Encoder().encode(publicKey.getEncoded());
        System.out.println(publicKeyStr);
        System.out.println("=============");
        System.out.println("生成私钥");
        PrivateKey privateKey = getPrivateKey(new BASE64Encoder().encode(keyPair.getPrivate().getEncoded()), "utf-8");
        String privateKeyStr = new BASE64Encoder().encode(privateKey.getEncoded());

        System.out.println(privateKeyStr);
        String strEncrpt = rsaEncrypt("abcd", publicKeyStr, "utf-8");
        System.out.println("密文===" + strEncrpt);
        String content = rsaDecrypt(strEncrpt, privateKeyStr, "utf-8");
        System.out.println("解密===" + content);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值