kikki's tech note

技術ブログです。UnityやSpine、MS、Javaなど技術色々について解説しています。

URLに利用できる文字列の暗号化・復号化を用意する

本章では、Javaで復号ができる暗号化処理について、共有します。

はじめに

Webアプリケーションで、システムが発行するIDをユーザに伝えずに特定できる文字列に変換する、といった必要性がありました。
そこで、URLでも利用できるよう、文字列を特定の文字に置き換える暗号化、暗号化された文字列を復号できる仕組みを用意しました。

暗号化処理

プログラム

以下、暗号化で利用した処理です。
※詳しい説明は省きます。

package com.hogehoge.project.common.util;

/**
 * 入力値を乱文字に変換
 */
public class ReversibleString {

    private final static String key = "hogehoge";

    public String encode(Long id) {
        return encode(Long.toString(id));
    }

    public String encode(String toencode) {
        String encrypt_key = MD5.encode(((int) (new Random().nextDouble() * 32000) + "").getBytes(), false);
        int ctr = 0;
        StringBuilder result = new StringBuilder();
        int len = toencode.length();
        for (int i = 0; i < len; i++) {
            ctr = (ctr == encrypt_key.length() ? 0 : ctr);
            result.append(encrypt_key.charAt(ctr));
            result.append(
                    (char) (toencode.charAt(i) ^ encrypt_key.charAt(ctr++)));
        }
        String encodedCharacters = Base64
                .encode(passKey(result.toString()).getBytes());
        return encodedCharacters.replace("+", "-").replace("/", "_");
    }

    public String decode(String todecode) {
        String replacedCharacters = todecode.replace("-", "+").replace("_",
                "/");
        try {
            String txt = passKey(
                    new String(Base64.decode(replacedCharacters.getBytes())));
            StringBuilder result = new StringBuilder();
            int len = txt.length();
            for (int i = 0; i < len; i++) {
                result.append((char) (txt.charAt(i) ^ txt.charAt(++i)));
            }
            return result.toString();
        } catch (ArrayIndexOutOfBoundsException ex) {
            return null;
        } catch (StringIndexOutOfBoundsException ex) {
            return null;
        }
    }

    private String passKey(String text) {
        String encrypt_key = MD5.encode(key.getBytes(), false);
        int ctr = 0;
        StringBuilder result = new StringBuilder();
        int len = text.length();
        for (int i = 0; i < len; i++) {
            ctr = (ctr == encrypt_key.length() ? 0 : ctr);
            result.append((char) (text.charAt(i) ^ encrypt_key.charAt(ctr++)));
        }
        return result.toString();
    }
}
public class MD5 {

    public static String encode(byte[] toencode, boolean useshort) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        md5.reset();
        md5.update(toencode);
        toencode = md5.digest();
        return useshort ? Hex.toString(toencode).substring(8, 24)
                : Hex.toString(toencode);
    }
}
public class Hex {

    public static String toString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (byte element : b) {
            int v = element & 0xFF;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase();
    }

    public static byte[] fromString(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i++) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}
public class Base64 {

    private static final char[] base64EncodeChars = new char[] {'A', 'B', 'C',
            'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
            'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
            'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
            '3', '4', '5', '6', '7', '8', '9', '+', '/'};

    private static byte[] base64DecodeChars = new byte[] {-1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,
            60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
            10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,
            -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
            38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
            -1, -1};

    public static String encode(byte[] data) {
        StringBuilder sb = new StringBuilder();
        int len = data.length;
        int i = 0;
        int b1, b2, b3;

        while (i < len) {
            b1 = data[i++] & 0xff;
            if (i == len) {
                sb.append(Base64.base64EncodeChars[b1 >>> 2]);
                sb.append(Base64.base64EncodeChars[(b1 & 0x3) << 4]);
                sb.append("==");
                break;
            }
            b2 = data[i++] & 0xff;
            if (i == len) {
                sb.append(Base64.base64EncodeChars[b1 >>> 2]);
                sb.append(Base64.base64EncodeChars[((b1 & 0x03) << 4)
                        | ((b2 & 0xf0) >>> 4)]);
                sb.append(Base64.base64EncodeChars[(b2 & 0x0f) << 2]);
                sb.append("=");
                break;
            }
            b3 = data[i++] & 0xff;
            sb.append(Base64.base64EncodeChars[b1 >>> 2]);
            sb.append(Base64.base64EncodeChars[((b1 & 0x03) << 4)
                    | ((b2 & 0xf0) >>> 4)]);
            sb.append(Base64.base64EncodeChars[((b2 & 0x0f) << 2)
                    | ((b3 & 0xc0) >>> 6)]);
            sb.append(Base64.base64EncodeChars[b3 & 0x3f]);
        }
        return sb.toString();
    }

    public static byte[] decode(byte[] data) {
        int len = data.length;
        ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
        int i = 0;
        int b1, b2, b3, b4;

        while (i < len) {

            /* b1 */
            do {
                b1 = Base64.base64DecodeChars[data[i++]];
            } while (i < len && b1 == -1);
            if (b1 == -1) {
                break;
            }

            /* b2 */
            do {
                b2 = Base64.base64DecodeChars[data[i++]];
            } while (i < len && b2 == -1);
            if (b2 == -1) {
                break;
            }
            buf.write(((b1 << 2) | ((b2 & 0x30) >>> 4)));

            /* b3 */
            do {
                b3 = data[i++];
                if (b3 == 61) {
                    return buf.toByteArray();
                }
                b3 = Base64.base64DecodeChars[b3];
            } while (i < len && b3 == -1);
            if (b3 == -1) {
                break;
            }
            buf.write((((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

            /* b4 */
            do {
                b4 = data[i++];
                if (b4 == 61) {
                    return buf.toByteArray();
                }
                b4 = Base64.base64DecodeChars[b4];
            } while (i < len && b4 == -1);
            if (b4 == -1) {
                break;
            }
            buf.write((((b3 & 0x03) << 6) | b4));
        }
        return buf.toByteArray();
    }
}

使い方

ReversibleString reversibleString = new ReversibleString ();
// 暗号化
String encoded = reversibleString.encode("hogehoge");
// 復号化
String decoded = reversibleString.decode(encoded);

筆休め

URLで利用できる暗号・復号の仕組みは、色々応用が効くと思います。一度試してみてください。

以上、「URLに利用できる文字列の暗号化・復号化を用意する」でした。


※無断転載禁止 Copyright (C) kikkisnrdec All Rights Reserved.