Cipher: init(int arg0, Key arg1, AlgorithmParameterSpec arg2) : Cipher « javax.crypto « Java by API






Cipher: init(int arg0, Key arg1, AlgorithmParameterSpec arg2)

   

import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
  public static void main(String[] args) throws Exception {
   // Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    byte[] input = "input".getBytes();
    byte[] ivBytes = "1234567812345678".getBytes();

    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
    generator.init(128);
    Key encryptionKey = generator.generateKey();
    System.out.println("key : " + new String(encryptionKey.getEncoded()));

    cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(ivBytes));
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);
    Key decryptionKey = new SecretKeySpec(encryptionKey.getEncoded(), encryptionKey.getAlgorithm());

    cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(ivBytes));
    byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
    int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
    ptLength += cipher.doFinal(plainText, ptLength);
    System.out.println("plain : " + new String(plainText));
  }
}

   
    
    
  








Related examples in the same category

1.Cipher: ENCRYPT_MODE
2.Cipher: DECRYPT_MODE
3.Cipher: getInstance(String arg0, String arg1)
4.Cipher: doFinal(byte[] arg0, int arg1)
5.Cipher: update(byte[] arg0, int arg1, int arg2, byte[] arg3, int arg4)