在自己的MIS系统使用简单的加密功能加密基本数据

王朝java/jsp·作者佚名  2006-01-08
宽屏版  字体: |||超大  

package skydev.modules.encryption;

import java.security.*;

import javax.crypto.*;

import javax.crypto.spec.*;

import java.io.*;

public class Encryption {

public Encryption() {}

/**

* 简单的加密系统

* @param infoToBeEncrypted 需要加密的数据

* @return 返回被加密的数据,数据长度20位

*/

public byte[] getEncryptedData(String infoToBeEncrypted) {

byte[] digest = null; //new byte[20];

try {

//SHA算法返回20位长度,MD5算法返回16位长度

//系统设计数据库使用20位长度,所以这里使用SHA算法

MessageDigest md = MessageDigest.getInstance("SHA"); //"SHA-1"

md.update(infoToBeEncrypted.getBytes("UTF-8"));

digest = md.digest();

}

catch (NoSuchAlgorithmException ex) {

}

finally {

return digest;

}

}

public String byte2hex(byte[] b) { //二进制转字符串

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();

}

}

package skydev.modules.encryption;

import junit.framework.*;

public class TestEncryption_getEncryptedData

extends TestCase {

private Encryption encryption = null;

protected void setUp() throws Exception {

super.setUp();

/**@todo verify the constructors*/

encryption = new Encryption();

}

protected void tearDown() throws Exception {

encryption = null;

super.tearDown();

}

public void testGetEncryptedData() {

String infoToBeEncrypted = "b";

byte[] expectedReturn = null;

byte[] actualReturn = encryption.getEncryptedData(infoToBeEncrypted);

assertEquals("return value", expectedReturn, actualReturn);

/**@todo fill in the test code*/

}

public static void main(String[] args) {

Encryption enc = new Encryption();

System.out.println(enc.byte2hex(enc.getEncryptedData("abcdef")));

System.out.println(enc.byte2hex(enc.getEncryptedData("ab")));

System.out.println(enc.byte2hex(enc.getEncryptedData("ab")));

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有