暗号化して結果を書きだす前にサイズを計算しておきたいことがある。
時間がかかっても一旦、暗号化実行をするしかないのか。。。
public final class Criptor{
private Key secretKey;
private AlgorithmParameterSpec ivParamSpec;
public Criptor(byte salt,byte vector){
secretKey = new SecretKeySpec(salt,"AES");
ivParamSpec = new IvParameterSpec(vector);
}
public final int encryptSize(byte data){
try{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,this.secretKey,this.ivParamSpec);
byte iv = cipher.getIV();
byte enc = cipher.doFinal(data);
return iv.length + enc.length;
}catch(Exception e){
throw new RuntimeException(e);
}
}
public final byte encrypt(byte data){
try{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,this.secretKey,this.ivParamSpec);
byte iv = cipher.getIV();
byte enc = cipher.doFinal(data);
byte bs = new byte[iv.length + enc.length];
System.arraycopy(iv,0,bs,0,iv.length);
System.arraycopy(enc,0,bs,iv.length,enc.length);
return bs;
}catch(Exception e){
throw new RuntimeException(e);
}
}
public final byte decrypt(byte data){
try{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE,this.secretKey,this.ivParamSpec);
int blocksize = cipher.getBlockSize();
return cipher.doFinal(data,blocksize,data.length - blocksize);
}catch(Exception e){
throw new RuntimeException(e);
}
}
}