Java/暗号化復号化処理

Java/暗号化復号化処理

3DES-CBC NoPadding

暗号化

public String crypt3Des(String src) {
    String key = "hogehogehoge";
    String initVector = "piyopiyo"
    src = StringUtil.multipleBytePadCharacter(src, 8, " ");
    SecretKey sKey = this.to3DesSecretKey(key);
    byte[] ivByte = initVector.getBytes();
    IvParameterSpec ivSpec = new IvParameterSpec(ivByte);
    String output = null;
    try {
        Cipher cipher = null;
        cipher = Cipher.getInstance("DESede/CBC/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, sKey, ivSpec);
        byte[] encryptedByte = cipher.doFinal(src.getBytes());
        BASE64Encoder encoder64 = new BASE64Encoder();
        output = encoder64.encodeBuffer(encryptedByte);
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
    return output;
}

復号化

public String decrypt3Des(String src) {
    String key = "hogehogehoge";
    String initVector = "piyopiyo";
    String output = "";
    SecretKey sKey = this.to3DesSecretKey(key);
    byte[] ivByte = initVector.getBytes();
    IvParameterSpec ivSpec = new IvParameterSpec(ivByte);
    try {
        Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, sKey, ivSpec);
        BASE64Decoder decoder64 = new BASE64Decoder();
        byte[] srcByte = decoder64.decodeBuffer(src.trim());
        byte[] decryptedMessage = cipher.doFinal(srcByte);
        output = new String(decryptedMessage, "UTF-8");
        output = output.trim();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }
    return output;
}
 
public SecretKey to3DesSecretKey(String key) {
    byte[] kyebyte = key.getBytes();
    byte[] keyByte24 = new byte[24];
    for (int i = 0; i < kyebyte.length; i++) {
        keyByte24[i] = kyebyte[i];
    }
    return new SecretKeySpec(keyByte24, "DESede");
}

タグ

java/encrypt_decrypt.txt · 最終更新: 2012-01-19 20:51 by ore