您当前的位置:首页 > 计算机 > 加密解密

一起聊聊加密算法⭐Base64+对称加密算法+非对称加密算法!!!

时间:06-18来源:作者:点击数:
城东书院 www.cdsy.xyz

简介

本文章是作者在闲时去了解的加密算法的使用,也实际的了解了什么是加密算法,以及算法的分类,算法都有哪些,在这里分享给大家。

主要包含Base64算法对称加密算法——DES、3重DES、AES、PBE非对称加密算法——DH、RSA、Elgamal

密码常用术语

明文:待加密信息。

密文:经过加密后的明文。

加密:明文转为密文的过程。

加密算法:明文转为密文的转换算法。

加密密钥:通过加密算法进行加密操作用的密钥。

解密:将密文转为明文的过程。

解密算法:密文转为明文的算法。

解密密钥:通过解密算法进行解密操作用的密钥。

密码分析:截获密文者试图通过分析截获的密文从而推断出原来的明文或密钥的过程。

主动攻击:攻击者非法入侵密码系统,采用伪造、修改、删除等手段向系统注入假消息进行欺骗。(对密文具有破坏作用)

被动攻击:对一个保密系统采取截获密文并对其进行分析和攻击。(对密文没有破坏作用)。

密码体制:由明文空间、密文空间、密钥空间、加密算法和解密算法五部分构成。

密码协议:也称安全协议,指以密码学为基础额的消息交换的通信协议,目的是在网络环境中提供安全的服务

密码系统:指用于加密、解密的系统。

柯克霍夫原则:数据的安全基于密钥而不是算法的保密。即系统的安全取决于密钥,对密钥保密,对算法公开。——现代密码学设计的基本原则。

密码分类——时间

古典密码:以字符为基本加密单元。

现代密码:以信息块为基本加密单元。

密码分类——保密内容算法

名称 详细说明 应用领域 类别
受限制算法 算法的保密性基于保持算法的秘密 军事领域 古典密码
基于密钥算法 算法的保密性基于对密钥的保密   现代密码

密码分类——密码体制

名称 别名 详细说明
对称密码 单钥密码或私钥密码 指加密密码与解密密码相同
非对称密码 双钥密码或公钥密码 指加密密钥与解密密钥不同,密钥分公钥、私钥
对称密码算法 单钥密码算法或私钥密码算法 指应用于对称密码的加密、解密算法
非对称密码算法 双钥密码算法或公钥密码算法 指对应于非对称密码的加密、解密算法

密码分类——明文处理方法

分组密码:指加密时将名为分成固定长度的组,用同一密钥和算法对每一块加密,输出也是固定长度的密文。多用于网络加密。

流密码:也称序列密码。指加密时每次加密以为或者一个字节明文。

散列函数

散列函数用来验证数据的完整性

特点:

长度不受限制

哈希值容易计算

散列运算过程不可逆

散列函数相关的算法

消息摘要算法MD5等

SHA——安全散列算法

MAC——消息认证码算法

数字签名

主要是针对数字的形式存储的消息进行的处理。

OSI安全体系

OSI(Open System Interconnection)

Java安全组成

JCA(Java Cryptography Architecture):Java加密体系结构

JCE(Java Cryptography Extension):Java加密扩展包(DES、AES、RSA算法都是通过JCE提供)

JSSE(Java Secure Socket Extension):Java安全套接字扩展包(JSSE提供基于SSL的加密功能,主要用于网络传输)

JAAS(Java Authenticatoin and Authentication Service):Java鉴别于安全服务

相关Java包、类

java.security——消息摘要

javax.crypto——安全消息摘要,消息认证(鉴别)码

java.net.ssl——安全套接字(HttpsURLConnection\SSLContext)

第三方java扩展

Bouncy Castle——两种支持方案:1)配置 2)调用

Commons Codec——Apache、Base64、二进制、十六进制、字符集编码、URL编码/解码

Base64算法

算法实现方式:

JDK、Commons Codec、Bouncy Castle

三种实现方式代码实现:

package com.bxl.demo.service;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**
 * Created by xiaobai on 2021-8-24
 */
public class Base64Demo {

    private static String src = "xiaobai base64";

    public static void main(String[] args) {
        jdkBase64();
        commonsCodesBase64();
        bouncyCastleBase64();
    }

    public static void jdkBase64(){
        try {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            String encodeBase64 = base64Encoder.encode(src.getBytes());
            System.out.println("encode:" + encodeBase64);

            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] decoderBase64 = base64Decoder.decodeBuffer(encodeBase64);
            System.out.println("decode:" + new String(decoderBase64));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void  commonsCodesBase64(){
        byte[] encodeBase64 = Base64.encodeBase64(src.getBytes());
        System.out.println("encode:" + new String(encodeBase64));

        byte[] decodeBytes = Base64.decodeBase64(encodeBase64);
        System.out.println("decode:" + new String(decodeBytes));
    }

    /**
     * BC算法需要添加依赖bcprov-jdk15on
     * <dependency>
     *     <groupId>org.wso2.orbit.org.bouncycastle</groupId>
     *     <artifactId>bcprov-jdk15on</artifactId>
     *     <version>1.60.0.wso2v1</version>
     * </dependency>
     */
    public static void  bouncyCastleBase64(){
        byte[] encodeBase64 = org.bouncycastle.util.encoders.Base64.encode(src.getBytes());
        System.out.println("encode:" + new String(encodeBase64));

        byte[] decodeBytes = org.bouncycastle.util.encoders.Base64.decode(encodeBase64);
        System.out.println("decode:" + new String(decodeBytes));
    }

}

应用场景:

e-mail、密钥、证书文件

对称加密算法——DES

DES(Data Encryption Standard)数据加密标准(目前不建议使用,因为不安全了)

实现方:

主要流程:

代码实现:

package com.bxl.demo.service;

import org.apache.commons.codec.binary.Hex;
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.Key;
import java.security.Security;

/**
 * Created by xiaobai on 2021-8-24
 */
public class DESDemo {

    private static String src = "xiaobai DES";

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

    public static void jdkDES(){

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

            // KEY转换
            DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
            Key convertSecretKey = secretKeyFactory.generateSecret(desKeySpec);

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

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

    }


    public static void bcDES(){
        try {
            // 推荐这样使用,而不是修改JDK的配置文件
            Security.addProvider(new BouncyCastleProvider());

            // 生成KEY
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES","BC");

            keyGenerator.init(56);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] bytesKey = secretKey.getEncoded();

            // KEY转换
            DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
            Key convertSecretKey = secretKeyFactory.generateSecret(desKeySpec);

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

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

}

对称加密算法——3重DES

3DES(Triple DES或DESede),还有2重DES、4重DES,但是3重DES的实际应用广泛。

3重DES的好处:

1.密钥长度增强

2.迭代次数提高

3重DES的缺点:

效率低,速度慢

实现方:

代码实现:

package com.bxl.demo.service;

import org.apache.commons.codec.binary.Hex;
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 javax.crypto.spec.DESedeKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;

/**
 * Created by xiaobai on 2021-8-24
 */
public class TreeDESDemo {

    private static String src = "xiaobai 3DES";

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

    public static void jdkDES(){

        try {
            // 生成KEY
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
            //keyGenerator.init(168);
            // SecureRandom生成默认长度的key
            keyGenerator.init(new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] bytesKey = secretKey.getEncoded();

            // KEY转换
            DESedeKeySpec desKeySpec = new DESedeKeySpec(bytesKey);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
            Key convertSecretKey = secretKeyFactory.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 desede encrypt:" + Hex.encodeHexString(result));

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

    }


    public static void bcDESede(){
        try {
            // 推荐这样使用,而不是修改JDK的配置文件
            Security.addProvider(new BouncyCastleProvider());

            // 生成KEY
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
            //keyGenerator.init(168);
            // SecureRandom生成默认长度的key
            keyGenerator.init(new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] bytesKey = secretKey.getEncoded();

            // KEY转换
            DESedeKeySpec desKeySpec = new DESedeKeySpec(bytesKey);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
            Key convertSecretKey = secretKeyFactory.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 desede encrypt:" + Hex.encodeHexString(result));

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

对称加密算法——AES

比较高级、DES替代者

主要流程:

代码实现:

package com.bxl.demo.service;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;

/**
 * Created by xiaobai on 2021-8-24
 */
public class AESDemo {

    private static String src = "xiaobai AES";

    public static void main(String[] args) {
        jdkAES();
    }

    public static void jdkAES(){
        try {
            // 生成KEY
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            //keyGenerator.init(168);
            // SecureRandom生成默认长度的key
            keyGenerator.init(new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] bytesKey = secretKey.getEncoded();

            // KEY转换
            Key key = new SecretKeySpec(bytesKey,"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:" + Base64.encodeBase64String(result));

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

    }
}

对称加密算法——PBE

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

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

对已有算法的包装

常用的如:PBEWithMD5AndDES

实现方:

JDK、BC

主要流程:

代码实现:

package com.bxl.demo.service;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.Key;
import java.security.SecureRandom;

/**
 * Created by xiaobai on 2021-8-24
 */
public class PBEDemo {

    private static String src = "xiaobai PDE";

    public static void main(String[] args) {
        jdkPDE();
    }

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

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

            // 实例化PDE输入材料
            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 pde encrypt:" + Base64.encodeBase64String(result));

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

    }
}

非对称加密算法——DH(密钥交换)

构建本地密钥

实现方:

主要流程

代码实现:

package com.bxl.demo.service;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;
import java.util.Objects;

/**
 * Created by xiaobai on 2021-8-24
 */
public class DHDemo {

    private static String src = "xiaobai DH";

    public static void main(String[] args) {
        jdkDH();
    }

    public static void jdkDH(){
        try {
            // 1.初始化发送方密钥
            KeyPairGenerator senderKeyPairGenerator = KeyPairGenerator.getInstance("DH");
            senderKeyPairGenerator.initialize(512);
            KeyPair senderKeyPair = senderKeyPairGenerator.generateKeyPair();
            // 发送方公钥,发送给接收方(网络、文件...)
            byte[] senderPublicKeyEnc = senderKeyPair.getPublic().getEncoded();

            // 2.初始化接收方密钥
            KeyFactory receiverKeyFactory = KeyFactory.getInstance("DH");
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(senderPublicKeyEnc);
            PublicKey receiverPublicKey = receiverKeyFactory.generatePublic(x509EncodedKeySpec);
            // 获取发送方公钥中的参数
            DHParameterSpec dhParameterSpec = ((DHPublicKey)receiverPublicKey).getParams();
            KeyPairGenerator receiverPairGenerator = KeyPairGenerator.getInstance("DH");
            receiverPairGenerator.initialize(dhParameterSpec);
            KeyPair receiverKeypair = receiverPairGenerator.generateKeyPair();
            PrivateKey receiverPrivateKey = receiverKeypair.getPrivate();
            byte[] receiverPublicKeyEnc = receiverKeypair.getPublic().getEncoded();

            // 3.密钥构建
            KeyAgreement receiverKeyAgreement = KeyAgreement.getInstance("DH");
            receiverKeyAgreement.init(receiverPrivateKey);
            receiverKeyAgreement.doPhase(receiverPublicKey,true);
            // 根据发送方的公钥来生成本地的密钥
            SecretKey receiverDesKey = receiverKeyAgreement.generateSecret("DES");

            KeyFactory senderKeyFactory = KeyFactory.getInstance("DH");
            x509EncodedKeySpec = new X509EncodedKeySpec(receiverPublicKeyEnc);
            PublicKey senderPublicKey = senderKeyFactory.generatePublic(x509EncodedKeySpec);
            KeyAgreement senderKeyAgreement = KeyAgreement.getInstance("DH");
            senderKeyAgreement.init(senderKeyPair.getPrivate());
            senderKeyAgreement.doPhase(senderPublicKey,true);
            SecretKey senderDesKey = senderKeyAgreement.generateSecret("DES");
            if(Objects.equals(receiverDesKey,senderDesKey)){
                System.out.println("双方密钥相同!");
            }

            // 4.加密
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE,senderDesKey);
            byte[] result = cipher.doFinal(src.getBytes());
            System.out.println("jdk dh encrypt:" + Base64.encodeBase64String(result));

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

可能会出现的问题:

问题解决:

由于JDK版本不同,在Java 8 update 161版本以后就会出现此问题,根本原因还是DH密钥长度至少为512位,而DES算法密钥没有这么长,密钥长度不一致引起的。

配置JVM的系统变量:

-Djdk.crypto.KeyAgreement.legacyKDF=true

非对称加密算法——RSA

唯一广泛接受并实现

数据加密&数字签名

公钥加密、私钥解密

私钥加密、公钥解密

实现方:

主要流程:

代码实现:

package com.bxl.demo.service;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by xiaobai on 2021-8-24
 */
public class RSADemo {

    private static String src = "xiaobai rsa";

    public static void main(String[] args) {
        // 执行方法
        jdkRSA();
    }

    public static void jdkRSA(){

        try {
            /* 一、初始化密钥 */
            // 1.获得RSA的KeyPairGenerator对象示例
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            // 2.修改key的长度
            keyPairGenerator.initialize(512);
            // 3.得到KeyPair对象
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            // 4.获取公钥
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            // 5.获取私钥
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            System.out.println("Public key:" + Base64.encodeBase64String(rsaPublicKey.getEncoded()));
            System.out.println("Private key:" + Base64.encodeBase64String(rsaPrivateKey.getEncoded()));

            // 2.私钥加密、公钥解密——加密
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE,privateKey);
            byte[] result = cipher.doFinal(src.getBytes());
            System.out.println("私钥加密、公钥解密——加密:" + Base64.encodeBase64String(result));

            // 3.私钥加密、公钥解密——解密
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE,publicKey);
            result = cipher.doFinal(result);
            System.out.println("私钥加密、公钥解密——解密:" + Base64.encodeBase64String(result));
            System.out.println("私钥加密、公钥解密——解密:" + new String(result));

            // 4.公钥加密、私钥解密——加密
            x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("RSA");
            publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE,publicKey);
            result = cipher.doFinal(src.getBytes());
            System.out.println("公钥加密、私钥解密——加密:" + Base64.encodeBase64String(result));

            // 5.公钥加密、私钥解密——解密
            pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
            keyFactory = KeyFactory.getInstance("RSA");
            privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE,privateKey);
            result = cipher.doFinal(result);
            System.out.println("公钥加密、私钥解密——解密:" + new String(result));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

非对称加密算法——ElGamal

使用的是公钥加密算法

Bouncy Castle提供

实现方:

主要流程:

代码实现:

package com.bxl.demo.service;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.DHParameterSpec;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by xiaobai on 2021-8-24
 */
public class ElgamalDemo {

    private static String src = "xiaobai Elgamal";

    public static void main(String[] args) {
        // 执行方法
        jdkElgamal();
    }

    public static void jdkElgamal(){

        try {
            // 首先需要添加Provider
            // 公钥加密、私钥解密
            Security.addProvider(new BouncyCastleProvider());

            /* 一、初始化密钥 */
            AlgorithmParameterGenerator algorithmParameterGenerator = AlgorithmParameterGenerator.getInstance("ElGamal");
            algorithmParameterGenerator.init(256);
            AlgorithmParameters algorithmParameters = algorithmParameterGenerator.generateParameters();
            DHParameterSpec dhParameterSpec = algorithmParameters.getParameterSpec(DHParameterSpec.class);
            KeyPairGenerator keyPairGenerator1 = KeyPairGenerator.getInstance("ElGamal");
            keyPairGenerator1.initialize(dhParameterSpec,new SecureRandom());
            KeyPair keyPair = keyPairGenerator1.generateKeyPair();
            PublicKey elGamalPublicKey = keyPair.getPublic();
            PrivateKey elGamalPrivateKey = keyPair.getPrivate();
            System.out.println("Public key:" + Base64.encodeBase64String(elGamalPublicKey.getEncoded()));
            System.out.println("Private key:" + Base64.encodeBase64String(elGamalPrivateKey.getEncoded()));
            
            // 2.公钥加密、私钥解密——加密
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(elGamalPublicKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("ElGamal");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("ElGamal");
            cipher.init(Cipher.ENCRYPT_MODE,publicKey);
            byte[] result = cipher.doFinal(src.getBytes());
            System.out.println("公钥加密、私钥解密——加密:" + Base64.encodeBase64String(result));

            // 3.公钥加密、私钥解密——解密
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(elGamalPrivateKey.getEncoded());
            keyFactory = KeyFactory.getInstance("ElGamal");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            cipher = Cipher.getInstance("ElGamal");
            cipher.init(Cipher.DECRYPT_MODE,privateKey);
            result = cipher.doFinal(result);
            System.out.println("公钥加密、私钥解密——解密:" + new String(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

RSA——基于因子分解

Elgamal——基于离散对数

大家可以动手试一下,其实挺好理解的,大部分实现都是一样,学会一种,就可以举一反三了。

城东书院 www.cdsy.xyz
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐