Java加密

概念


  • 加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的内容。
  • 加密作用:防止重要敏感信息,被人获取。防看
  • 加密一般指的是双向加密

分类


  • 对称加密
  • 非对称加密

算法


  • 对称:DES、3DES
  • 非对称:RSA
    • RSA加密异常:javax.crypto.IllegalBlockSizeException: Data must not be longer than 117bytes
    • RSA非对称加密内容长度有限制,1024位key的最多只能加密117位数据,否则就会报错

代码


DES加密
// 生成一个可信任的随机数源,加强加密安全性
SecureRandom sr = new SecureRandom();
byte[] keyByte = key.getBytes("UTF-8");
byte[] plainByte = plaintext.getBytes("UTF-8");
SecretKey securekey = new SecretKeySpec(keyByte, algorithmDES);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(algorithmDES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
byte[] cipherByte = cipher.doFinal(plainByte);
// cipherText = BytesHexConverter.bytesToHexString(cipherByte);
cipherText = Base64.encode(cipherByte);
System.out.println(cipherText);

在这里插入图片描述

DES解密
SecureRandom sr = new SecureRandom();
byte[] keyByte = key.getBytes("UTF-8");
// byte[] cipherByte = BytesHexConverter.hexStringToBytes(cipherText);
byte[] cipherByte = Base64.decode(cipherText);
SecretKey securekey = new SecretKeySpec(keyByte, algorithmDES);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(algorithmDES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
byte[] plaintByte = cipher.doFinal(cipherByte);
plaintext = new String(plaintByte);
System.out.println(plaintext);

在这里插入图片描述

RSA加密
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithmRSA);
// 可以初始化一些配置:密钥长度,随机数。
// 配置随机串,加强加密安全性
// 声明随机串,可以指定种子 SecureRandom(byte[] seed)
// 注:RSA的密钥长度决定了可加密内容的长度;1024的key,加密内容不能超过127
keyPairGenerator.initialize(1024);
// 生成密钥
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 获取公私密钥
publicKey = keyPair.getPublic();
privateKey = keyPair.getPrivate();

// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(algorithmRSA);

byte[] plainByte = plaintext.getBytes("UTF-8");
// 用密钥初始化Cipher对象
// 公钥加密
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 私钥加密
// cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherByte = cipher.doFinal(plainByte);
// cipherText = BytesHexConverter.bytesToHexString(cipherByte);
cipherText = Base64.encode(cipherByte);
System.out.println(cipherText);
RSA解密
byte[] cipherByte = Base64.decode(cipherText);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(algorithmRSA);
// 用密钥初始化Cipher对象
// 私钥解密
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// 公钥解密
// cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] plaintByte = cipher.doFinal(cipherByte);
plaintext = new String(plaintByte);
System.out.println(plaintext);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值