Search code examples
javac#encryptiondes

C# DES vs Java DES Byte[] and BlockSize differs


I am struggling to get the Java code to output the same Byte[] as the C# code.

C# Code:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public class Program
{
    private const string k = "A2B3C4D1";
    private const string kiv = "1A2B3C4D";
    
    public static void Main()
    {
        encrypt("peanuts");
    }
    
    public static void encrypt(string str)
    {
        try
        {
            using (var ms = new MemoryStream())
            using (var csp = new DESCryptoServiceProvider() { Key = Encoding.UTF8.GetBytes(k), IV =  Encoding.UTF8.GetBytes(kiv) })
            {
                Console.WriteLine("Algorithm: DES?/" + csp.Mode + "/" + csp.Padding);
                Console.WriteLine("BlockSize: " + csp.BlockSize);

                using (var cs = new CryptoStream(ms, csp.CreateEncryptor(), CryptoStreamMode.Write))
                using (var sw = new StreamWriter(cs))
                    sw.WriteLine(str);

                byte[] barray = ms.ToArray();

                Console.WriteLine("barray length: " + barray.Length);
            
                Console.WriteLine("barray: " + string.Join(" ", barray));
            }
        }
        catch (Exception ex) { Console.Write(ex.ToString()); }
    }
}

Java Code:

import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class MyClass {
    private static final String k = "A2B3C4D1";
    private static final String kiv = "1A2B3C4D";
    
    public static void main(String args[]) {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        encrypt("peanuts");
    }
    
    public static void encrypt(String str) {
        try {
            SecretKeySpec key = new SecretKeySpec(k.getBytes(Charset.forName("UTF-8")), "DES");
            IvParameterSpec iv = new IvParameterSpec(kiv.getBytes(Charset.forName("UTF-8")));
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, iv);
            
            System.out.println("Algorithm: " + cipher.getAlgorithm());
            System.out.println("BlockSize: " + cipher.getBlockSize());
    
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            CipherOutputStream cos = new CipherOutputStream(out, cipher);
            
            cos.write(str.getBytes());
            cos.close();
            
            byte[] barray = out.toByteArray();
            
            System.out.println("barray length: " + barray.length);
        
            System.out.print("barray: ");
            for(byte b : barray){
                System.out.print(" " + b);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

C# Output

Algorithm: DES?/CBC/PKCS7

BlockSize: 64

barray length: 16

barray: 107 125 91 205 77 206 98 120 214 194 64 167 128 97 132 75

base64: a31bzU3OYnjWwkCngGGESw==

Java Output

Algorithm: DES/CBC/PKCS7Padding

BlockSize: 8

barray length: 8

barray: 45 100 -86 103 9 -7 -19 -76

base64: LWSqZwn57bQ=

I am trying to get exactly the same Byte[] output from the Java code as I'm already getting from the C#. But the only difference I manage to see is the block size differs from both.

C# Dot.Net Fiddle

Java jDoodle.com

I just don't get it, is there something which I am missing or don't understand?

EDIT

I have added code to print out the byte array in string, it differs:

C#

barray length: 16
barray: 107 125 91 205 77 206 98 120 214 194 64 167 128 97 132 75
base64: a31bzU3OYnjWwkCngGGESw==

Java

barray length: 8
barray: 45 100 -86 103 9 -7 -19 -76
base64: LWSqZwn57bQ=

Solution

  • @JamesKPolk is correct: You're encrypting { (byte)'p', (byte)'e', (byte)'a', (byte)'n', (byte)'u', (byte)'t', (byte)'s', (byte)'\r', (byte)'\n' } in C#, and { (byte)'p', (byte)'e', (byte)'a', (byte)'n', (byte)'u', (byte)'t', (byte)'s' } in Java.

    Since "peanuts" is (in UTF-8) 7 bytes, it can be PKCS7 padded into one DES block. The next 1-8 bytes results in a second block... and you added two.

    Changing the code in the Dot.Net Fiddle to Write instead of WriteLine produces

    Algorithm: DES?/CBC/PKCS7
    BlockSize: 64
    barray length: 8
    barray: 45 100 170 103 9 249 237 180
    barray: LWSqZwn57bQ=
    

    where now the only difference is that C# BlockSize is bits, and your Java code has it as bytes.

    Change "peanuts" to "peanuts\r\n" in your JDoodle and you get

    Algorithm: DES/CBC/PKCS7Padding
    BlockSize: 8
    barray length: 16
    barray:  107 125 91 -51 77 -50 98 120 -42 -62 64 -89 -128 97 -124 75
    barray: a31bzU3OYnjWwkCngGGESw==
    

    Which is the same, if the barray decimal contents had been printed as unsigned values instead of signed values (add 256 to all the negative numbers) -- a fact easily visible in the Base64 being the same.