生成DES密钥、保存密钥到文件、从文件读取密钥、加密、解密等操作。
java 代码
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.security.InvalidKeyException;
- import java.security.Key;
- import java.security.NoSuchAlgorithmException;
- import java.security.SecureRandom;
- import java.security.Security;
- import java.security.spec.InvalidKeySpecException;
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKeyFactory;
- import javax.crypto.spec.DESKeySpec;
- import org.apache.commons.configuration.ConfigurationException;
- import org.apache.commons.configuration.PropertiesConfiguration;
- import com.sun.crypto.provider.SunJCE;
- public class DESTest {
- private static final String ALGORITHM = "DES";
- /**
- * 获得DES加密的密钥。在交易处理的过程中应该定时更 换密钥。需要JCE的支持,如果jdk版本低于1.4,则需要
- * 安装jce-1_2_2才能正常使用。
- *
- * @return Key 返回对称密钥
- * @throws java.security.NoSuchAlgorithmException
- * @see util.EncryptUtil 其中包括加密和解密的方法
- */
- public Key generateKey() throws EncryptException {
- try {
- Security.insertProviderAt(new SunJCE(), 1);
- KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
- generator.init(new SecureRandom());
- Key key = generator.generateKey();
- return key;
- } catch (NoSuchAlgorithmException e) {
- throw new EncryptException(e);
- }
- }
- /**
- * 得到一个密钥的密码
- *
- * @param key
- * 密钥
- * @param cipherMode
- * 密码的类型
- * @return Cipher
- * @throws util.EncryptException
- * 当加密出现异常情况时,产生异常信息
- */
- public Cipher getCipher(Key key, int cipherMode) throws EncryptException {
- try {
- Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
- cipher.init(cipherMode, key);
- return cipher;
- } catch (Exception e) {
- // e.printStackTrace();
- throw new EncryptException("Generate Cipher occurs Exception.["
- + e.getMessage() + "]");
- }
- }
- public void saveKey(Key key, String filename) throws EncryptException {
- if (key == null) {
- return;
- }
- File file = new File(filename);
- try {
- file.createNewFile();
- } catch (IOException e1) {
- throw new EncryptException(e1);
- }
- try {
- PropertiesConfiguration publicConfig = new PropertiesConfiguration(
- filename);
- publicConfig.setProperty("Key", Utils.bytesToHexStr(key
- .getEncoded()));
- publicConfig.save();
- } catch (ConfigurationException e) {
- throw new EncryptException(e);
- }
- }
- public Key loadKey(String filename) throws EncryptException {
- try {
- PropertiesConfiguration config = new PropertiesConfiguration(
- new File(filename));
- String privateKeyValue = config.getString("Key");
- // 从原始密钥数据创建DESKeySpec对象
- DESKeySpec dks = new DESKeySpec(Utils
- .hexStrToBytes(privateKeyValue));
- // 创建一个密钥工厂,然后用它把DESKeySpec转换成Secret Key对象
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
- Key key = keyFactory.generateSecret(dks);
- return key;
- } catch (ConfigurationException e) {
- throw new EncryptException(e);
- } catch (NoSuchAlgorithmException e) {
- throw new EncryptException(e);
- } catch (InvalidKeyException e) {
- throw new EncryptException(e);
- } catch (InvalidKeySpecException e) {
- throw new EncryptException(e);
- }
- }
- public byte[] doEncrypt(Key key, byte[] data) throws EncryptException {
- try {
- // Get a cipher object
- Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
- // Encrypt
- cipher.init(Cipher.ENCRYPT_MODE, key);
- // byte[] stringBytes = amalgam.getBytes("UTF8");
- byte[] raw = cipher.doFinal(data);
- // BASE64Encoder encoder = new BASE64Encoder();
- // String base64 = encoder.encode(raw);
- return raw;
- } catch (Exception e) {
- e.printStackTrace();
- throw new EncryptException("Do encrypt occurs Exception.["
- + e.getMessage() + "]");
- }
- }
- public byte[] doDecrypt(Key key, byte[] raw) throws EncryptException {
- try {
- // Get a cipher object
- Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
- // Decrypt
- cipher.init(Cipher.DECRYPT_MODE, key);
- // BASE64Decoder decoder = new BASE64Decoder();
- // byte[] raw = decoder.decodeBuffer(data);
- byte[] data = cipher.doFinal(raw);
- // String result = new String(stringBytes, "UTF8");
- // System.out.println("the decrypted data is: " + result);
- return data;
- } catch (Exception e) {
- e.printStackTrace();
- throw new EncryptException("Do decrypt occurs Exception.["
- + e.getMessage() + "]");
- }
- }
- public static void main(String[] args) {
- DESTest bean = new DESTest();
- String keyFilename = "d:/key.txt";
- String srcFilename = "d:/temp/1.txt";
- String encryptFilename = "D:/temp/encrypt_result.dat";
- String decryptFilename = "D:/temp/decrypt_result.txt";
- Key key = bean.initKey(keyFilename);
- DESEncrypt encrypt = DESEncryptImpl.getInstance();
- try {
- // encrypt
- System.out.println("encrypt begin ...");
- FileInputStream in = new FileInputStream(srcFilename);
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- byte[] tmpbuf = new byte[1024];
- int count = 0;
- while ((count = in.read(tmpbuf)) != -1) {
- bout.write(tmpbuf, 0, count);
- tmpbuf = new byte[1024];
- }
- in.close();
- byte[] orgData = bout.toByteArray();
- byte[] raw = encrypt.doEncrypt(key, orgData);
- OutputStream out = new FileOutputStream(new File(encryptFilename));
- out.write(raw);
- out.close();
- System.out.println("encrypt done ...");
- // decrypt
- System.out.println("decrypt begin ...");
- in = new FileInputStream(encryptFilename);
- bout = new ByteArrayOutputStream();
- tmpbuf = new byte[1024];
- count = 0;
- while ((count = in.read(tmpbuf)) != -1) {
- bout.write(tmpbuf, 0, count);
- tmpbuf = new byte[1024];
- }
- in.close();
- orgData = bout.toByteArray();
- byte[] data = encrypt.doDecrypt(key, orgData);
- out = new FileOutputStream(new File(decryptFilename));
- out.write(data);
- out.flush();
- out.close();
- System.out.println("decrypt done ...");
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (EncryptException e) {
- e.printStackTrace();
- }
- }
- /*
- * test
- */
- public Key initKey(String keyFilename) {
- DESControl control = DESControlImpl.getInstance();
- File keyFile = new File(keyFilename);
- Key key = null;
- try {
- if (!keyFile.exists()) {
- System.out.println("generate Key.");
- key = control.generateKey();
- control.saveKey(key, keyFilename);
- return key;
- } else {
- System.out.println("load Key.");
- key = control.loadKey(keyFilename);
- return key;
- }
- } catch (EncryptException e) {
- e.printStackTrace();
- }
- return key;
- }
- }