DESede-ECB Encryption-Decryption

1k Views Asked by At

I'm trying to Encrypt and decrypt a string in java using the following code:

public byte[] encrypt(String message) throws Exception {
    final MessageDigest md = MessageDigest.getInstance("md5");
    final byte[] digestOfPassword = md.digest("MYKEY12345"
            .getBytes("utf-8"));
    final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
    for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];
    }

    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
//        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    final byte[] plainTextBytes = message.getBytes("utf-8");
    final byte[] cipherText = cipher.doFinal(plainTextBytes);
    // final String encodedCipherText = new sun.misc.BASE64Encoder()
    // .encode(cipherText);



    Log.d("base64", Base64.getEncoder().encodeToString(cipherText));

    return cipherText;
}


public String decrypt(byte[] message) throws Exception {
    final MessageDigest md = MessageDigest.getInstance("md5");
    final byte[] digestOfPassword = md.digest("MYKEY12345"
            .getBytes("utf-8"));
    final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
    for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];
    }

    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
//    final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    final Cipher decipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
    decipher.init(Cipher.DECRYPT_MODE, key);

    // final byte[] encData = new
    // sun.misc.BASE64Decoder().decodeBuffer(message);
    final byte[] plainText = decipher.doFinal(message);

    return new String(plainText, "UTF-8");
}

usage:

byte[] codedtext = new Common().encrypt("HELLOWORLD!"); // Function to get the Encrption

Output:

 base64: Ya9zBTukyOmdOh5/5vCaGA== // encrypted string converted to base64
 Encrypted : [B@d41c149 

ToDecrypt:

 String decodedtext = new Common().decrypt(codedtext); // To decrypt String

Output:

Decrypted : HELLOWORLD!  // from Encrypted string

Now if i use the same Key and String to get the encryption key online i get different values.

Using this link to verify my encryption/decryption.

I'm just starting in encryption/decryption so any help is appreciated about any thing that i'm doing wrong here.

1

There are 1 best solutions below

2
g00se On

You need

final byte[] plainText = decipher.doFinal(Base64.getDecoder().decode(message));