import java.security.Key;
import java.security.Security;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;//BC的提供者
public class TripleDES
{ static String strToEnc="这里是明文内容,请把短信内容赋给它";//明文
static byte[] plainText = strToEnc.getBytes();//明文转为字节型
static String keydesede="k4@#$%^&^F*O)_<>:?9684cai&4^*3J5",HexcipherText;//固定密钥,共32个字节,这个密钥可以随便设定32个字节,发送消息要传送
static byte[] key=keydesede.getBytes();//密钥转字节型
static byte[] cipherTextdes;//全局的密文变量,此处应该把密文赋给它,发送消息要传送
static byte[] iv="a^&*6_i(".getBytes();//IV随机向量
public static void main(String[] args)//主函数
{
test_Cipher(key,plainText,iv);//加密函数,参数为密钥,明文
test_Decrypt(key,HexcipherText,iv);//解密函数,参数为密钥规范后的ky,和密文
}
public static String test_Cipher(byte key[], byte data[],byte[] iv)//加密函数
{
try
{
System.out.println("\n开始生成DESede密钥");
IvParameterSpec ivps;
ivps = new IvParameterSpec(iv, 0, iv.length);
SecretKeyFactory kf = SecretKeyFactory.getInstance("DESede"); //设置密钥工厂模式为DESede,可以设置为AES、DES、DESede、PBEWith等模式
DESedeKeySpec ks = new DESedeKeySpec(key); //新建密钥规范, 使密钥规范化
SecretKey ky2 = kf.generateSecret(ks); //生成密钥,最后的执行密钥是ky2
Cipher cipher=Cipher.getInstance("DESede/OFB/PKCS5Padding");
//打印Cipher对象密码服务提供者信息
System.out.println("\n"+cipher.getProvider().getInfo());
//加密
System.out.println("\n开始加密");
cipher.init(Cipher.ENCRYPT_MODE,ky2,ivps);//cipher对象初始化,设置为加密
byte[] cipherText=cipher.doFinal(plainText);//结束数据加密,输出密文
cipherTextdes=cipherText;//把密文赋给全局的密文变量
//HexcipherText1=byte2HexStr(cipherTextdes);
HexcipherText=Base64Coder.encode(cipherTextdes);
System.out.println("加密完成,密文为:");
System.out.println(HexcipherText);
//System.out.println(new String(cipherText));//打印乱码密文
return HexcipherText;//返回密文,返回的是字符串型的密文
}
catch (Exception e)
{
System.out.println("加密出错");//这里在放入android时请去掉
return null;
}
}
public static byte[] test_Decrypt(byte key[], String datades,byte[] iv)//解密函数,要输入的密文要求为字符串形式
{
byte[] newPlainText;
byte[] data;
try
{
data=Base64Coder.decode(datades);
IvParameterSpec ivps;
ivps = new IvParameterSpec(iv, 0, iv.length);
KeySpec ks = new DESedeKeySpec(key);
SecretKeyFactory kf = SecretKeyFactory.getInstance("DESede");
SecretKey ky = kf.generateSecret(ks);
Cipher cipher = Cipher.getInstance("DESede/OFB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, ky,ivps);
//输出原文
newPlainText = cipher.doFinal(data);//这里在放入android时请去掉
System.out.println("解密完成,明文为:");//这里在放入android时请去掉
System.out.println(new String(newPlainText));
return newPlainText;//返回明文
}
catch (Exception e)
{
System.out.println("解密出错");//这里在放入android时请去掉
return null;
}
}
}
- 1
- 2
前往页