关于配置文件内容加密处理的感想

本文详细介绍了如何使用3DES加密技术对数据库和服务器路径进行加密处理,包括加密算法实现、代码示例以及解决转换过程中出现的问题。

前几天,公司提了一个需求,及让我们将数据库及服务器的路径做加密处理。这对于才接触工作的我来说,着实让我头疼半天。说实话,我一开始完全没想过加密问题,直到上次让我用3DES加密技术,对用户名和密码等做加密处理时稍微了解了一下。先说下3DES,这是对称加密算法,所谓对称加密,我的理解就是,加密解密通用一个密匙。

以下是3DES对字符串的处理代码:

public class ThreeDES
{
private static Key key;


/**
* 根据参数生成KEY

* @param strKey
*/
public static void getKey(String strKey)
{
try
{
KeyGenerator generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom(strKey.getBytes()));
key = generator.generateKey();
generator = null;
} catch (Exception e)
{
e.printStackTrace();
}
}


/**
* 加密String明文输入,String密文输出

* @param strMing
* @return
*/
public static String getEncString(String strMing)
{
String strMi = "";
try
{
return byte2hex(getEncCode(strMing.getBytes()));
} catch (Exception e)
{
e.printStackTrace();
}
return strMi;
}


/**
* 解密 以String密文输入,String明文输出

* @param strMi
* @return
*/
public static String getDesString(String strMi)
{
String strMing = "";
try
{
return new String(getDesCode(hex2byte(strMi.getBytes())));
} catch (Exception e)
{
e.printStackTrace();
}
return strMing;
}


/**
* 加密以byte[]明文输入,byte[]密文输出

* @param byteS
* @return
*/
private static byte[] getEncCode(byte[] byteS)
{
byte[] byteFina = null;
Cipher cipher;
try
{
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byteFina = cipher.doFinal(byteS);
} catch (Exception e)
{
e.printStackTrace();
} finally
{
cipher = null;
}
return byteFina;
}


/**
* 解密以byte[]密文输入,以byte[]明文输出

* @param byteD
* @return
*/
private static byte[] getDesCode(byte[] byteD)
{
Cipher cipher;
byte[] byteFina = null;
try
{
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byteFina = cipher.doFinal(byteD);
} catch (Exception e)
{
e.printStackTrace();
} finally
{
cipher = null;
}
return byteFina;
}


/**
* 二行制转字符串

* @param b
* @return
*/
public static String byte2hex(byte[] b)
{ // 一个字节的数,
// 转成16进制字符串
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++)
{
// 整数转成十六进制表示
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase(); // 转成大写
}


public static byte[] hex2byte(byte[] b)
{
if ((b.length % 2) != 0)
throw new IllegalArgumentException("长度不是偶数");
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += 2)
{
String item = new String(b, n, 2);
// 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个进制字节
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}

这是我查到的可以用于字符串之间的转换的方法。

起初我找到的是将其转换成字节数组然后根据16进制密匙处理得到的新的字节数组,但这个方法有一个缺点就是转换回原来的字符串必须得传字节数组,而我们将打乱后的字符串转成字节数组后,则一直报错,后来查原因发现是因为转码前后的字节数组长度不一样。因此和我们的需求相形甚远。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值