欢迎光临
我们一直在努力

用Java编写的密码算法类-JSP教程,Java技巧及代码

建站超值云服务器,限时71元/月

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;

}

}

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 用Java编写的密码算法类-JSP教程,Java技巧及代码
分享到: 更多 (0)

相关推荐

  • 暂无文章