1

First I want to mention that I have looked at all other questions related to this kind on encryption, so this is a unique question, not duplicate in any form.

I have been working on this problem for three days now, I finally got a piece of code that encrypts, but I doubt that this encryption is correct because the encrypted text is too short, that is what online decryptor tools are telling me any how, because I want decryption to be done using stand alone tool (by providing the other party a secret key), these are the tools I tried using, they all agree on one thing: The provided data/text is too small.

The code I have is as simple as I tried to make it:

import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.Base64;

public class DataEncrypt {

    //static String plainText = "This is a plain text which need to be encrypted by Java AES 256 GCM Encryption Algorithm";
    public static final int AES_KEY_SIZE = 256;
    public static final int GCM_IV_LENGTH = 12;
    public static final int GCM_TAG_LENGTH = 16;


    public  String encrypt(byte[] plaintext)
    {
        String res=null;
        try {


            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(AES_KEY_SIZE);

            // Generate Key
            SecretKey key = keyGenerator.generateKey();
            byte[] IV = new byte[GCM_IV_LENGTH];
            SecureRandom random = new SecureRandom();
            random.nextBytes(IV);


            // Get Cipher Instance
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

            // Create SecretKeySpec
            SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

            // Create GCMParameterSpec
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);

            // Initialize Cipher for ENCRYPT_MODE
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);

            // Perform Encryption
            byte[] cipherText = cipher.doFinal(plaintext);

             res= "cipheredText= " + cipherText.toString() + "\nkeySpec=" + keySpec.toString() + "\nKey=" +
                     Base64.getEncoder().encodeToString(key.getEncoded());
        }catch (Exception e){

        }
        return res;
    }

}

Where this line is for debugging:

 res= "cipheredText= " + cipherText.toString() + "\nkeySpec=" + keySpec.toString() + "\nKey=" +
                     Base64.getEncoder().encodeToString(key.getEncoded())

This is how I am calling the function:

//string number entered here is not actually the same one I used, but it has the same length
    System.out.println(dataEncrypt.encrypt("320900401024111".getBytes()));

This is the console output:

cipheredText= [B@2d612431
keySpec=javax.crypto.spec.SecretKeySpec@fffe956d
Key=3OF/L6XHck3imIRO9q8yi/Dr8+h6cMw99/21zMlByuo=

So I have a key (from the output) which i can use in an online tool to decrypt, and I have an encrypted text (cipheredText) to enter in the tool, but the cipheredText seems to be short, or generally the tools are just not able to give me back my original string (320900401024111).

Tools I have used for decryption:

I am not an expert with encryption, but I am asking this question because I have exhausted most efforts, not for the lack of trying, I just need help with:

  1. Is there something wrong with this code?
  2. Is there somethign wrong with the result of this code?
  3. Why I am unable to decrypt using the tools mentioned?

Thank you for any effort to help.

aero
  • 372
  • 1
  • 4
  • 18
  • 1
    You convert cipherText into a string but the result of an encryption are bytes in the range of 0 to 255 and a lot of them can't get a letter or number with the result that your string is much to short. If you need an output string convert the byte array with Base64 and vice versa. Second use charset encoding for conversion string to byte array. – Michael Fehr Sep 04 '20 at 20:16
  • 4
    @MichaelFehr: `new String(byte[] /*nocset*/)` as in Mauricio's answer would have the problem of losing _some_ data; this code does `byte[].toString()` which doesn't even attempt to convert any of the data at all, just shows the type (as `[B`) and hashcode. aero: there are _hundreds_ of Qs about the fact `toString()` is totally wrong to display arrays; this is not a crypto problem at all, just basic Java 101. Of the websites you link three are clearly useless toys, and the fourth might reasonably be considered a tool but doesn't support – dave_thompson_085 Sep 04 '20 at 20:48
  • @MichaelFehr Thanks for the reply, so I am actually now getting: some question marks inside a diamond and other weird symbols when i use : new String(cipherText, StandardCharsets.UTF_8), for getting cipheredText string. Still tweaking it to make it work – aero Sep 04 '20 at 21:01
  • @dave_thompson_085 , these links will end up being the only method for decryption, because the encrypted data supposed to be logged into a file, which will be read by human eye, not a program, so decrypting them will have to be done manually, I'll be grateful if you can suggest something else. – aero Sep 04 '20 at 21:03
  • 3
    I kindly suggested to use a Base64 encoding for the conversion cipherText to cipheredText. On decryption use Base64 decoding. – Michael Fehr Sep 04 '20 at 21:07
  • @MichaelFehr , thanks, i am getting full string now, still need to find a tool to decrypt, the third tool i posted giving me tag mismatch exception. – aero Sep 04 '20 at 21:22
  • for decryption use the same key and iv and Base64.getdecoder ().decode your cipheredText. – Michael Fehr Sep 05 '20 at 07:45
  • Related: [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – Mark Rotteveel Sep 06 '20 at 08:10

0 Answers0