0

I have a snippet of C# code for encryption :

 private static byte[] sharedkey = {0x01, 0x02, 0x03, 0x05, 0x03, 0x0B, 0x0D, 0x11, 0x12, 0x11, 0x0D, 0x0B, 0x07, 0x07, 0x04, 0x08,
0x01, 0x02, 0x03, 0x05, 0x07, 0x0B, 0x0D, 0x11};
private static byte[] sharedvector = {0x01, 0x07, 0x01, 0x05, 0x07, 0x0B, 0x0C, 0x11};



 public static String Encrypt(String val) {
    TripleDESCryptoServiceProvider tdes = newTripleDESCryptoServiceProvider(); 
    byte[] toEncrypt = Encoding.UTF8.GetBytes(val);
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, tdes.CreateEncryptor(sharedkey, sharedvector ), CryptoStreamMode.Write);
    cs.Write(toEncrypt, 0, toEncrypt.Length); cs.FlushFinalBlock();
    return Convert.ToBase64String(ms.ToArray());

 }

I tried to make a java version of this, but it does not work. this is my java version:

public String doTripleDESEncryption(String rawData) {

    byte[] cipher;
    int length;
    int inputLength = sharedvector.length;
    int iterations = inputLength / 8;
    if (inputLength % 8 != 0) {
        iterations++;
    }

    cipher = new byte[8 * iterations];

    for (int i = 0; i < iterations; i++) {
        DESedeEngine tdes = new DESedeEngine();
        tdes.init(true, new DESedeParameters(sharedkey));
        byte[] data = new byte[8];

        if (i == (iterations - 1)) {
            length = sharedvector.length - i * 8;
        } else {
            length = 8;
        }

        System.arraycopy(sharedvector, i * 8, data, 0, length);
        tdes.processBlock(data, 0, cipher, i * 8);
    }
    return new String(org.bouncycastle.util.encoders.Hex.encode(cipher));
}

But it does not work.I feel i am doing the conversion in the wrong way, as i am new to 3DES.

In the C# snippet, CryptoStream takes in the sharedKey and sharedVector to create CryptoStream, but in Java I can't seem to find the equivalent.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • "*it does not work*" - **how** does it not work? Please [edit] your question to give more details. – Wai Ha Lee Apr 17 '19 at 17:07
  • @WaiHaLee done, it does not work cause i am not even sure if i am converting it well, i am new to 3DES. I was hoping someone could look at my code and help me rewrite it or correct me in what i am doing wrong. – Oto-obong Eshiett Apr 17 '19 at 17:11
  • @WaiHaLee in the C# snippet, CryptoStream takes in the sharedKey and sharedVector to create CryptoStream, but in java i cant seem to find the equivalent. – Oto-obong Eshiett Apr 17 '19 at 17:13
  • 1
    Possible duplicate of [How do I use 3DES encryption/decryption in Java?](https://stackoverflow.com/questions/20227/how-do-i-use-3des-encryption-decryption-in-java) – Mark Benningfield Apr 17 '19 at 17:21

0 Answers0