论坛首页 Java企业应用论坛

sample code about TripleDES

浏览 3650 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-10-12  
刚刚对triple-DES 研究了一下,整理出了下面的代码:
package com.nxj.cpp.usersecurity.common.util;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

/**
 * The class is encryption/decryption the password by "Triple-DES" Algorithm.
 * @author justin.gong
 *
 */
public class TripleDES {
    
    /**
     * the file store key.
     */
    private static File keyFile = new File("./secretKey");

    /**
     * store the key Object.
     */
    private static SecretKey key = null;

    static {
        try {
            if (!keyFile.exists()) {
                key = generateKey();
                writeKey(key, keyFile);
            } else {
                key = readKey();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }

    /**
     * Generate a secret TripleDES encryption/decryption key.
     */
    private static SecretKey generateKey() throws NoSuchAlgorithmException {
        // Get a key generator for Triple DES (a.k.a DESede)
        KeyGenerator keygen = KeyGenerator.getInstance("DESede");
        // Use it to generate a key
        return keygen.generateKey();
    }

    /**
     * Save the specified TripleDES SecretKey to the specified file.
     * @param key
     * @param file
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private static void writeKey(SecretKey key, File file) throws IOException,
            NoSuchAlgorithmException, InvalidKeySpecException {
        // Convert the secret key to an array of bytes like this
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
        DESedeKeySpec keyspec = (DESedeKeySpec) keyfactory.getKeySpec(key,
                DESedeKeySpec.class);
        byte[] rawkey = keyspec.getKey();

        // Write the raw key to the file
        FileOutputStream out = new FileOutputStream(file);
        out.write(rawkey);
        out.close();
    }

    /**
     * Read a TripleDES secret key from the specified file.
     * @return key created according to the keyfile
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws InvalidKeySpecException
     */
    private static SecretKey readKey() throws IOException,
            NoSuchAlgorithmException, InvalidKeyException,
            InvalidKeySpecException {
        // Read the raw bytes from the keyfile
        DataInputStream in = new DataInputStream(new FileInputStream(keyFile));
        byte[] rawkey = new byte[(int) keyFile.length()];
        in.readFully(rawkey);
        in.close();

        // Convert the raw bytes to a secret key like this
        DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
        SecretKey key = keyfactory.generateSecret(keyspec);
        return key;
    }

    /**
     * encrypt the password.
     * @param password
     * @return password after encrypt
     */
    public static String encrypt(String password) {
        String encodedPassword = null;
        try {
            if ((password != null) && (!"".equals(password.trim()))
                    && (key != null)) {
                Cipher cipher;
                cipher = Cipher.getInstance("DESede");
                cipher.init(Cipher.ENCRYPT_MODE, key);
                byte[] cleartext = password.getBytes();
                byte[] ciphertext = cipher.doFinal(cleartext);
                StringBuffer buf = new StringBuffer();
                for (int i = 0; i < ciphertext.length; i++) {
                    buf.append(Byte.toString(ciphertext[i]) + "|");
                }
                encodedPassword = buf.toString();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return encodedPassword;
    }

    /**
     * decrypt the password.
     * @param password
     * @return password after decrypt
     */
    public static String decrypt(String password) {
        String decodedPassword = null;
        if ((password != null) && (!"".equals(password.trim()))
                && (key != null)) {
            ArrayList<String> list = new ArrayList<String>();
            StringTokenizer toker = new StringTokenizer(password, "|");
            while (toker.hasMoreElements()) {
                list.add(toker.nextToken());
            }
            byte[] cleartext = new byte[list.size()];
            int i = 0;
            for (Iterator iter = list.iterator(); iter.hasNext();) {
                String element = (String) iter.next();
                cleartext[i] = Byte.parseByte(element);
                i++;
            }

            Cipher cipher;
            try {
                cipher = Cipher.getInstance("DESede");
                cipher.init(Cipher.DECRYPT_MODE, key);
                byte[] ciphertext = cipher.doFinal(cleartext);
                decodedPassword = new String(ciphertext);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            }
        }
        return decodedPassword;
    }
}


论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics