CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1
  1. #1
    Join Date
    Nov 2002
    Location
    Brazil
    Posts
    181

    Trouble encrypting correctly with AES with a static key

    Hi. I'm trying to get JCE to work with the following example using AES in ECB mode (yes, ECB shouldn't be used, but it's what I'm supposed to use): given a clear text String represented by the bytes (in hex) 546578746F2070617261207465737465 and a key 6573736173656E686165686672616361, the program is supposed to provide the encrypted bytes A506A19333F306AC2C62CBE931963AE7. I used an online encryption service to check for myself if the above is true, and it is. However, I just can't get it to work right in Java:

    Code:
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;
    
    public class AESTest {
        public static String asHex(byte buf[]) {
            StringBuffer strbuf = new StringBuffer(buf.length * 2);
    	int i;
    
    	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 static void main(String[] args) throws Exception {
            String keyString = "Texto para teste";
    	// 546578746F2070617261207465737465 (Hex)
    	byte[] key = keyString.getBytes("UTF-8");
    	System.out.println(asHex(key).toUpperCase());
    
    	String clearText = "essasenhaehfraca";
    	// ZXNzYXNlbmhhZWhmcmFjYQ== (Base64)
    	// 6573736173656E686165686672616361 (Hex)
    	byte[] clear = clearText.getBytes("UTF-8");
    	System.out.println(asHex(clear).toUpperCase());
    
    	SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    	// PKCS5Padding or NoPadding
    	Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
    	cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    
    	byte[] encrypted = cipher.doFinal(clear);
    	System.out.println(asHex(encrypted).toUpperCase());
        }
    }
    All examples I found generate a key instead of using a static one. Well, I need to use that specific key.

    What am I doing wrong? Thank you very much!
    Last edited by Magus; June 7th, 2007 at 01:40 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured