Home > Software engineering >  Exception decrpyting with padded cypher
Exception decrpyting with padded cypher

Time:06-09

I have the following code:

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Scanner;

public class gtUF2 {

    public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException,
            UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey sKey = passwordGeneration("MiClave", 256);

        System.out.println(Base64.getEncoder().encodeToString(sKey.getEncoded()));

        String key = "7JUQgSTY3kFSYQC6/0L89rdYW36ArmK75Kdn3 cOvaE=";

        cipher.init(Cipher.DECRYPT_MODE, sKey);
        byte[] decrypted = cipher.doFinal(key.getBytes(StandardCharsets.UTF_8));
        System.out.println(Base64.getEncoder().encodeToString(decrypted));
    }

    public static SecretKey passwordGeneration(String text, int keySize) throws NoSuchAlgorithmException {
        byte[] data = text.getBytes(StandardCharsets.UTF_8);
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hash = md.digest(data);
        byte[] key = Arrays.copyOf(hash, keySize/8);
        return new SecretKeySpec(key, "AES");
    }
}

However, when I execute it throws the following exception:

Basically, what I want is to encrpyt in SHA256 the String MiClave and then use that as a SecretKey to decode key, that was encrpyted using AES.

CodePudding user response:

The following is simpler and produces readable output:

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

public class Decoder {
    public static void main(String[] args) {
        try {
            String cipherText = "7JUQgSTY3kFSYQC6/0L89rdYW36ArmK75Kdn3 cOvaE=";
            byte[] cipherBytes = Base64.getDecoder().decode(cipherText);
            MessageDigest sha256 = MessageDigest.getInstance("SHA256");
            byte[] key = sha256.digest("MiClave".getBytes());
            Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKey secretKey = new SecretKeySpec(key, "AES");
            c.init(Cipher.DECRYPT_MODE, secretKey);
            System.out.println(new String(c.doFinal(cipherBytes)));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
  •  Tags:  
  • java
  • Related