JAVA实现对称加密

JAVA实现对称加密

对称加密算法

1、初等

2、DES (常见的)

DES(Data Encryption Standard) 数据加密标准

密钥长度

默认

工作模式

填充方式

实现方

56

56

ECBCBCPCBCCTRCTS

CFBCFB8 128OFBOFB8 128

NOPadding

PKCS5Padding

ISO10126Padding

JDK

64

56

同上

PKCS7Padding

ISO10126d2Padding

X932Padding

ISO7816d4Padding

ZeroBytePadding

BC

 

例子:

package des;
import org.apache.tomcat.util.buf.HexUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;

/**
 * Created by gailun on 2018/3/30.
 */
public class DES {
    private static String src = "security des";

    public static void main(String[] args) {
        jdkDES();
        bcDES();

    }

    public static void jdkDES(){

        try {
            //生成KEY
            
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            //指定KEY的长度
            
keyGenerator.init(56);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] bytesKey = secretKey.getEncoded();

            //KEY转换
            
DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            //生成我们需要的密钥
            //SecretKey convertSecretKey = factory.generateSecret(desKeySpec);  和下面等价
            
Key convertSecretKey = factory.generateSecret(desKeySpec);

            //加密
            
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,convertSecretKey);
            byte[] bytes = cipher.doFinal(src.getBytes());
            System.out.println("jdk des encrypt: "+ Hex.bytesToHexString(bytes));

            //解码
            
cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
            bytes = cipher.doFinal(bytes);
            System.out.println("jdk des decrypt:"+new String(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void bcDES(){
        try {
            Security.addProvider(new BouncyCastleProvider());
            //生成KEY
            
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES","BC");
            keyGenerator.getProvider();
            //指定KEY的长度
            
keyGenerator.init(56);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] bytesKey = secretKey.getEncoded();

            //KEY转换
            
DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            //生成我们需要的密钥
            //SecretKey convertSecretKey = factory.generateSecret(desKeySpec);  和下面等价
            
Key convertSecretKey = factory.generateSecret(desKeySpec);

            //加密
            
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,convertSecretKey);
            byte[] bytes = cipher.doFinal(src.getBytes());
            System.out.println("bc des encrypt: "+ Hex.bytesToHexString(bytes));

            //解码
            
cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
            bytes = cipher.doFinal(bytes);
            System.out.println("bc des decrypt:"+new String(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

工具类:

package des;
/**
 * Created by gailun on 2018/4/2.
 */
public class Hex {
    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}

 

执行结果:

jdkDES()方法执行接口是:

 

bcDES()方法执行接口是:

 

 

3、3DES(3DES密钥长度比DES)

3DES的好处:

1>、密钥长度增强

2>、迭代次数提高

3DES(Triple DES DESede)

密钥长度

默认

工作模式

填充方式

实现方

112168

168

ECBCBCPCBCCTRCTSCFB

CFB8128OFBOFB8128

NoPadding

PKCS5Padding

ISO1012Padding

JDK

128192

168

同上

PKCS7Padding

ISO10126d2Padding

X932Padding

ISO7816d4Padding

ZeroBytePadding

BC

 

例子:

package des;
import org.bouncycastle.jce.provider.symmetric.DESede;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Created by gailun on 2018/4/8.
 */
public class T3DES {
    private static String src ="security 3des";
    public static void main(String[] args) {
        jdk3DES();
    }

    public static void jdk3DES(){
        try {
            //生成KEY
            
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
            //keyGenerator.init(168);
            
keyGenerator.init(new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] bytesKey = secretKey.getEncoded();

            //KEY转换
            
DESedeKeySpec desKeySpec = new DESedeKeySpec(bytesKey);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
            Key convertSecretKey = factory.generateSecret(desKeySpec);

            //加密
            
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,convertSecretKey);
            byte[] result = cipher.doFinal(src.getBytes());
            System.out.println("jdk 3des encrpt:"+Hex.bytesToHexString(result));

            //解密
            
cipher.init(Cipher.DECRYPT_MODE,convertSecretKey);
            result=cipher.doFinal(result);
            System.out.println("jdk 3des desrypt:"+new String(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

jdk3DES()方法执行结果:

 

 

4、AES(替代DES算法)

AES是目前使用最多的对称加密算法

AES的优势之一是至今尚未被破解

AES通常用于移动通信系统加密以及基于SSH协议的软件(SSH ClientsecureCRT)

1> 高级

2> DES替代者

密钥长度

默认

工作模式

填充方式

实现方

128192

256

128

ECBCBCPCBCCTRCTS

CFBCFB8128OFBOFB8128

NoPadding

PKCS5Padding

ISO10126Padding

JDK(256位密钥需要获得无政策限制权限文件)

同上

同上

同上

PKCS7Padding

ZeroBytePadding

BC

 

无政策限制权限文件是指, 因为某些国家的进口管制限制, Java发布的运行环境包中的加密有一定的限制.

例子:

package des;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/**
 * Created by gailun on 2018/4/10.
 */
public class AES {
    private static String src = "security aes";
    public static void main(String[] args) {
        jdkAES();
    }

    public static void jdkAES(){
        try {
            //生成KEY
            
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            //初始化长度
            
keyGenerator.init(128);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] keyBytes = secretKey.getEncoded();

            //KEY的转换
            
Key key = new SecretKeySpec(keyBytes,"AES");

            //加密
            
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,key);
            byte[] result = cipher.doFinal(src.getBytes());
            System.out.println("jdk aes encrypt:"+ Hex.bytesToHexString(result));

            //解密
            
cipher.init(Cipher.DECRYPT_MODE,key);
            result = cipher.doFinal(result);
            System.out.println("jdk aes desrypt:"+new String(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

jdkAES()执行结果:

 

 

5、PBE

PBE算法结合了消息摘要算法和对称加密算法的优点

PBE(Password Based Encryption) 基于口令加密

对已有算法的包装

JDKBC

PBEWithMD5AndDES(常用)

算法

密钥长度

默认

工作模式

填充方式

实现

PBEWithMD5AndDES

64

64

CBC

 

PKCS5Padding

PKCS7Padding

ISO1012Padding

ZeroBytePadding

BC

PBEWithMD5AndRC2

112

128

PBEWithSHA1AndDES

64

64

PBEWithSHA1AndRC2

128

128

PBEWithSHAAndIDEA

-CBC

128

128

PBEWithSHAAnd2-

KeyTripleDES-CBC

128

128

PBEWithSHAAnd3-

KeyTripleDES-CBC

192

192

 

算法

密钥长度

默认

工作模式

填充方式

实现

PBEWithMD5AndDES

56

56

CBC

PKCS5Padding

JDK

PBEWithMD5AndTripleDES

112168

168

PBEWithSHA1AndDESede

112168

168

PBEWithSHA1AndRC2_40

40~1024

(8倍数)

128

例子:

package des;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
 * Created by gailun on 2018/4/11.
 */
public class PBE {
    private static String src ="security pbe";
    public static void main(String[] args) {
        jdkPBE();
    }

    public static void jdkPBE(){
        try {
            //初始化盐
            
SecureRandom random = new SecureRandom();
            byte[] salt = random.generateSeed(8);

            //口令与密钥
            
String password = "pbe";
            PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWITHMD5andDES");
            Key key = factory.generateSecret(pbeKeySpec);

            //加密
            
PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt,100);
            Cipher cipher = Cipher.getInstance("PBEWITHMD5andDES");
            cipher.init(Cipher.ENCRYPT_MODE,key,pbeParameterSpec);
            byte[] result = cipher.doFinal(src.getBytes());
            System.out.println("jdk pbe encrypt:"+Hex.bytesToHexString(result));

            //解密
            
cipher.init(Cipher.DECRYPT_MODE,key,pbeParameterSpec);
            result = cipher.doFinal(result);
            System.out.println("jdk pbe decrypt:"+new String(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

jdkPBE()执行结果:

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值