[Java] AES/CBC/PKCS5Padding で暗号化,復号化

スポンサーリンク

鍵長は 128 ビット.

暗号

package mokyu

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class MyEncrypter {
	
	private String message;
	
	MyEncrypter(String message){
		this.message = message;
	}
	
	ArrayList<byte[]> encrypt(){
		
		ArrayList<byte[]> ret = new ArrayList<byte[]>();
		
		String keyString = "0123456789ABCDEF"; // 16byte = 128bit
		SecretKeySpec key = new SecretKeySpec(keyString.getBytes(), "AES");
		
		Cipher c;
		try {
			c = Cipher.getInstance("AES/CBC/PKCS5Padding");
			c.init(Cipher.ENCRYPT_MODE, key);
			byte[] encryptedMessage = c.doFinal(message.getBytes());
			byte[] iv = c.getIV();
			ret.add(encryptedMessage);
			ret.add(iv);
		} 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 ret;
	}

}

復号

package mokyu

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class MyDecrypter {
	
	private byte[] encryptedMessage;
	private byte[] iv;
	
	ResultDecrypter(byte[] encryptedMessage, byte[] iv){
		this.encryptedMessage = encryptedMessage;
		this.iv = iv;
	}
	
	byte[] decrypt(){
		
		byte[] ret = null;
		
		String keyString = "0123456789ABCDEF"; // 16byte = 128bit
		SecretKeySpec key = new SecretKeySpec(keyString.getBytes(), "AES");
		
		try {
			Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec ips = new IvParameterSpec(iv);
			c.init(Cipher.DECRYPT_MODE, key, ips);
			byte[] decryptedMessage = c.doFinal(encryptedMessage);
			ret = decryptedMessage;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		
		return ret;
	}

}

Java
スポンサーリンク
コピペワールド