Java密码学之加解密

前篇:Java密码学之数字签名_东皋长歌的博客-CSDN博客

日常开发中用的比较多的功能点,加解密数据,用Java实现也是很快很实用。

下面记录一下加解密数据的过程。

1,创建密钥对生成器

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

2,初始化密钥

keyPairGen.initialize(2048);

3,生成密钥对

KeyPair pair = keyPairGen.generateKeyPair();

4,创建加密对象

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

5,用公钥初始化加密对象

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

6,添加待加密内容到加密对象

byte[] input = "Welcome to Shenzhen".getBytes();
cipher.update(input);

7,使用公钥加密内容

byte[] cipherText = cipher.doFinal();
System.out.println( "加密后的内容:"+new String(cipherText, "UTF8"));

8,用私钥初始化加密对象,使用DECRYPT_MODE

cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());

9,解密密文

byte[] decipheredText = cipher.doFinal(cipherText);
System.out.println("解密后的内容:"+new String(decipheredText));

10,完整过程

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.*;

public class CipherDemo {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        //创建密钥对生成器,后面算法选择有: DiffieHellman,DSA,RSA 三种,如果是其他的话,就会抛出异常NoSuchAlgorithmException
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

        //初始化密钥生成器,一般长度要大于待加密内容
        keyPairGen.initialize(2048);

        //生成密钥对
        KeyPair pair = keyPairGen.generateKeyPair();

        //获取公钥
        PublicKey publicKey = pair.getPublic();

        //创建加密对象,后面内容为填充算法,RSA/ECB/PKCS1Padding,RSA/ECB,RSA//PKCS1Padding,RSA 4种选择,如果不在这里面会抛出异常NoSuchAlgorithmException,NoSuchPaddingException
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        //用公钥初始化加密对象,模式有ENCRYPT_MODE,DECRYPT_MODE,WRAP_MODE,UNWRAP_MODE 4种模式
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        //添加待加密内容到加密对象
        byte[] input = "Welcome to Shenzhen".getBytes();
        cipher.update(input);

        //使用公钥加密内容
        byte[] cipherText = cipher.doFinal();
        System.out.println( "加密后的内容:"+new String(cipherText, "UTF8"));

        //用私钥初始化加密对象,使用DECRYPT_MODE
        cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());

        //解密密文
        byte[] decipheredText = cipher.doFinal(cipherText);
        System.out.println("解密后的内容:"+new String(decipheredText));
    }
}

注意要结合自己项目里实际场景使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东皋长歌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值