基于Cipher的Java加密工具类

devtools/2025/2/2 20:57:31/

一、什么是Cipher

        Cipher是一种用于加密和解密信息的算法或方法。它将原始的明文转化为密文,从而保护信息的安全性和机密性。使用密码学中的数学原理和技术,Cipher可以对数据进行加密处理,使其在传输或存储过程中对未授权的访问者不可读。在必要时,只有具有正确密钥或密码的人才能解密并获取原始的明文信息。

        Cipher可以分为对称加密和非对称加密两种类型。对称加密使用相同的密钥进行加密和解密,速度较快,但密钥管理较为复杂。而非对称加密使用一对密钥,私钥用于解密,公钥用于加密,在安全性上更加可靠,但运算速度较慢。

        实际应用中,Cipher被广泛应用于保护敏感数据的传输,如网上银行、电子商务、密码学通信等领域。通过使用Cipher,可以保护个人隐私、防止信息被窃取或篡改,提高数据的安全性和机密性。

二、Java中的Cipher类

       在Java中,Cipher是一个提供加密和解密功能的类。它位于javax.crypto包下,用于实现各种加密算法。Cipher类可以用于对数据进行加密和解密操作,同时还可以进行数字签名和验签。

代码示例:

java">package com.blockchain.qgy.demo.cipherdemo;import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.util.Arrays;
import java.util.Random;public class CipherDemo {public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {//密钥StringBuilder sb = new StringBuilder("QGY");while(sb.length() < 8) {sb.append((char)new Random().nextInt(128));}byte[] keyBytes = sb.toString().getBytes();//生成密钥SecretKey key = new SecretKeySpec(keyBytes,"DES");System.out.println("密钥:"+key);Cipher instance = Cipher.getInstance("DES");System.out.println("初始化Cipher对象");instance.init(Cipher.ENCRYPT_MODE,key);System.out.println("Cipher对象:"+instance);Provider provider = instance.getProvider();System.out.println("Cipher对象提供者:"+provider);String algorithm = instance.getAlgorithm();System.out.println("Cipher对象的算法名称:"+algorithm);int blockSize = instance.getBlockSize();System.out.println("返回块的大小:"+blockSize);byte[] iv = instance.getIV();System.out.println("返回新缓冲区的初始化向量:"+iv);AlgorithmParameters parameters = instance.getParameters();System.out.println("返回Cipher使用的参数:"+parameters);ExemptionMechanism exemptionMechanism = instance.getExemptionMechanism();System.out.println("Cipher使用的豁免机制对象:"+exemptionMechanism);byte[] bytes = instance.doFinal(new byte[]{'Q', 'G', 'Y'});System.out.println("bytes:"+Arrays.toString(bytes));System.out.println("bytes->update:"+Arrays.toString(instance.update(bytes)));}
}

上面是一个Cipher类加密的简单示例,在Cipher类中常用的常量字段有7个:

  1. public static final int ENCRYPT MODE:用于将 Cipher 初始化为加密模式的常量。
  2. public static final int DECRYPT MODE:用于将 Cipher 初始化为解密模式的常量。
  3. public static fnal int WRAP MODE:用于将 Cipher 初始化为密钥包装模式的常量。
  4. public static finalint UNWRAP MODE:用于将 Cipher 初始化为密钥解包模式的常量。
  5. public static final int PUBLIC KEY:用于表示要解包的密钥为“公钥”的常量。
  6. public static final int PRIVATE KEY:用于表示要解包的密钥为“私钥”的常量。
  7. public static final intSECRET KEY:用于表示要解包的密钥为“秘密密钥”的常量。

三、封装好的加密工具类

加密工具类:

java">package com.blockchain.qgy.util;import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;/*** 基于Cipher实现的加密和解密工具类** @author QGY**/
public class DeEnCoderCipherUtil {//加密、解密模式,即加密算法名称private final static String CIPHER_MODE = "DES";//DES密钥private static String DEFAULT_DES_KEY = "主播主播,你的MD5加密确实很强,但还是太吃操作了,有没有更加简单和强势的加密工具推荐一下,有的兄弟,有的,这就是当前版本T0.5的强势加密算法";/*** 不允许创建对象*/private DeEnCoderCipherUtil(){}/*** function 字符串加密方法** @param plaintext:要加密的字符串* @param key:密钥* @return 加密后的字符串*/public static String getCipherText(String plaintext,String key){//判断入参是否正确if(Strings.isNullOrEmpty(plaintext) || Strings.isNullOrEmpty(key)) return null;try{byte[] cipherText = getCipherText(plaintext.getBytes(), key.getBytes());return new BASE64Encoder().encode(cipherText);} catch (Exception e){e.printStackTrace();}return null;}/*** function 字节加密方法** @param plaintext:要加密的字节* @param key:密钥* @return 加密后的字节*/private static byte[] getCipherText(byte[] plaintext,byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {//1.生成随机数SecureRandom random = new SecureRandom();//2.基于密钥数据创建DESKeySpec对象DESKeySpec desKeySpec = new DESKeySpec(key);//3.创建密钥工厂,将DESKeySpec转换成SecretKey对象来保存对称密钥SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CIPHER_MODE);SecretKey secretKey = keyFactory.generateSecret(desKeySpec);//4.Cipher对象进行加密Cipher cipher = Cipher.getInstance(CIPHER_MODE);//5.初始化Cipher对象cipher.init(Cipher.ENCRYPT_MODE,secretKey,random);//返回密文return cipher.doFinal(plaintext);}public static String getPlainText(String cipherText,String key){//判断入参if(Strings.isNullOrEmpty(cipherText) ||  Strings.isNullOrEmpty(key)) return null;try{BASE64Decoder decoder = new BASE64Decoder();return new String(getPlainText(decoder.decodeBuffer(cipherText),key.getBytes()));}catch (Exception e) {e.printStackTrace();}return null;}private static byte[] getPlainText(byte[] cipherText,byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {//1.生成随机数SecureRandom random = new SecureRandom();//2.基于密钥数据创建DESKeySpec对象DESKeySpec desKeySpec = new DESKeySpec(key);//3.创建密钥工厂,将DESKeySpec转换成SecretKey对象来保存对称密钥SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CIPHER_MODE);SecretKey secretKey = keyFactory.generateSecret(desKeySpec);//4.Cipher对象进行解密Cipher cipher = Cipher.getInstance(CIPHER_MODE);//5.初始化Cipher对象cipher.init(Cipher.DECRYPT_MODE,secretKey,random);//返回明文return cipher.doFinal(cipherText);}
}

strings工具类:

java">package com.blockchain.qgy.util;import java.util.Objects;/*** 字符串工具类** @author QGY**/
public class Strings {/*** 判断字符串是否为空或null** @param string* @return 布尔值*/public static Boolean isNullOrEmpty(String string){if (Objects.isNull(string)) return true;if (string.isEmpty()) return true;return false;}
}

注意:这里密钥的长度为8,如果有其他需求可以通过进一步封装达到自身需求 


http://www.ppmy.cn/devtools/155537.html

相关文章

LVGL+FreeRTOS实战项目:智能健康助手(lcd篇)

1.8寸彩色TFT显示屏简介 接线图 我们选用的是分辨率为128*160的彩色显示屏&#xff0c;采用的SPI接口&#xff0c;通过我们STM32的SPI外设&#xff0c;来和我们的屏幕进行通信&#xff0c;以显示我们需要显示的图片。 软件部分 #include "lcd_driver.h"//液晶IO初始…

2015年蓝桥杯第六届CC++大学B组真题及代码

目录 1A&#xff1a;奖券数目&#xff08;填空_简单枚举&#xff09; 2B&#xff1a;星系炸弹&#xff08;填空_日期计算&#xff09; 3C&#xff1a;三羊献瑞&#xff08;填空_全排列&#xff09; 4D&#xff1a;格子中输出&#xff08;代码填空&#xff09; 5E&#xff1…

C# 拖入文件 只能拖入txt文件

要实现只能将 .txt 文件拖入 Button 控件&#xff08;如 button1&#xff09;并获取其路径&#xff0c;可以在之前的基础上添加文件类型的检查逻辑。以下是具体实现步骤和示例代码&#xff1a; 1. 创建 Windows Forms 项目 打开 Visual Studio&#xff0c;创建一个新的 Window…

ASP.NET Core WebAPI的异步及返回值

目录 Action方法的异步 Action方法参数 捕捉URL占位符 捕捉QueryString的值 JSON报文体 其他方式 Action方法的异步 Action方法既可以同步也可以异步。异步Action方法的名字一般不需要以Async结尾。Web API中Action方法的返回值如果是普通数据类型&#xff0c;那么返回值…

【BQ3568HM开发板】深入解析智能家居中控屏工程的NAPI接口设计

目录 引言 一、NAPI接口概述 二、NAPI接口设计 1. 接口定义 2. 接口实现 三、NAPI接口在智能家居中控屏中的应用 1. 灯光控制 2. 窗帘控制 四、总结 本文收发于电子发烧友论坛&#xff1a;https://bbs.elecfans.com/jishu_2474863_1_1.html。 引言 在智能家居中控屏…

开源智慧园区管理系统对比五款主流产品探索智能运营新模式

内容概要 在这个数字化迅速发展的时代&#xff0c;园区管理也迎来了全新的机遇和挑战。众所周知&#xff0c;开源智慧园区管理系统作为一种创新解决方案&#xff0c;正逐步打破传统管理的局限性。它的开放性不仅使得系统可以根据具体需求进行灵活调整&#xff0c;也为用户提供…

【2025年数学建模美赛F题】(顶刊论文绘图)模型代码+论文

全球网络犯罪与网络安全政策的多维度分析及效能评估 摘要1 Introduction1.1 Problem Background1.2Restatement of the Problem1.3 Literature Review1.4 Our Work 2 Assumptions and Justifications数据完整性与可靠性假设&#xff1a;法律政策独立性假设&#xff1a;人口统计…

Java - WebSocket

一、WebSocket 1.1、WebSocket概念 WebSocket是一种协议&#xff0c;用于在Web应用程序和服务器之间建立实时、双向的通信连接。它通过一个单一的TCP连接提供了持久化连接&#xff0c;这使得Web应用程序可以更加实时地传递数据。WebSocket协议最初由W3C开发&#xff0c;并于2…