java之--加密、解密算法

0、概述

在项目开发中,我们常需要用到加解密算法,加解密算法主要分为三大类:

1、对称加密算法,如:AESDES3DES

2、非对称加密算法,如:RSADSAECC

3、散列算法,如:MD5SHA1HMAC

 

1、各算法对比

不废话,直接开表格对比:

对称加密算法(加解密密钥相同)

名称

密钥长度

运算速度

安全性

资源消耗

DES

56位

较快

3DES

112位或168位

AES

128、192、256位

 

非对称算法(加密密钥和解密密钥不同)

名称

成熟度

安全性(取决于密钥长度)

运算速度

资源消耗

RSA

DSA

只能用于数字签名

ECC

低(计算量小,存储空间占用小,带宽要求低)

 

散列算法比较

名称

安全性

速度

SHA-1

MD5

 

对称与非对称算法比较

名称

密钥管理

安全性

速度

对称算法

比较难,不适合互联网,一般用于内部系统

快好几个数量级(软件加解密速度至少快100倍,每秒可以加解密数M比特数据),适合大数据量的加解密处理

非对称算法

密钥容易管理

慢,适合小数据量加解密或数据签名

3、项目中常用总结

对称加密: AES(128位),

非对称加密: ECC(160位)或RSA(1024),

消息摘要: MD5

数字签名:DSA

其中,AES和MD5最为常用,

 

4、代码示例

下面直接实现一个包含AES和MD5的加解密类,不废话,直接上步骤:

1、添加第三方包的依赖:项目用到两个第三方包,在pom中添加这两个包的依赖:

<!-- 添加加解密算法的依赖 --> 
<dependency> 
    <groupId>org.apache.commons</groupId> 
    <artifactId>commons-lang3</artifactId> 
    <version>3.4</version> 
</dependency> 
<dependency> 
    <groupId>org.apache.directory.studio</groupId>             
    <artifactId>org.apache.commons.codec</artifactId> 
    <version>1.8</version> 
</dependency>    

2、import相关包;

3、AES有五种模式(ECB、CBC、CFB、OFB、CTR),我们采用的是CBC,各工作模式的远离自行百度,好了,直接上代码:

package com.anson.utility;

//引入相关包
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

//引入第三方包
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;


public class Encrypt {

    //--------------AES---------------
    private static final String KEY = "f4k9f5w7f8g4er26";  // 密匙,必须16位
    private static final String OFFSET = "5e8y6w45ju8w9jq8"; // 偏移量
    private static final String ENCODING = "UTF-8"; // 编码
    private static final String ALGORITHM = "AES"; //算法
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; // 默认的加密算法,CBC模式

    //---------------MD5-------------------
    private static final String MD5KEY = "f4k9f5w7f8g4er26";  // 密匙

    /**
     *  AES加密
     * @param data
     * @return String
     * @author anson
     * @date   2019-8-24 18:43:07
     */
    public static String AESencrypt(String data) throws Exception
    {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());//CBC模式偏移量IV
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(data.getBytes(ENCODING));
        return new Base64().encodeToString(encrypted);//加密后再使用BASE64做转码
    }

    /**
     * AES解密
     * @param data
     * @return String
     * @author anson
     * @date   2019-8-24 18:46:07
     */
    public static String AESdecrypt(String data) throws Exception
    {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes()); //CBC模式偏移量IV
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] buffer = new Base64().decode(data);//先用base64解码
        byte[] encrypted = cipher.doFinal(buffer);
        return new String(encrypted, ENCODING);
    }

    //---------------------MD5--------------------
    /**
     * MD5方法
     * @param text 明文
     * @return 密文
     * @author anson
     * @date 2019-8-24 18:54:42
     */
    public static String MD5encrypt(String text) throws Exception {
        //加密后的字符串
        String encodeStr=DigestUtils.md5Hex(text + MD5KEY);
        return encodeStr;
    }

    /**
     * MD5验证方法
     * @param text 明文
     * @param md5 密文
     * @return true/false
     * @author anson
     * @date 2019-8-24 18:58:56
     */
    public static boolean verify(String text, String md5) throws Exception
    {
        //根据传入的密钥进行验证
        String md5Text = MD5encrypt(text);
        if(md5Text.equalsIgnoreCase(md5))
        {
            return true;
        }
        return false;
    }

}

 

转载于:https://www.cnblogs.com/yanghj/p/11405776.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
文件加密解密算法(Java源码) java,file,算法,加密解密,java源码 package com.crypto.encrypt; import java.security.SecureRandom; import java.io.*; import javax.crypto.spec.DESKeySpec; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.Cipher; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.NoSuchPaddingException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import java.lang.reflect.Constructor; import java.security.spec.KeySpec; import java.lang.reflect.InvocationTargetException; public class EncryptData { private String keyfile=null; public EncryptData() { } public EncryptData(String keyfile) { this.keyfile=keyfile; } /** * 加密文件 * @param filename String 源路径 * @param filenamekey String 加密后的路径 */ public void createEncryptData(String filename,String filenamekey) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException { //验证keyfile if(keyfile==null || keyfile.equals("")) { throw new NullPointerException("无效的key文件路径"); } encryptData(filename,filenamekey); } /** * 加密类文件 * @param filename String 原始的类文件 * @param encryptfile String 加密后的类文件 * @throws IOException * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws IllegalStateException */ private void encryptData(String filename,String encryptfile) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, IllegalStateException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException { byte data[]=Util.readFile(filename); // 执行加密操作 byte encryptedClassData[] = getencryptData(data); // 保存加密后的文件,覆盖原有的类文件。 Util.writeFile(encryptedClassData,encryptfile); } /** * 直接获得加密数据 * @param bytes byte[] * @throws IllegalStateException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws InstantiationException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws SecurityException * @throws ClassNotFoundException * @throws IOException * @return byte[] */ public byte[] createEncryptData(byte[] bytes) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IOException { bytes=getencryptData(bytes); return bytes; } private byte[] getencryptData(byte[] bytes) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IllegalStateException { // 产生一个可信任的随机数源 SecureRandom sr = new SecureRandom(); //从密钥文件key Filename中得到密钥数据 byte[] rawKeyData = Util.readFile(keyfile); // 从原始密钥数据创建DESKeySpec对象 Class classkeyspec=Class.forName(Util.getValue("keyspec")); Constructor constructor = classkeyspec.getConstructor(new Class[]{byte[].class}); KeySpec dks = (KeySpec) constructor.newInstance(new Object[]{rawKeyData}); // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Util.getAlgorithm()); SecretKey key = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(Util.getAlgorithm()); // 用密钥初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, key, sr); // 执行加密操作 bytes = cipher.doFinal(bytes); // 返回字节数组 return bytes; } /** * 设置key文件路径 * @param keyfile String */ public void setKeyFile(String keyfile) { this.keyfile=keyfile; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值