62,615
社区成员
发帖
与我相关
我的任务
分享
package com.hnzskj.encrypt;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.apache.commons.codec.binary.Base64;
public class Encrypt {
/**
* 对称加密-产生密钥
*/
public static void generatorKey() {
SecretKey key = null;
try {
// 指定算法,这里为DES;如果想用Blowfish算法,则用getInstance("Blowfish")
// BouncyCastle基本上支持所有通用标准算法
KeyGenerator keygen = KeyGenerator.getInstance("DES");
// 指定密钥长度,长度越高,加密强度越大
keygen.init(56);
// 产生密钥
key = keygen.generateKey();
// 构造输出文件,这里的目录是动态的,根据用户名称来构造目录
ObjectOutputStream keyFile = new ObjectOutputStream(
new FileOutputStream("c:\\encrypt\\yhb.des"));
keyFile.writeObject(key);
keyFile.close();
} catch (NoSuchAlgorithmException e5) {
// generateKey()抛出的异常
e5.printStackTrace();
System.out.print("no such algorithm");
System.exit(0);
} catch (IOException e4) {
e4.printStackTrace();
System.out.print("error when generate the deskey");
System.exit(0);
}
}
/**
* 方法描述:对称加密-读取密钥
*/
private static SecretKey getSecretKey() {
// 从密钥文件中读密钥
SecretKey key = null;
try {
ObjectInputStream keyFile = new ObjectInputStream(
new FileInputStream("c:\\encrypt\\yhb.des"));
key = (SecretKey) keyFile.readObject();
keyFile.close();
} catch (FileNotFoundException ey1) {
ey1.printStackTrace();
System.out.println("Error when read keyFile");
System.exit(0);
} catch (Exception ey2) {
System.out.println("error when read the keyFile");
ey2.printStackTrace();
}
return key;
}
/**
* 方法描述:加密文本信息
*/
public static String encrypt(String encryptStr) {
SecretKey key = getSecretKey();
Cipher cipher = null;
try {
// 设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
// 设置解密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (Exception ey3) {
ey3.printStackTrace();
System.out.println("Error when create the cipher");
}
byte[] data = null;
try {
data = cipher.doFinal(encryptStr.getBytes());
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
encryptStr = Base64.encodeBase64String(data);
return encryptStr;
}
public static void main(String[] args) {
System.out.println(encrypt("加密字符串"));
}
}
try {
// 设置算法,应该与加密时的设置一样
cipher = Cipher.getInstance("DES");
// 设置解密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (Exception ey3) {
ey3.printStackTrace();
System.out.println("Error when create the cipher");
// 这里都出现异常了,cipher还是为null
}
byte[] data = null;
try {
//运行到这里,cipher为空肯定出空指针异常啊
data = cipher.doFinal(encryptStr.getBytes());
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {