Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

DEs ECB Encryption

UmerMar 14 2012 — edited Mar 14 2012
Hi,

I am trying to encrypt a 16byte key with a 8byte transport key using DES in ECB mode with noPadding. I have searched on the net and found few examples. I am using one of the examles I found. Here, my 16byte key is in Hex format. Now problem is that I want that the ciphered key should also be in hex, but when i tried to output ciphered key is not giving any readable output.
Any guidence please how to get the ciphered key in hex format ?
Here is the sample code:
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Basic symmetric encryption example with padding and ECB using DES
 */
public class MainClass {
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());        
    byte[] input = "014B620635F04A24C0D4025E063E506B".getBytes();
    byte[] keyBytes = new byte[] { (byte)0x9A, (byte)0xE1, (byte)0x5E, (byte)0x9E,
                                   (byte)0x32, (byte) 0x4A, (byte) 0xB4, (byte) 0x2A };

    SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
    Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding", "BC");
    System.out.println("input : " + new String(input) +"| Length:"+input.length);

    // encryption pass
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);
    //String strCipherText = new BASE64Encoder().encode(cipherText);
    System.out.println("cipher: " + new String(cipherText, "UTF8")+ " bytes: " + ctLength);

    // decryption pass

    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
    int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
    ptLength += cipher.doFinal(plainText, ptLength);
    System.out.println("plain : " + new String(plainText) + " bytes: " + ptLength);
  }
}
Kind regards
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 11 2012
Added on Mar 14 2012
1 comment
919 views