您的位置:首页 > 其它

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

2004-01-26 01:34 901 查看
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
& 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")));

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐