-2

I have the following CryptoJS code for encryption and decryption.

Encryption Code

<script type="text/javascript">
    $(document).on("click", "#crack", function(evt) {
        evt.preventDefault();
        var e = $("#plaintext").val();
        var key = $("#key").val();
        var iv = CryptoJS.enc.Utf8.parse(key);
        var r, t = CryptoJS.enc.Utf8.parse(key), // key
            n = CryptoJS.DES.encrypt(CryptoJS.enc.Utf8.parse(e), t,{
                iv:iv,
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            });
            r = n.toString(CryptoJS.enc.Utf8);
        $(".result").text(n);
    });
    </script>

Decryption Code

<script type="text/javascript">
    $(document).on("click", "#crack", function(evt) {
        evt.preventDefault();
        var e = $("#ciphertext").val();

        var key = $("#key").val();
        var r, t = CryptoJS.enc.Utf8.parse(key), // key
            n = CryptoJS.DES.decrypt({
                ciphertext: CryptoJS.enc.Base64.parse(e.replace('"', ""))
            }, t, {
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            }),
            r = n.toString(CryptoJS.enc.Utf8);
        $(".result").text(r);
    });
    </script>

I want to recreate the same logic in Java but it's not quite working our well. I followed most of the existing questions which are already asked here on StackOverflow but it didn't help out.

I found another article and sample code which seemed like it would work but it didn't.

Article Link: https://androidfreetutorial.wordpress.com/2017/03/14/android-encryptiondecryption-with-tripledes-3des-algorithm/

I get the following error message:

java.security.NoSuchAlgorithmException: Cannot find any provider supporting DESede/ECB/PKCS7Padding

What am I doing wrong and how is CryptoJS code here is different from the Java one?

Sample Inputs:

Key:

CipherText: 3OwGE1y7zFLyPT49uGMvFQ==

Key: 75a1b1ae20af8de7bdfb6fac8ca9d36c0ab91930


EDIT: Added Working Code. Also the CryptoJS is Simple DES and not Triple DES as Suggested by @James. the application I was testing used tripledes.js in the resource file which mislead me to believe maybe Triple DES is used. I crossed checked that in CryptoJS if you want to use TripleDES you have to use something like CryptoJS.TripleDES.encrypt(...). Also, I forgot that DES Key size is 8 Bytes and the key that I gave wasn't being handled properly causing the bad padding exception, which I workedaround using Arrays.copyOf, and lastly Thanks to P.Soutzikevich.

The following code works exactly how I want it to be.

private final int DES_KEY_SIZE = 8;
private final String DES_MODE = "DES/ECB/PKCS5Padding";

Encryption

byte[] keyBytes = Arrays.copyOf(secretKey.getBytes(), DES_KEY_SIZE);
byte[] plainTextBytes = plainText.getBytes();
desKeySpec = new SecretKeySpec(keyBytes, "DES");
desCipher = Cipher.getInstance(DES_MODE);
desCipher.init(Cipher.ENCRYPT_MODE, desKeySpec);
byte[] encryptedText = desCipher.doFinal(plainTextBytes);
data = Base64.getEncoder().encodeToString(encryptedText);

Decryption:

byte[] keyBytes = Arrays.copyOf(secretKey.getBytes(), DES_KEY_SIZE);
byte[] encryptedTextBytes = Base64.getDecoder().decode(cipherText);
desKeySpec = new SecretKeySpec(keyBytes, "DES");
desCipher = Cipher.getInstance(DES_MODE);
desCipher.init(Cipher.DECRYPT_MODE, desKeySpec);
data = new String(desCipher.doFinal(encryptedTextBytes));
Ritz
  • 180
  • 1
  • 12
  • Have a look into the following links. https://stackoverflow.com/questions/20227/how-do-i-use-3des-encryption-decryption-in-java/13612902 – Sambit May 12 '19 at 07:53
  • https://stackoverflow.com/questions/11930805/tripledes-encryption-error-in-java – Sambit May 12 '19 at 07:53
  • Oracle has a tutorial for almost anything: [Cryptography Reference Guide](https://docs.oracle.com/javase/8/docs/technotes/guides/security/crypto/CryptoSpec.html). Don't skip these. Also, posting JavaScript code for a question actually about Java, is not something you should ever do. Additionally, dumping code and saying *"This is what I want to do"*, is simply disrespectful to others trying to help you. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Soutzikevich May 12 '19 at 07:58
  • @P.Soutzikevich I don't understand whats wrong with me asking this. I don't think it is disrespectful in anyway. Like I said I have searched for similar posts on stackoverflow. I suggest you search once's and you will see that similar posts are there already. I am not the first one to do so. People generally recommend that you provide relevant facts/code to clarify the point clearly. Hence I did the same I posted the Javascript code whose equivalent java code is what I am trying to make. As simple as that. – Ritz May 12 '19 at 08:11
  • You need to show your Java code if you want us to help you with `java.security.NoSuchAlgorithmException`. – sanyassh May 12 '19 at 08:31
  • @Ritz No you didn't use relevant **"facts/code"** to clarify any point. What I'm saying is that, I find it disrespectful when someone finds a snippet of code, copy-pastes it into a question and asks: *"How can I do this in **** language?*. I did attach the links for you to read in my first comment, that pointed out what you need to do (post your code with what you've tried, but you completely ignored it. If that's not disrespectful, I don't know what is. You didn't even take the time to write (in English, not in code) what it is you are trying to do. – Soutzikevich May 12 '19 at 09:06
  • @P.Soutzikevich Again, Read my OP properly. I have clearly mentioned "I want to recreate the same logic in Java" and before that I gave you both the CryptoJS code which I have worked on after going through various examples from multiple sites. But when I try to recreate it in Java it's not quite working. Also I did mention that I have gone through most articles relevant to my post from StackOverflow already but they didn't quite suffice well hence I asked it clearly and made my motives clear. If I were really disrespectful I would have randomly copy pasted code without any credits. – Ritz May 12 '19 at 09:19
  • @Ritz I gave you the solution you were looking for, even though there was little effort to create a [MCVE](https://stackoverflow.com/help/mcve). If it solved your problem, then please consider accepting it as the answer and upvoting. – Soutzikevich May 12 '19 at 09:29
  • @P.Soutzikevich I have replied as well. Kindly try the example code provided with the sample inputs given. As of now, it doesn't work. And I am also searching for the answer of my own. I thinking of giving BouncyCastle a try. I went through their documentation and it seems they implement the provider necessary for the code. – Ritz May 12 '19 at 09:34
  • 1
    Your javascript code is using single DES, but your Java code is using Triple DES. – President James K. Polk May 12 '19 at 12:43
  • 2
    @Ritz While there is no obligation for you to accept any answer, you would only be proving me correct by not doing so. So thanks for helping me prove my point in the previous comments. – Soutzikevich May 12 '19 at 12:48
  • 1
    Please do not deface your own questions. Simply edit them to add information/corrections, or delete them. – President James K. Polk May 12 '19 at 16:04

1 Answers1

1

The transformation you have used appears to be invalid for Triple-DES.

Change the padding of this string:

public static String ALGO = "DESede/ECB/PKCS7Padding";

into PKCS5Padding:

public static String ALGO = "DESede/ECB/PKCS5Padding";

The compiler error message you received was pretty clear; No Such Algorithm exception. Compilers usually suffer from poor error description messages, but in this case it points you directly to the source of the error. By doing a little good old web-searching, you would've realised that Triple DES takes PKCS5Padding or no padding at all.

Where did I get this information? From the documentation of course.

See this screenshot: enter image description here

The documentation about a java Cipher object can be found here. You can see that one of the parameters for calling Cipher.init(int opmode, Key key), is obviously of type Key.

By clicking on the relevant link to read about the Key interface, you will notice that one of the implementing Classes (of this interface), is SecretKeySpec. The documentation for SecretKeySpec can be found here.

From the first paragraph of SecretKeySpec:

This class is only useful for raw secret keys that can be represented as a byte array and have no key parameters associated with them, e.g., DES or Triple DES keys.

Soutzikevich
  • 991
  • 3
  • 13
  • 29
  • I should have mentioned this already but I have already tried PKCS5Padding and NoPadding and it doesn't work. I get the following error message, `javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.` I would have mentioned this when you first posted the same answer without screenshot and then deleted it. – Ritz May 12 '19 at 09:31
  • 3
    @Ritz Your question was for a `java.security.NoSuchAlgorithmException` and was caused by an invalid Transformation string you entered, in the form of *"algorithm/mode/padding"*, for the initialization of a Cipher. This information can be found in the documentation [here](https://docs.oracle.com/javase/8/docs/api/javax/crypto/Cipher.html). The **new** issue you have, as you mention in the above comment, is caused by using a **bad** (invalid or wrongly instantiated) key. For triple-DES, you should use [SecretKeySpec](https://docs.oracle.com/javase/8/docs/api/javax/crypto/spec/SecretKeySpec.html) – Soutzikevich May 12 '19 at 12:33
  • I have used SecretKeySpec only. Let me go through this entirely once more. I am messing it up somewhere. – Ritz May 12 '19 at 15:18
  • 2
    Even if he uses the correct key, the Javascript code is using DES and the Java code is using Triple-DES, different algorithms. – President James K. Polk May 12 '19 at 16:03
  • @JamesKPolk Yes, I saw that when you first pointed it out. I just ignored the wrong JS code, because he copy/pasted it from somewhere on the web. He was bored to write a proper question. Good eye btw ;) – Soutzikevich May 12 '19 at 16:24
  • @P. Soutzikevich Added working code and updated post. – Ritz May 13 '19 at 04:29