0

Decryption logic is missing something can you please assist. Output is not completely decrypted.

Java Encryption Logic:

public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {

    try {

        String in ="This is a text message";

        byte[] input = in.toString().getBytes("utf-8");
        String ENCRYPTION_KEY = "RW50ZXIgS2V5IEhlcmU=";
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] thedigest = md.digest(ENCRYPTION_KEY.getBytes("UTF-8"));
        // SecretKeySpec skc = new SecretKeySpec(thedigest, "AES/ECB/PKCS5Padding");
        SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skc);

        byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
        int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
        ctLength += cipher.doFinal(cipherText, ctLength);

        // String query = Base64.encodeToString(cipherText, Base64.DEFAULT);
        String query = new String(java.util.Base64.getEncoder().encode(cipherText));
        System.out.println("query " + query);
        // String query = new String(encode(cipherText), StandardCharsets.ISO_8859_1);
    } catch(UnsupportedEncodingException e) { // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Nodejs Decryption Logic:

let crypto = require('crypto');
var decipher = crypto.createDecipher('aes-256-ecb', "RW50ZXIgS2V5IEhlcmU=");
decipher.setAutoPadding(false);
console.log(decipher.update("EncyptedText", 'base64', 'utf8') + decipher.final('utf8'));
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
Sandra Pavan
  • 194
  • 1
  • 2
  • 8
  • Why did you choose to call `setAutoPadding(false)` coupled with `"AES/ECB/PKCS5Padding"`? What does "not completely decrypted" mean? (Note that this is an incredibly insecure approach to encryption. But that may be beyond the question you're asking.) – Rob Napier Sep 06 '19 at 17:25
  • Can you please suggest if the decryption logic is missing anything. – Sandra Pavan Sep 08 '19 at 00:48
  • 1. Create a SHA256-[`Hash`](https://nodejs.org/api/crypto.html#crypto_class_hash) of `RW50ZXIgS2V5IEhlcmU=` and use it as key. 2. Use [`createDecipheriv`](https://nodejs.org/api/crypto.html#crypto_crypto_createdecipheriv_algorithm_key_iv_options) instead of `createDecipher`, because the latter generates a key from the given password, but uses a different algorithm (and not SHA256). 3. In `createDecipheriv` set the IV equal to null, since ECB doesn't use an IV. 4. Don't disable padding (as already noted in the comment). Concerning the Java-Code: ECB is insecure. Better choices are CBC or GCM. – Topaco Sep 11 '19 at 15:45

0 Answers0