473,770 Members | 2,133 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can't decrypt my AES-128 C#-encrypted byte array in java

42 New Member
I'm trying to decrypt a byte array in java that was encrypted in C#. I don't get any error messages, just a result that's completely not what I was hoping for.

I think I am using the same type of algorithm, initialization vector (IV), mode, padding, key etc, but I just don't get the two languages to "understand each other", or, in other words, I must be missing out on something crucial.

I encrypt a byte array in C# and send over the byte initialization vector used for encrypting it as well as the encrypted byte to java. In java I use the received initialization vector to try to decrypt the received encrypted byte array. And I don't get anything near the original plaintext.

I leave out the communication code between the two applications since I don't think that's where the problem is. Though I'm not sure, of course, but let's try this first. (Why I don't think that's the problem? I print out the arrays in my C# code as well as in my java code, once they're received in the java code, and they look exactly the same.)

Here's the encryption code I use so you get the idea of the encryption methods I'm using. I'm trying to achieve AES-128, CBC, no padding in both applications.

NOTE: Of course, in my application I use the IV received from C#, not "tmpiv" as in this example. Also, I use the received encrypted plaintext-buffer from C#... yeah, you get the point. I just wanted to post runnable code..

Any ideas or hints to lead me in the right direction would be extremely appreciated! Cheers!
Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. import javax.crypto.Cipher;
  3. import javax.crypto.NoSuchPaddingException;
  4. import javax.crypto.spec.IvParameterSpec;
  5. import javax.crypto.spec.SecretKeySpec;
  6.  
  7.  
  8. public class Main {
  9.  
  10.     public Main() {
  11.     }
  12.  
  13.     public static void main(String[] args) {
  14.         byte[] keyBytes = ("abcdefghijklmnop").getBytes();
  15.          byte[] plaintext = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
  16.                               (byte)0x88, (byte)0x99, (byte)0xaa, (byte)0xbb,
  17.                               (byte)0xcc, (byte)0xdd, (byte)0xee, (byte)0xff };
  18.  
  19.          byte[] tmpIV = {0x43, (byte)0x6d, 0x22, (byte)0x9a, 0x22,
  20.                         (byte)0xf8, (byte)0xcf, (byte)0xfe, 0x15, 0x21,
  21.                         (byte)0x0b, 0x38, 0x01, (byte)0xa7, (byte)0xfc, 0x0e};
  22.  
  23.          System.out.println("Plaintext is:");
  24.          displayBytes(plaintext);
  25.  
  26.          byte[] encrypted = encrypt(plaintext,keyBytes,tmpIV);
  27.          System.out.println("Encrypted plaintext is:");
  28.          displayBytes(encrypted);
  29.  
  30.          byte[] decrypted = decrypt(encrypted,keyBytes,tmpIV);
  31.          System.out.println("Decrypting encrypted plaintext, we get plaintext back:");
  32.          displayBytes(decrypted);
  33.  
  34.  
  35.     }
  36.  
  37.      public static byte[] decrypt(byte[] cipherText, byte[] key, byte [] iv)
  38.     {
  39.       try{    
  40.       Cipher c = Cipher.getInstance("AES/CBC/NoPadding");
  41.       SecretKeySpec sks = new SecretKeySpec(key, "AES");
  42.       IvParameterSpec ips = new IvParameterSpec(iv);
  43.       c.init(Cipher.DECRYPT_MODE, sks, ips);   
  44.       //Re-use of "cipherText"
  45.       cipherText = c.doFinal(cipherText);
  46.       }
  47.       catch(Exception e){ System.out.println("Exception caught:"+e.getMessage());}
  48.       return cipherText;
  49.    }
  50.  
  51.      public static byte[] encrypt(byte[] plainText, byte[] key, byte [] iv)
  52.     {
  53.      try{    
  54.       Cipher c = Cipher.getInstance("AES/CBC/NoPadding");
  55.       SecretKeySpec sks = new SecretKeySpec(key, "AES");
  56.       IvParameterSpec ips = new IvParameterSpec(iv);
  57.       c.init(Cipher.ENCRYPT_MODE, sks, ips);
  58.       //Re-use of "plainText"
  59.       plainText = c.doFinal(plainText);
  60.       }
  61.       catch(Exception e){System.out.println("Exception caught:"+e.getMessage());}
  62.       return plainText;      
  63.    }
  64.  
  65.  
  66.      public static void displayBytes(byte[] bytes) {
  67.         StringBuffer ret = new StringBuffer(bytes.length);
  68.         for (int i = 0; i < bytes.length; i++) {
  69.             String hex = Integer.toHexString(0x0100 + (bytes[i] & 0x00FF)).substring(1);
  70.             ret.append((hex.length() < 2 ? "0" : " ") + hex);
  71.         }
  72.         System.out.println (ret.toString());
  73.     }
  74. }


Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Security.Cryptography;
  5. using System.IO;
  6.  
  7. namespace forumapp
  8. {
  9.     class Program
  10.     {
  11.         static RijndaelManaged rijndaelCipher;
  12.  
  13.         static void Main(string[] args)
  14.         {
  15.           byte[] plaintext = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
  16.           Console.WriteLine ("\nPlaintext is: ");
  17.           DisplayBytes(plaintext);
  18.  
  19.           initCrypt();
  20.  
  21.           byte[] ciphered = Encrypt(plaintext);
  22.           Console.WriteLine("\nEncrypted plaintext is: ");
  23.           DisplayBytes(ciphered);
  24.  
  25.           byte[] deciphered = Decrypt(ciphered);
  26.           Console.WriteLine("\nDecrypting encrypted plaintext, we get plaintext back: ");
  27.           DisplayBytes(deciphered);
  28.  
  29.           Console.WriteLine("\nDone");
  30.           Console.ReadLine();
  31.  
  32.         }
  33.  
  34.         public static void initCrypt()
  35.         {
  36.             byte[] keyBytes = System.Text.UTF8Encoding.UTF8.GetBytes ("abcdefghijklmnop");
  37.  
  38.             rijndaelCipher = new RijndaelManaged();
  39.             PasswordDeriveBytes pdb = new PasswordDeriveBytes(keyBytes, new SHA1CryptoServiceProvider().ComputeHash(keyBytes));
  40.             byte[] key = pdb.GetBytes(32);
  41.             byte[] iv = pdb.GetBytes(16);
  42.             rijndaelCipher.Mode = CipherMode.CBC;
  43.             rijndaelCipher.Padding = PaddingMode.None;
  44.             rijndaelCipher.KeySize = 128;
  45.             rijndaelCipher.BlockSize = 128;
  46.             rijndaelCipher.Key = key;
  47.             rijndaelCipher.IV = iv;
  48.         }
  49.  
  50.         public static byte[] Encrypt(byte[] plainBytes)
  51.         {
  52.             ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
  53.             using (MemoryStream ms = new MemoryStream(plainBytes))
  54.             {
  55.                 using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Read))
  56.                 {
  57.                     return ReadFully(cs);
  58.                 }
  59.             }
  60.         }
  61.  
  62.         public static byte[] Decrypt(byte[] encryptedData)
  63.         {
  64.             ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
  65.             using (MemoryStream ms = new MemoryStream(encryptedData))
  66.             {
  67.                 using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Read))
  68.                 {
  69.                     return ReadFully(cs);
  70.                 }
  71.             }
  72.         }
  73.  
  74.         public static byte[] ReadFully(Stream stream)
  75.         {
  76.             byte[] buffer = new byte[32768];
  77.             using (MemoryStream ms = new MemoryStream())
  78.             {
  79.                 while (true)
  80.                 {
  81.                     int read = stream.Read(buffer, 0, buffer.Length);
  82.                     if (read <= 0)
  83.                         return ms.ToArray();
  84.                     ms.Write(buffer, 0, read);
  85.                 }
  86.             }
  87.         }
  88.  
  89.         static void DisplayBytes(byte[] bytes)
  90.         {
  91.             for (int i = 0; i < bytes.Length; ++i)
  92.             {
  93.                 Console.Write(bytes[i].ToString("x2") + " ");
  94.                 if (i > 0 && i % 16 == 0) Console.Write("\n");
  95.             }
  96.             Console.WriteLine("");
  97.         }
  98.  
  99.     }
  100. }
  101.  
Aug 29 '07 #1
2 17968
MimiMi
42 New Member
My mistake. (Sorry for being such a 'moron'...)
The key is not the same!!
Of course I shouldn't use rijndaelCipher. Key = key, where key = pdb.GetBytes(32 )
(PasswordDerive Bytes).
It should be "rijndaelCipher .Key = keyBytes.
Then it works like a charm!
"I'm so happy, oh so happy..." cheers
Aug 30 '07 #2
JosAH
11,448 Recognized Expert MVP
My mistake. (Sorry for being such a 'moron'...)
The key is not the same!!
Of course I shouldn't use rijndaelCipher. Key = key, where key = pdb.GetBytes(32 )
(PasswordDerive Bytes).
It should be "rijndaelCipher .Key = keyBytes.
Then it works like a charm!
"I'm so happy, oh so happy..." cheers
Good you found it yourself; I've been playing with your code a bit and I was
completely on the wrong track and about to check the Sun Bugbase for this
encryption method ;-)

kind regards,

Jos
Aug 30 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

2
26915
by: David Cook | last post by:
Java's InetAddress class has some methods that use a byte-array to hold what it describes as a 'raw IP address'. So, I assume that they mean an array like: byte ba = new byte; would hold an IPv4 address. Ok, yes, in theory, there are enough bits to hold the values. But, my Java book clearly states that a byte is a SIGNED quantity, is part of the Integer class, and can hold values ranging from 127
0
2349
by: EdInPhoenix | last post by:
I'm not sure where to post this, so I thought I'd start here. I need to get a .NET web service to play nice with a Java consumer. The web service passes back a byte array with an encrypted string. The java app needs to decrypt the bytes. The problem I think is that .net bytes can be 0-255, but Java bytes are -127-128. How can we get java to accept the bytes without mangling them? Thanks,
1
1952
by: Brian Mitchell | last post by:
I'm sorry if this is the wrong group but I couldn't find one relating to cryptography. I have a byte array that I am encrypting using the System.Cryptography classes and it encrypts just fine. However when I decrypt the array the decryptor removes all the white spaces from the array (byte values of 255). I've tried setting the padding to none but it doesn't work. As long as the array doesn't have any white spaces in there it encrypts...
0
5793
by: lovecarole | last post by:
hi, i am the student who should write a program about reading wav file and do the DFT. actually i don't know how to read data of the wav song and save it into the array... if i want to read 17640 every times., and i set byte read=new byte, i have the wav format paper, but i don't know how to read the data correctly into the byte array, and used for doing DFT.... here's my code, and i am little hurry...thanks for the helps first~
1
2395
by: radhikaullas | last post by:
Hello all In my application to store the encrypted password in sql server. i know the code for encrypt & decrypt. but the problem is the encrypt will return byte array. i dont know how to store & retrieve byte array in sql server using java code
1
4836
by: MimiMi | last post by:
I'm trying to decrypt a byte array in java that was encrypted in C#. I don't get any error messages, just a result that's completely not what I was hoping for. I think I am using the same type of algorithm, initialization vector (IV), mode, padding, key etc, but I just don't get the two languages to "understand each other", or, in other words, I must be missing out on something crucial. I encrypt a byte array in C# and send over the byte...
0
2901
by: eitanyan | last post by:
I am trying to create a Java to .Net interop and the way I am doing it is by creating a C# com object and a native unmanaged c++ dll that uses JNIEnv of java. the java is loading the native c++ dll and invokes a method in it which invokes a method on The command passed from java to .Net is a byte array and the response passed back is also a byte array the C# managed COM object which finally invokes a method on a regular C# managed dll....
10
6382
by: Scott Townsend | last post by:
So I need to talk to a devices that expects all of the bits and bytes I sent it to be in specific places (not yet 100% defined). I wanted to create a structure/class with all of the data in it and then convert that to a byte array, pass it to the device, then get a reply and then convert that to a structure. I'm having issues with making sure what I've coded is correct. Cant figure out how to define an array in structure that is a...
1
13410
by: phpuser123 | last post by:
I want to convert my object to byte array and then next to an object and run a method..The codes are below: public class test_serialisation implements Serializable{ /** * */ private static final long serialVersionUID = 1L;
0
9618
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9906
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8933
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6712
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.