简体   繁体   中英

Datapower encrypted text Decrypted value of CBC algorithm consists of input and unwanted characters in java

Am trying to Decrypt an encrypted text from data power in Java using below code. Am using symmetric key mechanism. Thee below code is able to Decrypt the data but gives me a data with unwanted characters f ollowed by plain text. I tried to substring the response for 16 characters, but I found not all the decrypted texts have the same unwanted characters. Can you please help me on this. Appreciate your response.


public String decrypt(String encryptedText, String basekey){

byte[] encryptedTextByte = DatatypeConverter.parseBase64Binary(encrypted text);

byte[] key = Base64.getDecoder().decode(base64Key.getBytes());

byte[] IV = new byte[16];

IvParameterSpec ivSpec = new IvParameterSpec(iv);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding);

 SecretKeySpec secret = new SecretKeySpec(key, "AES");

cipher.init(Cipher.DECRYPT_MODE, secret, ivSpec);

return new String(cipher.doFinal(encryptedTextByte));

}

Encryption logic in datapower

<xsl:variable name="ciphertext">
  <xsl:value-of select="dp:encrypt-data($algorithm,$session-key,$node)"/>
</xsl:variable>

I found solution, am using substring of 16 to remove the padding. But ideally I should be removing the bytes. So before conversion to String I will remove the extra bytes and then convert it to String. So, I only have plain text.

public String decrypt(String encryptedText, String basekey){

byte[] encryptedTextByte = DatatypeConverter.parseBase64Binary(encrypted text);

byte[] key = Base64.getDecoder().decode(base64Key.getBytes());

byte[] IV = new byte[16];

IvParameterSpec ivSpec = new IvParameterSpec(iv);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding);

 SecretKeySpec secret = new SecretKeySpec(key, "AES");

cipher.init(Cipher.DECRYPT_MODE, secret, ivSpec);

byte[] decryptedBytes = cipher.doFinal(encryptedTextByte);

// Removing extra characters here

byte[] plainBytes = Arrays.copyOfRange(decryptedBytes, 16, decryptedBytes.length);

return new String(plainBytes);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM