Emil Andersson
Emil Andersson

Reputation: 33

Simple AES encryptor in Java

This is my first project in Java and I decided to make a simple text encryptor using AES.

The error I am getting is: The method init(int, Key) in the type Cipher is not applicable for the arguments (int, byte[])

Code:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Key;

import javax.crypto.*;
import java.util.*;

public class Encryptor {

    public static void main(String[] args) throws Exception {
        String FileName = "encryptedtext.txt";
        String FileName2 = "decryptedtext.txt";

        Scanner input = new Scanner(System.in);

       System.out.println("Enter your 16 character key here:");
       String EncryptionKey = input.next();



        KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
        KeyGen.init(128);

        Cipher AesCipher = Cipher.getInstance("AES");

        System.out.println("Enter text to encrypt or decrypt:");
        String Text = input.next();

        System.out.println("Do you want to encrypt or decrypt (e/d)");
        String answer = input.next();
        if (answer.equalsIgnoreCase("e")){

            byte[] byteKey = (EncryptionKey.getBytes());
            byte[] byteText = (Text).getBytes();

            AesCipher.init(Cipher.ENCRYPT_MODE, byteKey); // ERROR LINE
            byte[] byteCipherText = AesCipher.doFinal(byteText);
            Files.write(Paths.get(FileName), byteCipherText);


              }
        else if (answer.equalsIgnoreCase("d")){

            byte[] byteKey = (EncryptionKey.getBytes());
            byte[] byteText = (Text).getBytes();
            byte[] cipherText = Files.readAllBytes(Paths.get(FileName));

            AesCipher.init(Cipher.DECRYPT_MODE, byteKey); // ERROR LINE
            byte[] bytePlainText = AesCipher.doFinal(cipherText);
            Files.write(Paths.get(FileName2), bytePlainText);
        }
}

}

Thanks in advance! :)

Upvotes: 2

Views: 1967

Answers (3)

Notável Tom
Notável Tom

Reputation: 1

I had to encrypt a URL for been exposed in a external link, and I have created a class to encrypt on AES. Maybe this can help someone. I added a method to create my Random Initial Vector and it is on this class also.

package br.com.tokiomarine.captcha.encryption;

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

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.text.CharacterPredicates;
import org.apache.commons.text.RandomStringGenerator;

public class Encryptor 
{
    public static String encrypt(String key, String initVector, String value) throws Exception
    {
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

        byte[] encrypted = cipher.doFinal(value.getBytes());

        return Base64.encodeBase64URLSafeString(encrypted);
    }

    public static String decrypt(String key, String initVector, String encrypted) throws Exception 
    {
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

        byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

        return new String(original);
    }

    public static String generateInitVector() {
    RandomStringGenerator randomStringGenerator =
        new RandomStringGenerator.Builder()
            .withinRange('0', 'z')
            .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
            .build();
    return randomStringGenerator.generate(16);
    }

}

And here is my Test Class:

public class EcryptionTest {

    @Test
    public void encryptionTest() {
        try 
        {
            String key = "Key@TokioMarineC";
            for(int i = 0; i < 1000; i++) 
            {
                String initVector = Encryptor.generateInitVector();
                String encrypted = Encryptor.encrypt(key, initVector, "StringTeste");
                assertTrue("StringTeste".equals(Encryptor.decrypt(key, initVector, encrypted)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Upvotes: 0

Prashant
Prashant

Reputation: 118

You should not pass byte array directly to Cipher object, instead you need to create object of SecretKeySpecs.

This is complete Code

  import java.nio.file.Files;
  import java.nio.file.Paths;
  import javax.crypto.*;
  import javax.crypto.spec.IvParameterSpec;
  import javax.crypto.spec.SecretKeySpec;

  import java.util.*;

  public class Encrypter {

  public static void main(String[] args) throws Exception {
  String FileName = "encryptedtext.txt";
  String FileName2 = "decryptedtext.txt";

  Scanner input = new Scanner(System.in);

  System.out.println("Enter your 16 character key here:");
  String EncryptionKey = input.next();
  byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  IvParameterSpec ivspec = new IvParameterSpec(iv);


  KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
  KeyGen.init(128);


  Cipher AesCipher = Cipher.getInstance("AES/CFB/NoPadding");
  System.out.println("Enter text to encrypt or decrypt:");
  String Text = input.next();

  System.out.println("Do you want to encrypt or decrypt (e/d)");
  String answer = input.next();
  if (answer.equalsIgnoreCase("e")) {

   byte[] byteKey = (EncryptionKey.getBytes());
   byte[] byteText = (Text).getBytes();
   SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
   AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
   AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
   byte[] byteCipherText = AesCipher.doFinal(byteText);
   Files.write(Paths.get(FileName), byteCipherText);


  } else if (answer.equalsIgnoreCase("d")) {

   byte[] byteKey = (EncryptionKey.getBytes());
   byte[] byteText = (Text).getBytes();
   byte[] cipherText = Files.readAllBytes(Paths.get(FileName));

   SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
   AesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
   byte[] bytePlainText = AesCipher.doFinal(cipherText);
   Files.write(Paths.get(FileName2), bytePlainText);
  }
 }

}

Upvotes: 1

Emil Andersson
Emil Andersson

Reputation: 33

This is Full code

Full code:

import java.nio.file.Files;
import java.nio.file.Paths;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.util.*;

public class Encrypter {

public static void main(String[] args) throws Exception {
    String FileName = "encryptedtext.txt";
    String FileName2 = "decryptedtext.txt";

    Scanner input = new Scanner(System.in);

   System.out.println("Enter your 16 character key here:");
   String EncryptionKey = input.next();
   byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
   IvParameterSpec ivspec = new IvParameterSpec(iv);


    KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
    KeyGen.init(128);


    Cipher AesCipher = Cipher.getInstance("AES/CFB/NoPadding");
    System.out.println("Enter text to encrypt or decrypt:");
    String Text = input.next();

    System.out.println("Do you want to encrypt or decrypt (e/d)");
    String answer = input.next();
    if (answer.equalsIgnoreCase("e")){

        byte[] byteKey = (EncryptionKey.getBytes());
        byte[] byteText = (Text).getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
        AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivspec );
        AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivspec); // ERROR LINE
        byte[] byteCipherText = AesCipher.doFinal(byteText);
        Files.write(Paths.get(FileName), byteCipherText);


          }
    else if (answer.equalsIgnoreCase("d")){

        byte[] byteKey = (EncryptionKey.getBytes());
        byte[] byteText = (Text).getBytes();
        byte[] cipherText = Files.readAllBytes(Paths.get(FileName));

        SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
        AesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec,ivspec); // ERROR LINE
        byte[] bytePlainText = AesCipher.doFinal(cipherText);
        Files.write(Paths.get(FileName2), bytePlainText);
    }
}

}

Upvotes: 1

Related Questions