package data;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
/**
* security 提供了一个安全算法类,其中包括对称密码算法和散列算法
*/
public final class security
{
/**
* 对称加密方法
* @param bytesource 需要加密的数据
* @return 经过加密的数据
* @throws exception
*/
public static byte[] symmetricencrypto(byte[] bytesource) throws exception
{
bytearrayoutputstream baos = new bytearrayoutputstream();
try
{
int mode = cipher.encrypt_mode;
secretkeyfactory keyfactory = secretkeyfactory.getinstance("des");
byte[] keydata = {1, 9, 8, 2, 0, 8, 2, 1};
deskeyspec keyspec = new deskeyspec(keydata);
key key = keyfactory.generatesecret(keyspec);
cipher cipher = cipher.getinstance("des");
cipher.init(mode, key);
int blocksize = cipher.getblocksize();
int position = 0;
int length = bytesource.length;
boolean more = true;
while(more)
{
if(position + blocksize <= length)
{
baos.write(cipher.update(bytesource, position, blocksize));
position += blocksize;
}
else
{
more = false;
}
}
if(position < length)
{
baos.write(cipher.dofinal(bytesource, position, length – position));
}
else
{
baos.write(cipher.dofinal());
}
return baos.tobytearray();
}
catch(exception e)
{
throw e;
}
finally
{
baos.close();
}
}
/**
* 对称解密方法
* @param bytesource 需要解密的数据
* @return 经过解密的数据
* @throws exception
*/
public static byte[] symmetricdecrypto(byte[] bytesource) throws exception
{
bytearrayoutputstream baos = new bytearrayoutputstream();
try
{
int mode = cipher.decrypt_mode;
secretkeyfactory keyfactory = secretkeyfactory.getinstance("des");
byte[] keydata = {1, 9, 8, 2, 0, 8, 2, 1};
deskeyspec keyspec = new deskeyspec(keydata);
key key = keyfactory.generatesecret(keyspec);
cipher cipher = cipher.getinstance("des");
cipher.init(mode, key);
int blocksize = cipher.getblocksize();
int position = 0;
int length = bytesource.length;
boolean more = true;
while(more)
{
if(position + blocksize <= length)
{
baos.write(cipher.update(bytesource, position, blocksize));
position += blocksize;
}
else
{
more = false;
}
}
if(position < length)
{
baos.write(cipher.dofinal(bytesource, position, length – position));
}
else
{
baos.write(cipher.dofinal());
}
return baos.tobytearray();
}
catch(exception e)
{
throw e;
}
finally
{
baos.close();
}
}
/**
* 散列算法
* @param bytesource 需要散列计算的数据
* @return 经过散列计算的数据
* @throws exception
*/
public static byte[] hashmethod(byte[] bytesource) throws exception
{
try
{
messagedigest currentalgorithm = messagedigest.getinstance("sha-1");
currentalgorithm.reset();
currentalgorithm.update(bytesource);
return currentalgorithm.digest();
}
catch(exception e)
{
throw e;
}
}
}
