JCE实例快速上手 - 字节级别加解密文本

本文提供了一个Java实现的DES加密与解密的完整示例代码,通过使用KeyGenerator生成密钥,并利用Cipher进行数据的加密和解密操作。演示了如何处理加密过程中可能出现的各种异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package jce;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.BadPaddingException;
import java.security.Key;
import java.security.Security;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
public class DESCryptoTest {
public static void main(String[] args) {
//此为动态加载的办法;
//静态加载方法为:编辑文件<java-home>\jre\lib\security\java.security
//JDK1.4及以上版本已带JCE
//Security.addProvider(new com.sun.crypto.provider.SunJCE());
try {
//产生密钥(key)生成器生成密钥
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = kg.generateKey();
//产生加密器(Cipher)
Cipher cipher = Cipher.getInstance("DES");

byte[] data = "Hello World!".getBytes();
System.out.println("Original data : " + new String(data));

cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(data);
System.out.println("Encrypted data: " + new String(result));

cipher.init(Cipher.DECRYPT_MODE, key);
byte[] original = cipher.doFinal(result);
System.out.println("Decrypted data: " + new String(original));
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (NoSuchPaddingException e) {
e.printStackTrace();
}
catch (InvalidKeyException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
catch (BadPaddingException e) {
e.printStackTrace();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值