[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

Question
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

8.2

AES Decryption in C#

Asked by raheelasadkhan in C# Programming Language, Miscellaneous Security, .NET

Tags: aes, c#, .net, java

I have the following data. Each line has been encrypted using AES encryption in Java. The objective is to decrypt the same in C#. The Java code that encrypts is listed below. The key file generated by the Java code is also attached here (Please rename extension to .DAT).

I am not sure but I think that the last four characters are not part of the encrypted data.

4A675E034589E7FEAA1A9D3695044B9D]en]
827D3D22560C07ECF952DDC754E2FA59]en]
BF6040BD3F918BB58E09E0F4904D59A2]en]
A0C7DA329023435BB21FADEED79056AB]en]
58D8CA901DDB662590FCD61EBC538100]en]
7D7076896765CDDF83FC6B1C16BB8912]en]
AA4EE36240E3863A6126995D18B2FADF]en]
9473448BE9B664894B5760D07DD1264F]en]
CD756F597FCD3584EB942A31D7014E1A]en]
1522C008CF31B421C1B078989F384389]en]

DF3AF67774360E267ED4E8DF5E367075]en]
4DB4D36B7F1729C907A391C3B9F8E274]en]
07007DFA89924CEA1A0D1BDC0C1E1A0D]en]
7AF269B0AE8BEFF4AA91DB36161D36D4]en]
7200804B1612E11BD97C3F878821B8BF]en]
F44EA7B2BC892F2A3BB0F21B03045C42]en]
AB584DC3CFB9AFFA3475FA0BD78EA06E]en]
6FDDDCE7EE39DC6F2CC0527A3F20299A]en]
FF5A6F59CA7A508395B6242A67885725]en]
816AF23A648B807EE993EBC3B8A0866D]en]

819857F1A4E800CF862C32CBA271758D]en]
9FFD6731346E3C7B0AD0ED26441D6F2C]en]
A66EFBFA93D1DE2EB55B3A7ECD1D971E]en]
1EF541C76DDCC778CBCB8D82F05AE53D]en]
555B44DFC01A14545E57411EA735E368]en]
566B2E70E5ED497486B6D4AA637CD372]en]
402845E886C16484A4C7B3B96CD66FBA]en]
E45B5F2BE592033733A1B6A5BCCC92AF]en]
CE3E764E4D2E0509C98047D02EB6B1AB]en]
913F2BFF90AA90B9A015BEA790AF64A0]en]
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
package Emfasis; 
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
import java.io.FileOutputStream;
import java.text.*; 
import javax.swing.JOptionPane; 
public class ModelEngine
{
    public static String reportName ="";
    public static ObjectOutputStream outKey;
    public static Key keyFromFile;
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyHHmmss");
    public  static char[] hexChar =
    {
        '0' , '1' , '2' , '3' ,
        '4' , '5' , '6' , '7' ,
        '8' , '9' , 'A' , 'B' ,
        'C' , 'D' , 'E' , 'F'
    }; 

    /**
    * Turns array of bytes into string
    *
    * @param buf	Array of bytes to convert to hex string
    * @return	Generated hex string
    */
    public static String asHex (byte buf[])
    {
        int i;
        StringBuffer strbuf = new StringBuffer(buf.length * 2); 
        for (i = 0; i < buf.length; i++)
        {
            if (((int) buf[i] & 0xff) < 0x10)
                strbuf.append("0"); 
            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
        } 
        return strbuf.toString();
    } 
    public String generateAndStoreKey(String dirPath)
    {
        //=================================================
        // Generate the secret key specs.
        long keyId = System.currentTimeMillis(); 
        try
        {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128); // 192 and 256 bits may not be available
            SecretKey skey = kgen.generateKey(); 
            //generate random three letter String
            double randomNumber;
            double randomNumberSetup;
            char randomCharacter;
            String str = ""; 
            for (int i = 0; i < 3; i++)
            {
                randomNumber = Math.random();
                randomNumberSetup = (randomNumber * 26 + 'a');
                randomCharacter = (char) randomNumberSetup;
                System.out.print(randomCharacter + ": ");
                str += randomCharacter;
            } 
            //System.out.println(" - Random string is(" + str + ")");
            String reportFile = dirPath+System.getProperty("file.separator")+"ENCKey" + dateFormat.format(new java.util.Date())+"-"+str.toUpperCase()+".DAT";
            // System.err.println(reportFile);
            outKey = new ObjectOutputStream(new FileOutputStream(reportFile));// create serialized output stream
            outKey.writeObject(skey);              								  // write key in a file
            this.reportName = reportFile;
            outKey.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null,"<<Operational Error! >> \n Failed to generate key file.","eMedXchange 1.0",JOptionPane.ERROR);
            return null;
        } 
        return reportName;
    } 
    public String getReprtFile()
    {
        return reportName;
    } 
    public String  saveRowToFile(String keyLocatn,String rowForSave,boolean encrypIndicator)
    {
        FileOutputStream encryptedOutPutFile = null;
        long keyId = System.currentTimeMillis();
        String userHomeDir = System.getProperty("user.home"); 
        try
        {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128); // 192 and 256 bits may not be available
            SecretKey skey = kgen.generateKey();
            String encryptedFile = userHomeDir + System.getProperty("file.separator") + "med" + keyId + ".dat";
            encryptedOutPutFile = new FileOutputStream(new File(encryptedFile));
            // encryptedOutPutFile
            try
            {
                ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(keyLocatn));  // open key file
                keyFromFile = (Key) keyIn.readObject();  // read key from file
                keyIn.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            } 
            byte[] raw = keyFromFile.getEncoded();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            // Instantiate the cipher 
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 
            //===============
            String[] values = rowForSave.split("\\|");
            //DO better presentation here///////////////////////
            //check for more methods of cypher
            for (String str : values)
            {
                if(encrypIndicator)
                {
                    byte[] encrypted = cipher.doFinal(str.getBytes());
                    encryptedOutPutFile.write(encrypted);//save bytes encrypted to file
                    // System.out.println("encrypted string: " + asHex(encrypted));
                    // System.out.println(str);
                }
                else
                {
                    encryptedOutPutFile.write(str.getBytes());//save bytes unencrypted to file
                }
            } 
            //====================
            encryptedOutPutFile.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return "FALURE";
        } 
        return "SUCCESS";
    } 
    public String saveHeadingsToFile(String keyLocatn,String headingForSave,boolean encrypIndicator)
    {
        String[] values = headingForSave.split("\\|"); 
        for (String str : values)
        {
            System.out.println(str);
        } 
        return null;
    } 
    public String encryptAndSaveFile(Key key,String fileLocation)
    {
        //Read the lines into a StringBuffer,convert to String and encrypts
        String userHomeDir = System.getProperty("user.home");
        byte[] aesKey; 
        String result= null;
        try
        {
            Cipher cipher = Cipher.getInstance("AES");
            aesKey = key.getEncoded();
            SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec); 
            FileInputStream fis = new FileInputStream(new File(fileLocation));
            CipherInputStream cis = new CipherInputStream(fis, cipher); 
            FileOutputStream fos = new FileOutputStream(new File(userHomeDir + System.getProperty("file.separator") + "md_e.txt"));
            byte[] b = new byte[8];
            int i;
            while ((i = cis.read(b)) != -1)
            {
                fos.write(b, 0, i);
            }
            fos.flush();
            fos.close();
            result = "SUCCESS";
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null,"<<Operational Error!.Failed to encrypt file>>\nPlease check the input files.","MedRecord Track",JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
            result = "FAILURE";
        } 
        return result;
    } 
    public String decryptAndSaveFile(Key key,String fileLocation)
    {
        //Read the lines into a StringBuffer,convert to String and decrypts//another option
        String userHomeDir = System.getProperty("user.home");
        byte[] aesKey;
        String result= null;
        try
        {
            // Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            Cipher cipher = Cipher.getInstance("AES");
            aesKey = key.getEncoded();
            SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec); 
            FileInputStream fis = new FileInputStream(new File(fileLocation));
            CipherInputStream cis = new CipherInputStream(fis, cipher);
            FileOutputStream fos = new FileOutputStream(new File(userHomeDir+System.getProperty("file.separator")+"MedicalData_Ana_Decrypted.txt")); 
            byte[] b = new byte[8];
            int i; 
            while ((i = cis.read(b)) != -1)
            {
                fos.write(b, 0, i);
            }
            fos.flush();
            fos.close();
            cis.close();
            fis.close();
            result= "SUCCESS";
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null,"<<Operational Error! \nFailed to decrypt file>>\nPlease check the input files.","MedRecord Track",JOptionPane.ERROR);
            e.printStackTrace();
            result= "FAILURE";
        } 
        return result;
    } 
    public static byte[] toBinArray (String hexStr)
    {
        byte bArray[] = new byte[hexStr.length()/2]; 
        for(int i=0; i<(hexStr.length()/2); i++)
        {
            byte firstNibble  = Byte.parseByte(hexStr.substring(2*i,2*i+1),16); // [x,y)
            byte secondNibble = Byte.parseByte(hexStr.substring(2*i+1,2*i+2),16);
            int finalByte = (secondNibble) | (firstNibble << 4 ); // bit-operations only with numbers, not bytes.
            bArray[i] = (byte) finalByte;
        } 
        return bArray;
    } 
    public static String toHexString( byte[] b )
    {
        StringBuffer sb = new StringBuffer( b.length * 2 ); 
        for ( int i=0; i<b.length; i++ )
        {
            // look up high nibble char
            sb.append( hexChar [( b[i] & 0xf0 ) >>> 4] ); // fill left with zero bits
            // look up low nibble char
            sb.append( hexChar [b[i] & 0x0f] );
        } 
        return sb.toString();
    } 
    public String encryptStringPart(Key key,String strPart)
    {
        byte[] encrypted = null ;
        try
        {
            byte[] aesKey = key.getEncoded();
            SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES"); 
            // Instantiate the cipher
            //   Cipher cipher = Cipher.getInstance("AES");
            //Try explicitly stating a mode and padding
            //look up what modes and padding is available. 
            // Cipher cipher  = Cipher.getInstance("AES/ECB/PKCS5Padding");//my new
            Cipher cipher  = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 
            encrypted = cipher.doFinal(strPart.getBytes());
            // System.out.println("encrypted string: " + asHex(encrypted));
        }
        catch(Exception e )
        {
            e.printStackTrace();
        }
        ///New Test
        //Convert the encrpted byte[] to String
        String stringFromEncr = toHexString(encrypted);////will need
        // System.out.println("\n stringFromEncr: " + stringFromEncr);//I will need this 
        return stringFromEncr;
    } 
    public String decryptStringPart(Key key,String strPart)
    {
        byte[] decrypted = null ;
        String decreString = null; 
        try
        {
            byte[] aesKey = key.getEncoded();
            SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES"); 
            // Cipher cipher  = Cipher.getInstance("AES/ECB/PKCS5Padding");
            Cipher cipher  = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec); 
            String hexString = strPart.substring(0, strPart.length()-4);//Begining of "]en]" marker
            byte[] decodedBinary = toBinArray(hexString);
            //Then Hex
            decrypted = cipher.doFinal(decodedBinary);
            decreString = new String(decrypted);
            // System.out.println("XXXXXX decrypted string:XXXXXX " + decreString);
        }
        catch(Exception e )
        {
            e.printStackTrace();
        } 
        return decreString;
    } 
}
Attachments:
 
Please rename the extension to .DAT
 
 
Loading Advertisement...
 
[+][-]11/08/09 04:16 AM, ID: 25770248Accepted Solution

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

About this solution

Zones: C# Programming Language, Miscellaneous Security, .NET
Tags: aes, c#, .net, java
Sign Up Now!
Solution Provided By: raheelasadkhan
Participating Experts: 1
Solution Grade: A
 
[+][-]11/04/09 05:23 AM, ID: 25739001Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]11/04/09 05:57 AM, ID: 25739308Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
 
Loading Advertisement...
20091118-EE-VQP-93 - Hierarchy / EE_QW_3_20080625