PBEWithMD5AndDES加密
java 中的
加密:加密后的密文字符串=PasswordUtil.encrypt(待加密的明文字符串,生成密钥时所使用的密码,盐值)
解密:解密后的明文字符串=PasswordUtil.decrypt(待解密的密文字符串,生成密钥时所使用的密码,盐值)
C# 中的
加密:加密后的密文字符串=Rcode(待加密的明文字符串,生成密钥时所使用的密码,盐值)
JAVA
import java.io.File;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
public class PasswordUtil {
/**
* JAVA6支持以下任意一种算法 PBEWITHMD5ANDDES PBEWITHMD5ANDTRIPLEDES
* PBEWITHSHAANDDESEDE PBEWITHSHA1ANDRC2_40 PBKDF2WITHHMACSHA1
* */
/**
* 定义使用的算法为:PBEWITHMD5andDES算法
*/
public static final String ALGORITHM = "PBEWithMD5AndDES";//加密算法
public static final String Salt = "1111323423";//密钥,此处自定义
/**
* 定义迭代次数为100次
*/
private static final int ITERATIONCOUNT = 100;//此处自定义
/**
* 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作. 盐长度必须为8字节
*
* @return byte[] 盐值
* */
public static byte[] getSalt() throws Exception {
// 实例化安全随机数
SecureRandom random = new SecureRandom();
// 产出盐
return random.generateSeed(8);
}
public static byte[] getStaticSalt() {
// 产出盐
return Salt.getBytes();
}
/**
* 根据PBE密码生成一把密钥
*
* @param password
* 生成密钥时所使用的密码
* @return Key PBE算法密钥
* */
private static Key getPBEKey(String password) {
// 实例化使用的算法
SecretKeyFactory keyFactory;
SecretKey secretKey = null;
try {
keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
// 设置PBE密钥参数
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
// 生成密钥
secretKey = keyFactory.generateSecret(keySpec);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return secretKey;
}
/**
* 加密明文字符串
*
* @param plaintext
* 待加密的明文字符串
* @param password
* 生成密钥时所使用的密码
* @param salt
* 盐值
* @return 加密后的密文字符串
* @throws Exception
*/
public static String encrypt(String plaintext, String password, byte[] salt) {
Key key = getPBEKey(password);
byte[] encipheredData = null;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, ITERATIONCOUNT);
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
encipheredData = cipher.doFinal(plaintext.getBytes());
} catch (Exception e) {
}
return bytesToHexString(encipheredData);
}
/**
* 解密密文字符串
*
* @param ciphertext
* 待解密的密文字符串
* @param password
* 生成密钥时所使用的密码(如需解密,该参数需要与加密时使用的一致)
* @param salt
* 盐值(如需解密,该参数需要与加密时使用的一致)
* @return 解密后的明文字符串
* @throws Exception
*/
public static String decrypt(String ciphertext, String password, byte[] salt) {
Key key = getPBEKey(password);
byte[] passDec = null;
PBEParameterSpec parameterSpec = new PBEParameterSpec(getStaticSalt(), ITERATIONCOUNT);
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
passDec = cipher.doFinal(hexStringToBytes(ciphertext));
}
catch (Exception e) {
// TODO: handle exception
}
return new String(passDec);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param src
* 字节数组
* @return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 将十六进制字符串转换为字节数组
*
* @param hexString
* 十六进制字符串
* @return
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
public static void main(String[] args) {
File f = new File("C:/a/2.txt");
f.delete();
}
}
C#
public class PKCSKeyGenerator
{
byte[] key = new byte[8], iv = new byte[8];
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
public byte[] Key { get { return key; } }
public byte[] IV { get { return iv; } }
public ICryptoTransform Encryptor { get { return des.CreateEncryptor(key, iv); } }
public ICryptoTransform Decryptor { get { return des.CreateDecryptor(key, iv); } } // 多加一个Decryptor用于解密
public PKCSKeyGenerator() { }
public PKCSKeyGenerator(String keystring, byte[] salt, int md5iterations, int segments)
{
Generate(keystring, salt, md5iterations, segments);
}
public ICryptoTransform Generate(String keystring, byte[] salt, int md5iterations, int segments)
{
int HASHLENGTH = 16; //MD5 bytes
byte[] keymaterial = new byte[HASHLENGTH * segments]; //to store concatenated Mi hashed results
// --- get secret password bytes ----
byte[] psbytes;
psbytes = Encoding.UTF8.GetBytes(keystring);
// --- concatenate salt and pswd bytes into fixed data array ---
byte[] data00 = new byte[psbytes.Length + salt.Length];
Array.Copy(psbytes, data00, psbytes.Length); //copy the pswd bytes
Array.Copy(salt, 0, data00, psbytes.Length, salt.Length);//concatenate the salt bytes
// ---- do multi-hashing and concatenate results D1, D2 ...
// into keymaterial bytes ----
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = null;
byte[] hashtarget = new byte[HASHLENGTH + data00.Length]; //fixed length initial hashtarget
for (int j = 0; j < segments; j++)
{
// ---- Now hash consecutively for md5iterations times ------
if (j == 0) result = data00; //initialize
else
{
Array.Copy(result, hashtarget, result.Length);
Array.Copy(data00, 0, hashtarget, result.Length, data00.Length);
result = hashtarget;
}
for (int i = 0; i < md5iterations; i++)
result = md5.ComputeHash(result);
Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial
}
Array.Copy(keymaterial, 0, key, 0, 8);
Array.Copy(keymaterial, 8, iv, 0, 8);
return Encryptor;
}
}
调用方法
public static String Rcode(String message,String key,sbyte[] salt)
{
int count = 100; // 迭代次数
PKCSKeyGenerator cipher = new PKCSKeyGenerator(key, Array.ConvertAll(salt, a => (byte)a), count, 1);
byte[] src = Encoding.UTF8.GetBytes(message);
byte[] result = cipher.Encryptor.TransformFinalBlock(src, 0, src.Length);
string ret = "";
for (int i = 0; i < result.Length; i++)
{
ret += Convert.ToString(result[i], 16).PadLeft(2, '0');
}
return ret;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
2021-06-01 Docker安装PostgreSQL及还原备份