可用于根据一个主密码,生成多个固定密码
package com.xuyt.genpwd.utils;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* 自定义密匙加密
*/
public class CiperDemo {
public static final String DES = "DES";
public static void main(String[] args) throws Exception {
String masterPassword = "YourPwd!@#123";
//key不能设置小于8位,使用*进行补全
String key = String.format("%8s", "qqaaaaa").replaceAll("\\s", "*");
//加密
byte[] mEncrypt = encrypt(masterPassword, key);
//打印加密
System.out.println("加密后:" + new String(mEncrypt));
//解密
byte[] mDerypt = derypt(mEncrypt, key);
//打印解密
System.out.println("解密后:" + new String(mDerypt));
}
private static byte[] derypt(byte[] mEncrypt, String key) throws Exception {
DESKeySpec keySpec = new DESKeySpec(key.getBytes());
SecretKey secret = SecretKeyFactory.getInstance(DES).generateSecret(keySpec);
Cipher cipher = Cipher.getInstance(DES);
cipher.init(Cipher.DECRYPT_MODE, secret);
return cipher.doFinal(Base64.getDecoder().decode(mEncrypt));
}
private static byte[] encrypt(String input, String key) throws Exception {
//密匙规范--把自己想变成密匙的字符串规范成密匙对象
DESKeySpec keySpec = new DESKeySpec(key.getBytes());
//通过密匙工厂获取密匙
SecretKey secretKey = SecretKeyFactory.getInstance(DES).generateSecret(keySpec);
//获取加密对象
Cipher cipher = Cipher.getInstance(DES);
//初始化对象
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//进行加密
byte[] bs = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encode(bs);
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。