package packages;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Utils
{
public static String base64Encode(byte[] data)
{
if (data == null)
return null;
return Base64.encodeBase64String(data);
}
public static byte[] des3Encrypt(String encryptKey, byte[] metaData)
{
if ((encryptKey == null) || (metaData == null)) return null;
try
{
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(encryptKey.getBytes());
keyGenerator.init(112, secureRandom);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyGenerator.generateKey().getEncoded(), "DESede");
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(1, secretKeySpec);
return cipher.doFinal(metaData);
}
catch (Exception e)
{
}
return null;
}
public static byte[] base64Decode(String data)
{
if (data == null) return null;
return Base64.decodeBase64(data);
}
public static byte[] des3Decrypt(String decryptKey,byte[] cipherByte)
{
if ((decryptKey == null) || (cipherByte == null)) return null;
try
{
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(decryptKey.getBytes());
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
keyGenerator.init(112, secureRandom);
byte[] key = keyGenerator.generateKey().getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "DESede");
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(2, secretKeySpec);
return cipher.doFinal(cipherByte);
}
catch (Exception e)
{
}
return null;
}
//加密
public String EncryptForDes(String encryptKey,String metaData)
{
String res = "";
try
{
byte[] decryData = des3Encrypt(encryptKey,metaData.getBytes());
res = base64Encode(decryData);
}
catch(Exception e)
{
}
return res;
}
//解密
public String DecryptForDes(String encryptKey,String metaData)
{
String res = "";
try
{
byte[] encryData = base64Decode(metaData);
byte[] decryData = des3Decrypt(encryptKey,encryData);
res = new String(decryData);
}
catch(Exception e)
{
}
return res;
}
}