【JavaSE】对称加密算法,密钥交换算法和非对称加密算法的使用

目录

对称加密算法

概述

使用ASE加密

ECB模式

创建加密方法

创建解密方法

对称加密码算法:AES-ECB

CBC模式

创建加密方法

创建解密方法

合并数组方法

对称加密码算法:AES-CBC

秘钥交换算法

概述

创建用户类

 秘钥交换算法-AES

非对称加密算法

概述

创建用户类

非对称加密算法-RSA 


对称加密算法

概述

对称加密算法就是传统的用一个秘钥进行加密解密

在软件开发中,常用的对称加密算法有:

算法

密钥长度

工作模式

填充模式

DES

56/64

ECB/CBC/PCBC/CTR/...

NoPadding/PKCS5Padding/...

AES

128/192/256

ECB/CBC/PCBC/CTR/...

NoPadding/PKCS5Padding/PKCS7Padding/...

IDEA

128

ECB

PKCS5Padding/PKCS7Padding/...

密钥长度直接决定加密强度,而工作模式和填充模式可以看成是对称加密算法的参数和格式选择。Java标准库提供的算法实现并不包括所有的工作模式和所有填充模式。
最后,值得注意的是,DES算法由于密钥过短,可以在短时间内被暴力破解,所以现在已经不安全了。

使用ASE加密

AES算法是目前应用最广泛的加密算法。比较常见的工作模式是ECBCBC

ECB模式

ECB模式是最简单的AES加密模式,它需要一个固定长度的密钥,固定的明文会生成固定的密文。

创建加密方法
        // 加密:
    public static byte[] encrypt(byte[] key, byte[] input) throws GeneralSecurityException     {
        // 创建密码对象,需要传入算法/工作模式/填充模式
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

        // 根据key的字节内容,"恢复"秘钥对象
        SecretKey secretKey = new SecretKeySpec(key, "AES");

        // 初始化秘钥:设置加密模式ENCRYPT_
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        // 根据原始内容(字节),进行加密
        return cipher.doFinal(input);
    }
创建解密方法
        // 解密:
    public static byte[] decrypt(byte[] key, byte[] input) throws GeneralSecurityException {
        // 创建密码对象,需要传入算法/工作模式/填充模式
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

        // 根据key的字节内容,"恢复"秘钥对象
        SecretKey secretKey = new SecretKeySpec(key, "AES");

        // 初始化秘钥:设置解密模式DECRYPT_MODE
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        // 根据原始内容(字节),进行解密
        return cipher.doFinal(input);
    }
对称加密码算法:AES-ECB
        // 原文:
        String message = "天生我材必有用飞流直下三千尺";
        System.out.println("Message(原始信息): " + message);

        // 128位密钥 = 16 bytes Key:
        byte[] key = "1234567890abcdef".getBytes();

        // 加密:
        byte[] data = message.getBytes();
        byte[] encrypted = encrypt(key, data);
        System.out.println("Encrypted(加密内容): " + Base64.getEncoder().encodeToString(encrypted));

        // 解密:
        byte[] decrypted = decrypt(key, encrypted);
        System.out.println("Decrypted(解密内容): " + new String(decrypted));

CBC模式

ECB模式是最简单的AES加密模式,这种一对一的加密方式会导致安全性降低。所以,更好的方式是通过CBC模式,它需要一个随机数作为IV参数,这样对于同一份明文,每次生成的密文都不同

创建加密方法
        // 加密:
    public static byte[] encrypt(byte[] key, byte[] input) throws GeneralSecurityException {
        // 设置算法/工作模式CBC/填充
        Cipher cipher =Cipher.getInstance("AES/CBC/PKCS5Padding");
        // 恢复秘钥对象
        SecretKey secretKey =new SecretKeySpec(key,"AES");

        // CBC模式需要生成一个16 bytes的initialization vector:
        SecureRandom sr = SecureRandom.getInstanceStrong();
        byte[] iv = sr.generateSeed(16);
        System.out.println("iv字节数组内容:"+ Arrays.toString(iv));
        System.out.println("iv字节数组长度:"+iv.length);

        //随机数封装成IvParameterSpec参数对象
        IvParameterSpec ivps =new IvParameterSpec(iv);

        // 初始化秘钥:操作模式、秘钥、IV参数
        cipher.init(Cipher.ENCRYPT_MODE,secretKey,ivps);

        // 加密
        byte[] bytes = cipher.doFinal(input);

        // IV不需要保密,把IV和密文一起返回:
        return join(iv,bytes);
    }
创建解密方法
        // 解密:
    public static byte[] decrypt(byte[] key, byte[] input) throws GeneralSecurityException {
        // 把input分割成IV和密文:
        byte[] iv =new byte[16];
        byte[] bytes = new byte[input.length-16];

        System.arraycopy(input,0,iv,0,16);
        System.arraycopy(input,16,bytes,0,bytes.length);
        System.out.println(Arrays.toString(iv));


        // 解密:
        Cipher cipher =Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec =new SecretKeySpec(key,"AES");
        IvParameterSpec ivps =new IvParameterSpec(iv);

        // 初始化秘钥:操作模式、秘钥、IV参数
        cipher.init(Cipher.DECRYPT_MODE,keySpec,ivps);

        // 解密操作
        return cipher.doFinal(bytes);
    }
合并数组方法
        // 合并数组
    public static byte[] join(byte[] bs1, byte[] bs2) {
        byte[] r = new byte[bs1.length+bs2.length];
        System.arraycopy(bs1,0,r,0,bs1.length);
        System.arraycopy(bs2,0,r,bs1.length,bs2.length);
        return r;
    }
对称加密码算法:AES-CBC
        // 原文:
        String message = "天生我材必有用飞流直下三千尺";
        System.out.println("Message(原始信息): " + message);

        // 256位密钥 = 32 bytes Key:
        byte[] key = "1234567890abcdef1234567890abcdef".getBytes();

        // 加密:
        byte[] data = message.getBytes();
        byte[] encrypted = encrypt(key,data);
        System.out.println("Encrypted(加密内容): " +
                Base64.getEncoder().encodeToString(encrypted));

        // 解密:
        byte[] decrypted = decrypt(key,encrypted);
        System.out.println("Decrypted(解密内容): " + new String(decrypted));

CBC模式下,需要一个随机生成的16字节IV参数,必须使用SecureRandom生成

因为多了一个IvParameterSpec实例

因此,初始化方法需要调用Cipher的一个重载方法并传入IvParameterSpec

秘钥交换算法

概述

密钥交换算法DH算法Diffie-Hellman算法)。DH算法解决了密钥在双方不直接传递密钥的情况下完成密钥交换,这个神奇的交换原理完全由数学理论支持。
我们来看DH算法交换密钥的步骤。假设甲乙双方需要传递密钥,他们之间可以这么做:

  1. Alice首选选择一个素数p= 509,底数g = 5(任选),随机数a = 123,然后计算A = g^a mod p,结果是215,然后,Alice发送p = 509,g=5,A=215给Bob;
  2. Bob收到后,也选择一个随机数b=456,然后计算B = g^b mod p,结果是181,Bob再同时计算K = A^b mod p,结果是121;
  3. Bob把计算的B=181发给Alice,Alice计算K = B^a mod p的余数,计算结果与Bob算出的结果一样,都是121。

        如果我们把a看成甲的私钥,A看成甲的公钥,b看成乙的私钥,B看成乙的公钥,DH算法的本质就是双方各自生成自己的私钥和公钥,私钥仅对自己可见,然后交换公钥,并根据自己的私钥和对方的公钥,生成最终的密钥secretKeyDH算法通过数学定律保证了双方各自计算出的secretKey是相同的。 

创建用户类
    //用户类
class Person {
    public final String name; // 姓名

    // 密钥
    public PublicKey publicKey; // 公钥
    private PrivateKey privateKey; // 私钥
    private byte[] secretKey; // 本地秘钥(共享密钥)


    // 构造方法
    public Person(String name) {
        this.name = name;
    }

    // 生成本地KeyPair:(公钥+私钥)
    public void generateKeyPair()   {
        try {
            //创建DH算法的“密钥对”生成器
            KeyPairGenerator keyPairGenerator =KeyPairGenerator.getInstance("DH");
            keyPairGenerator.initialize(512);

            //生成一个密钥对
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            this.privateKey = keyPair.getPrivate();
            this.publicKey = keyPair.getPublic();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


    }

    // 按照 "对方的公钥" => 生成"共享密钥"
    public void generateSecretKey(byte[] receivedPubKeyBytes) {
        try {
            //从byte[]恢复PublicKey
            X509EncodedKeySpec keySpec =new X509EncodedKeySpec(receivedPubKeyBytes);

            //根据Dh算法获取KeyFactory
            KeyFactory keyFactory =KeyFactory.getInstance("DH");

            //通过KeyFactory创建公钥
            PublicKey publicKey = keyFactory.generatePublic(keySpec);

            //创建密钥协议对象(用于密钥协商)
            KeyAgreement keyAgreement = KeyAgreement.getInstance("DH");
            keyAgreement.init(this.privateKey);
            keyAgreement.doPhase(publicKey,true);

            //生成SecretKey本地密钥(共享密钥)
            this.secretKey = keyAgreement.generateSecret();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }
    //输出结果
    public void printKeys() {
        System.out.printf("Name: %s\n", this.name);
        System.out.printf("Private key: %x\n", new BigInteger(1, this.privateKey.getEncoded()));
        System.out.printf("Public key: %x\n", new BigInteger(1, this.publicKey.getEncoded()));
        System.out.printf("Secret key: %x\n", new BigInteger(1, this.secretKey));
    }
 秘钥交换算法-AES
        // Bob和Alice:
        Person bob = new Person("Bob");
        Person alice = new Person("Alice");

        // 各自生成KeyPair: 公钥+私钥
        bob.generateKeyPair();
        alice.generateKeyPair();

        // 双方交换各自的PublicKey(公钥):
        // Bob根据Alice的PublicKey生成自己的本地密钥(共享公钥):
        bob.generateSecretKey(alice.publicKey.getEncoded());

        // Alice根据Bob的PublicKey生成自己的本地密钥(共享公钥):
        alice.generateSecretKey(bob.publicKey.getEncoded());

        // 检查双方的本地密钥是否相同:
        bob.printKeys();
        alice.printKeys();

 DH算法是一种密钥交换协议,通信双方通过不安全的信道协商密钥,然后进行对称加密传输。

非对称加密算法

概述

        非对称加密:加密和解密使用的不是相同的密钥,用户A密钥加密后所得的信息,只能用用户A的解密密钥才能解密。如果知道了其中一个,并不能计算出另外一个。因此如果公开了一对密钥中的一个,并不会危害到另外一个的秘密性质。称公开的密钥为公钥;不公开的密钥为私钥。只有同一个公钥-私钥对才能正常加解密。
        非对称加密的缺点:运算速度非常慢,比对称加密要慢很多。
        从DH算法我们可以看到,公钥-私钥组成的密钥对是非常有用的加密方式,因为公钥是可以公开的,而私钥是完全保密的,由此奠定了非对称加密的基础。
        非对称加密的典型算法就是RSA算法,它是由Ron RivestAdi ShamirLeonard Adleman这三个人一起发明的,所以用他们三个人的姓氏首字母缩写表示。

我们通过小明索取小红公钥加密后发给小红,小红又通过自己私钥解密实现非对称加密算法

创建用户类
    // 用户类
class Human {
    // 姓名
    String name;

    // 私钥:
    PrivateKey privatekey;

    // 公钥:
    PublicKey publickey;

    // 构造方法
    public Human(String name) throws GeneralSecurityException {
        // 初始化姓名
        this.name = name;

        // 生成公钥/私钥对:
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        this.privatekey = keyPair.getPrivate();
        this.publickey = keyPair.getPublic();

    }

    // 把私钥导出为字节
    public PrivateKey getPrivateKey() {
        return this.privatekey;
    }

    // 把公钥导出为字节
    public PublicKey getPublicKey() {
        return this.publickey;
    }

    // 用公钥加密
    public byte[] encrypt(byte[] message, PublicKey publickey) throws GeneralSecurityException {
        // 使用公钥进行初始化
        Cipher cipher =Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE,publickey);
        return cipher.doFinal(message);
    }

    // 用私钥解密:
    public byte[] decrypt(byte[] input) throws GeneralSecurityException {
        // 使用私钥进行初始化
        Cipher cipher=Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE,privatekey);
        return cipher.doFinal(input);
    }
}
非对称加密算法-RSA 
        // 明文:
        byte[] plain = "Hello, encrypt use RSA".getBytes("UTF-8");

        // 创建公钥/私钥对
        Human hong = new Human("小红");
        Human ming = new Human("小明");

        // 小明使用小红的公钥进行加密
        // 1.获取小红的公钥
        PublicKey hongPublicKey = hong.getPublicKey();
        System.out.println(String.format("小红的public key(公钥): %x", new BigInteger(1, hongPublicKey.getEncoded())));

        // 2.使用公钥加密
        byte[] encrypted = ming.encrypt(plain,hongPublicKey);
        System.out.println(String.format("encrypted(加密): %x", new BigInteger(1, encrypted)));

        // 小红使用自己的私钥解密:
        // 1.获取小红的私钥,并输出
        PrivateKey hongPrivateKey = hong.privatekey;
        System.out.println(String.format("小红的private key(私钥): %x", new BigInteger(1, hongPrivateKey.getEncoded())));

        // 2.使用私钥解密
        byte[] decrypted = hong.decrypt(encrypted);
        System.out.println("decrypted(解密): " + new String(decrypted, "UTF-8"));

        以RSA算法为例,它的密钥有256/512/1024/2048/4096等不同的长度。长度越,密码强度越,当然计算速度也越。 

        非对称加密就是加密和解密使用的不是相同的密钥,只有同一个公钥-私钥对才能正常加解密

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值