加密解密


import java.io.ByteArrayOutputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
* ���ܽ���
*
* @author weichangyong
*/
public class EncryUtil
{
private final static BASE64Encoder base64encoder = new BASE64Encoder();
private final static BASE64Decoder base64decoder = new BASE64Decoder();
private final static String encoding = "UTF-8";

/**
* �����ַ�
*/
public static String encry(String str)
{
String result = str;
if (str != null && str.length() > 0)
{
try
{
byte[] encodeByte = symmetricEncrypto(str.getBytes(encoding));
result = base64encoder.encode(encodeByte);
}
catch (Exception e)
{
e.printStackTrace();
}
}
return result;
}

/**
* �����ַ�
*/
public static String unEncry(String str)
{
String result = str;
if (str != null && str.length() > 0)
{
try
{
byte[] encodeByte = base64decoder.decodeBuffer(str);
byte[] decoder = EncryUtil.symmetricDecrypto(encodeByte);
result = new String(decoder, encoding);
}
catch (Exception e)
{
e.printStackTrace();
}
}
return result;
}

/**
*
* @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);
byte[] result = cipher.doFinal(byteSource);
return result;
}
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);
byte[] result = cipher.doFinal(byteSource);
return result;
}
catch (Exception e)
{
throw e;
}
finally
{
baos.close();
}
}

public static void main(String[] args)
{
String test = "15727364097250141";

String re = encry(test);

System.out.println(re);

String a = "8iNYkkN fT/oAQtCc52mpvgcdQ8jEpSU";

if(a.indexOf(" ")>0)
{
a = a.replace(' ', '+');
}

String un = unEncry(a);

System.out.println(un);
}

}

你可能感兴趣的:(Security,sun)