您的位置:首页 > 其它

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

2015-01-02 14:05 507 查看
前几天,公司提了一个需求,及让我们将数据库及服务器的路径做加密处理。这对于才接触工作的我来说,着实让我头疼半天。说实话,我一开始完全没想过加密问题,直到上次让我用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
& 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进制密匙处理得到的新的字节数组,但这个方法有一个缺点就是转换回原来的字符串必须得传字节数组,而我们将打乱后的字符串转成字节数组后,则一直报错,后来查原因发现是因为转码前后的字节数组长度不一样。因此和我们的需求相形甚远。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐