AES encryp-decrypt is not working properly --Android - java

I want to encrypt an arbitrary text with RSA, but as I read, RSA dont allow to long texts, so firsts, I need to encrypt with AES-256 (for example), then encrypt the AES key with RSA public, add the encrypted text(with AES), and send the message.
At this moment, I'm doing the AES enc-dec. But I'm doing something wrong because is not decrypting the message properly:
First I generate the AES Key:
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(KEY_SIZE_AES);
this.secretKey_AES = keyGenerator.generateKey();
return this.secretKey_AES;
then I encrypt the message:
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey_AES);
byte[] encrypted = cipher.doFinal(message.getBytes("UTF-8"));
String encryptedMessage = Base64.encodeToString(encrypted, Base64.DEFAULT);
return encryptedMessage;
and finally I decrypt it:
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey_AES);
byte[] decrypted = cipher.doFinal(Base64.decode(message,Base64.DEFAULT));
String decryptedMessage = new String(Base64.encode(decrypted, Base64.DEFAULT));
return decryptedMessage;
But the decrypted text is not the same as the original. I'm missing somthing?
Or I forget some step?
Example:

Your code is working properly, but you are encoding the result in BASE64. ("Elias" is "RWxpYXM" in base64). Just change
String decryptedMessage = new String(Base64.encode(decrypted, Base64.DEFAULT));
with
String decryptedMessage = new String(decrypted, "UTF-8");
Note that this method will only work for text strings

Related

How to decrypt an AES encrypted string while having only the secret key

I am consuming a SOAP API that sends a response that is encrypted with AES. I too have the secret key from the API provider. However I am a bit confused on how to decrypt the response.
All guides that describe how I can decrypt the message tell me I need SecretKeySpec when using javax.crypto.Cipher. However I have no idea what is actually expected there?
Here is an example what I am trying to do:
final String encryptedResponse = "F9nwhTquiEcRY3wfwCGVH1yvZ1fl28VnBXQ3vo6fyCzdV0MnOmeeHg8ea/7c/9ZT0AeEywnR06r5eUoeq4Swf/bFIixc9JJEYB7/fJ0h6I7blQbiOuks7QOUBoSMNaAum1NYTgTm0MHbM3GYLHDPlb8PkBFTL0XxZalKqcqRuhr3BQxPfITeSXjqSvPvy5Wt1Jq";
final String secretKey = "ijsdfgDJJff42h3412";
BASE64Decoder myDecoder = new BASE64Decoder();
byte[] crypted = myDecoder.decodeBuffer(secretKey);
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] cipherData = cipher.doFinal(crypted);
String decryptedResponse = new String(cipherData);
here I receive the following error
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
The key length should be 16,get the true key first;
mayby the key length should be 16,get the true key first;

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);
}

Decrypting a message encrypted using a hashed key

I have a problem where I need to decrypt a message which was encrypted using AES=256. I am already provided with a key and vector. I have to hash the provided key using SHA-256 and then use this hash to encrypt a message. The decryption code runs fine but the result is not the original String.
Result: ?m?>? ???????z?p???>??<3? (the exact text is different, but after copying and pasting it, it is different).
My code below:
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest("someKey".getBytes(ENCODING_UTF8));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("somevector".getBytes(ENCODING_UTF8));
SecretKeySpec skeySpec = new SecretKeySpec(hashBytes, AES);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] cipherText = cipher.doFinal(plainText.getBytes(ENCODING_UTF8));
encrypted = EACECryptoUtils.base64Encode(cipherText);
Cipher decryptCipher = Cipher.getInstance(TRANSFORMATION_TYPE);
IvParameterSpec decryptIV = new IvParameterSpec("somevector".getBytes(ENCODING_UTF8));
SecretKeySpec decryptSkeySpec = new SecretKeySpec(hashBytes, AES);
decryptCipher.init(Cipher.DECRYPT_MODE, decryptSkeySpec, decryptIV);
byte[] original = cipher.doFinal(EACECryptoUtils.base64Decode(encrypted));
decrypted = new String(original);
} catch (Exception e) {
log.error(new LogRecord(FUNCTION_NAME + "Exception while encrypting the data", e));
throw e;
}
}
byte[] original = cipher.doFinal(EACECryptoUtils.
I believe you should use decryptCipher instead of cipher

What should be the output of the AES cipher?

I am encrypting a string with AES in Java Netbeans using
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
System.err.println(new String(encrypted));
The result I am getting are special characters. If I encrypt the text "1111"
with a 128 bit key "Bar12345Bar12345" then I am getting the output as []3SU[][][]~a[][]`)
Is this valid?
If not what should be the output then and how can i get the correct output?

convert byte[] to AES key

i have a AESkey which encrypted by a public key, and later decrypted by a private key
Cipher cipher = Cipher.getInstance("RSA");
PrivateKey privateKey = keyPair.getPrivate();
// decrypt the ciphertext using the private key
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedText = cipher.doFinal(theBytes);
theBytes is a byte[] containing a encrypted AESkey, the question is how to convert the decryptedText back to the AESkey?
I believe you're receiving an RSA-encrypted AES key along with some AES-encrypted data, and you still need to perform the second of 2 encryptions. Right?
So, anyway, you can load a key from the byte array.
SecretKeySpec secretKeySpec = new SecretKeySpec(decryptedText, "AES");
Subsequently you'd do something like this, to decrypt the AES-encrypted data, 'encrypted':
Cipher cipherAes = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipherAes.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedBytes = cipherAes.doFinal(encrypted);
String decryptedString = new String(decryptedBytes);
The /CBC/PKCS7Padding specification may vary, depending on how it was specified during encryption.
Hope this helps.

Categories