JMemo039

BACK

3DESで文字列を暗号化

package test;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

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

//参考
//http://hondou.homedns.org/pukiwiki/pukiwiki.php?JavaSE%20DES%A1%A23DES%A1%A2AES%B0%C5%B9%E6

public class EncryptUtil {
    private static final String KEY_STRING = "3DESIsEncrypt3timesByDES"; // 24byte(192bit)

    /**
     * Main Routine
     *
     * @param args
     *            Commandline Argument
     */
    public static void main(String[] args) {
        String pass = "this is a pen.";

        System.out.println(pass);
        String x = encryptBy3DES(pass);
        System.out.println(x);
        String y = decryptBy3DES(x);
        System.out.println(y);
    }

    /**
     * 3DESで暗号化する
     *
     * @param source
     *            平文文字列
     * @return 暗号化された文字列
     */
    public static String encryptBy3DES(String source) {
        String result = null;

        try {
            final SecretKey key = SecretKeyFactory.getInstance("DESEde")
                    .generateSecret(new DESedeKeySpec(KEY_STRING.getBytes()));
            final Cipher cipher = Cipher.getInstance(key.getAlgorithm()
                    + "/ECB/PKCS5Padding");

            cipher.init(Cipher.ENCRYPT_MODE, key);
            final byte[] rawText = source.getBytes();
            final byte[] encryptedText = cipher.doFinal(rawText);
            result = bytesToHexString(encryptedText);

        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        }

        return result;
    }

    /**
     * 3DESで復号化する
     *
     * @param source
     *            暗号化された文字列
     * @return 復号後の文字列
     */
    public static String decryptBy3DES(String source) {
        String result = null;

        try {
            final SecretKey key = SecretKeyFactory.getInstance("DESEde")
                    .generateSecret(new DESedeKeySpec(KEY_STRING.getBytes()));
            final Cipher cipher = Cipher.getInstance(key.getAlgorithm()
                    + "/ECB/PKCS5Padding");

            cipher.init(Cipher.DECRYPT_MODE, key);
            final byte[] encryptedText = hexStringToBytes(source);
            final byte[] decryptedText = cipher.doFinal(encryptedText);
            result = new String(decryptedText);

        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        }

        return result;
    }

    /**
     * バイト配列を16進数文字列に変換する
     *
     * @param source
     *            バイト配列
     * @return 変換された文字列
     */
    private static String bytesToHexString(byte[] source) {
        if (source == null) {
            return null;
        }

        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < source.length; i++) {
            sb.append(String.format("%02X", source[i]));
        }
        return sb.toString();
    }

    /**
     * 16進数文字列をバイト配列に変換する
     *
     * @param source
     *            16進数文字列
     * @return 変換されたバイト配列
     */
    private static byte[] hexStringToBytes(String source) {
        if (source == null) {
            return null;
        }

        byte[] result = new byte[source.length() / 2];

        int j = 0;
        for (int i = 0; i < source.length(); i += 2) {
            result[j++] = (byte) Integer.parseInt(source.substring(i, i + 2),
                    16);
        }

        return result;
    }
}
最終更新:2013年08月21日 09:57