BadPaddingException just with letters like “o”, “b”, “c”sun.misc.BASE64 to apache commonsWhat causes the error “java.security.InvalidKeyException: Parameters missing”?Java AES-128 encryption of 1 block (16 byte) returns 2 blocks(32 byte) as outputBadPaddingException: Given final block not properly paddedstring encryption in javascript and decryption in javajava.security.InvalidKeyException: Wrong key size during decryptionCannot extract android backup with abe.jarEncryption/decryption: HMAC tags don't match in decryption methodHow to add and get specific number of bytes from a file using file input and output streams?

Talk interpreter

Breaker Mapping Questions

When calculating a force, why do I get different result when I try to calculate via torque vs via sum of forces at an axis?

HJM in infinite dimensions

Improper Fourier transform

When, exactly, does the Rogue Scout get to use their Skirmisher ability?

Handling Disruptive Student on the Autism Spectrum

How much does Commander Data weigh?

Foreign language movie, people enter a church but find they can't leave

How do I make my image comply with the requirements of this photography competition?

"There were either twelve sexes or none."

Is first Ubuntu user root?

Why isn't "I've" a proper response?

What does "rel" in `mathrel` and `stackrel` stands for?

To get so rich that you are not in need of anymore money

How do proponents of Sola Scriptura address the ministry of those Apostles who authored no parts of Scripture?

Filling a listlineplot with a texture

Are the players on the same team as the DM?

I don't have the theoretical background in my PhD topic. I can't justify getting the degree

Where does learning new skills fit into Agile?

Does ostensible/specious make sense in this sentence?

Removal of て in Japanese novels

Was the Boeing 2707 design flawed?

What is the coil voltage of this contactor?



BadPaddingException just with letters like “o”, “b”, “c”


sun.misc.BASE64 to apache commonsWhat causes the error “java.security.InvalidKeyException: Parameters missing”?Java AES-128 encryption of 1 block (16 byte) returns 2 blocks(32 byte) as outputBadPaddingException: Given final block not properly paddedstring encryption in javascript and decryption in javajava.security.InvalidKeyException: Wrong key size during decryptionCannot extract android backup with abe.jarEncryption/decryption: HMAC tags don't match in decryption methodHow to add and get specific number of bytes from a file using file input and output streams?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I'm making a program which works with messages cryptography by Socket. But, when in my messages has a "o", or "b", or "c" and another letters, i receives that Exception in the decrypto moment.



Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:975)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at teste1.Decrypt.decrypt(Decrypt.java:15)
at teste1.Server.main(Server.java:24)


Yep, my message arrives completed with all the characters, so i don't think in some character was lost in the trasmission. So i don't really know what's the problem, because i've tried to changes a lot of things, but i continued recieving this Exception.



Decrypt class:



package teste1;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Decrypt

String IV = "AAAAAAAAAAAAAAAA";

public String decrypt(String str, String keys) throws Exception
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys.getBytes("UTF-8"), "AES");
decrypt.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return new String(decrypt.doFinal(str.getBytes()),"UTF-8");





If wants the encrypt class too:



package teste1;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Encrypt

String IV = "AAAAAAAAAAAAAAAA";

public byte[] encrypt(String menE, String keys) throws Exception
Cipher encrypt = Cipher.getInstance("AES/EBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys.getBytes("UTF-8"), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return encrypt.doFinal(menE.getBytes());











share|improve this question


























  • Bytes are not encoded characters. Don't transform bytes to strings. Or if you do, use a Base64 encoder.

    – JB Nizet
    Mar 27 at 19:02











  • Transfer bytes into base64 after encryption and decode base64 into bytes before decrypt String encStr = new String(Base64.getEncoder().encode(out)); and byte[] enc = Base64.getDecoder().decode(encryptedText); that will solve your problem.

    – kelalaka
    Mar 27 at 19:47


















1















I'm making a program which works with messages cryptography by Socket. But, when in my messages has a "o", or "b", or "c" and another letters, i receives that Exception in the decrypto moment.



Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:975)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at teste1.Decrypt.decrypt(Decrypt.java:15)
at teste1.Server.main(Server.java:24)


Yep, my message arrives completed with all the characters, so i don't think in some character was lost in the trasmission. So i don't really know what's the problem, because i've tried to changes a lot of things, but i continued recieving this Exception.



Decrypt class:



package teste1;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Decrypt

String IV = "AAAAAAAAAAAAAAAA";

public String decrypt(String str, String keys) throws Exception
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys.getBytes("UTF-8"), "AES");
decrypt.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return new String(decrypt.doFinal(str.getBytes()),"UTF-8");





If wants the encrypt class too:



package teste1;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Encrypt

String IV = "AAAAAAAAAAAAAAAA";

public byte[] encrypt(String menE, String keys) throws Exception
Cipher encrypt = Cipher.getInstance("AES/EBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys.getBytes("UTF-8"), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return encrypt.doFinal(menE.getBytes());











share|improve this question


























  • Bytes are not encoded characters. Don't transform bytes to strings. Or if you do, use a Base64 encoder.

    – JB Nizet
    Mar 27 at 19:02











  • Transfer bytes into base64 after encryption and decode base64 into bytes before decrypt String encStr = new String(Base64.getEncoder().encode(out)); and byte[] enc = Base64.getDecoder().decode(encryptedText); that will solve your problem.

    – kelalaka
    Mar 27 at 19:47














1












1








1








I'm making a program which works with messages cryptography by Socket. But, when in my messages has a "o", or "b", or "c" and another letters, i receives that Exception in the decrypto moment.



Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:975)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at teste1.Decrypt.decrypt(Decrypt.java:15)
at teste1.Server.main(Server.java:24)


Yep, my message arrives completed with all the characters, so i don't think in some character was lost in the trasmission. So i don't really know what's the problem, because i've tried to changes a lot of things, but i continued recieving this Exception.



Decrypt class:



package teste1;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Decrypt

String IV = "AAAAAAAAAAAAAAAA";

public String decrypt(String str, String keys) throws Exception
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys.getBytes("UTF-8"), "AES");
decrypt.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return new String(decrypt.doFinal(str.getBytes()),"UTF-8");





If wants the encrypt class too:



package teste1;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Encrypt

String IV = "AAAAAAAAAAAAAAAA";

public byte[] encrypt(String menE, String keys) throws Exception
Cipher encrypt = Cipher.getInstance("AES/EBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys.getBytes("UTF-8"), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return encrypt.doFinal(menE.getBytes());











share|improve this question
















I'm making a program which works with messages cryptography by Socket. But, when in my messages has a "o", or "b", or "c" and another letters, i receives that Exception in the decrypto moment.



Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:975)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at teste1.Decrypt.decrypt(Decrypt.java:15)
at teste1.Server.main(Server.java:24)


Yep, my message arrives completed with all the characters, so i don't think in some character was lost in the trasmission. So i don't really know what's the problem, because i've tried to changes a lot of things, but i continued recieving this Exception.



Decrypt class:



package teste1;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Decrypt

String IV = "AAAAAAAAAAAAAAAA";

public String decrypt(String str, String keys) throws Exception
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys.getBytes("UTF-8"), "AES");
decrypt.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return new String(decrypt.doFinal(str.getBytes()),"UTF-8");





If wants the encrypt class too:



package teste1;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Encrypt

String IV = "AAAAAAAAAAAAAAAA";

public byte[] encrypt(String menE, String keys) throws Exception
Cipher encrypt = Cipher.getInstance("AES/EBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys.getBytes("UTF-8"), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return encrypt.doFinal(menE.getBytes());








java exception encryption cryptography






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 19:09







Shynz0

















asked Mar 27 at 18:50









Shynz0Shynz0

84 bronze badges




84 bronze badges















  • Bytes are not encoded characters. Don't transform bytes to strings. Or if you do, use a Base64 encoder.

    – JB Nizet
    Mar 27 at 19:02











  • Transfer bytes into base64 after encryption and decode base64 into bytes before decrypt String encStr = new String(Base64.getEncoder().encode(out)); and byte[] enc = Base64.getDecoder().decode(encryptedText); that will solve your problem.

    – kelalaka
    Mar 27 at 19:47


















  • Bytes are not encoded characters. Don't transform bytes to strings. Or if you do, use a Base64 encoder.

    – JB Nizet
    Mar 27 at 19:02











  • Transfer bytes into base64 after encryption and decode base64 into bytes before decrypt String encStr = new String(Base64.getEncoder().encode(out)); and byte[] enc = Base64.getDecoder().decode(encryptedText); that will solve your problem.

    – kelalaka
    Mar 27 at 19:47

















Bytes are not encoded characters. Don't transform bytes to strings. Or if you do, use a Base64 encoder.

– JB Nizet
Mar 27 at 19:02





Bytes are not encoded characters. Don't transform bytes to strings. Or if you do, use a Base64 encoder.

– JB Nizet
Mar 27 at 19:02













Transfer bytes into base64 after encryption and decode base64 into bytes before decrypt String encStr = new String(Base64.getEncoder().encode(out)); and byte[] enc = Base64.getDecoder().decode(encryptedText); that will solve your problem.

– kelalaka
Mar 27 at 19:47






Transfer bytes into base64 after encryption and decode base64 into bytes before decrypt String encStr = new String(Base64.getEncoder().encode(out)); and byte[] enc = Base64.getDecoder().decode(encryptedText); that will solve your problem.

– kelalaka
Mar 27 at 19:47













1 Answer
1






active

oldest

votes


















2















That happens because Strings change your bytes, you should really use Base64
if strings are a must.



If you want to test that run this code:



byte[] aByte = -45;
System.out.println(Arrays.toString(new String(aByte, StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8)));


It will output: [-17, -65, -67] (which is not -45).



Anyways so a few tips for you:



  • You cannot encrypt with "ECB" and decrypt with "CBC".

  • An IV should not be a constant. you should generate a new IV for every message and send it along with the message.

  • Don't specify "UTF-8" use StandardCharsets.UTF_8 (note if using android: StandardCharsets.UTF-8 is API 19+ so you should have a constant for Charset.forName("UTF-8"))

Here is some example code for how to do it with Base64:



public byte[] encrypt(String message, String key, String iv) throws Exception 
Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return encrypt.doFinal(/*Get bytes from your message*/message.getBytes(StandardCharsets.UTF_8));


public String decrypt(String encryptedMessage, String key, String iv) throws Exception
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
decrypt.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return new String(decrypt.doFinal(Base64.getDecoder().decode(encryptedMessage)), StandardCharsets.UTF_8);



And run it with



//your message
String message = "Hello World!";
//generate a new AES key. (an AES key is just a random sequence 16 bytes)
SecureRandom random = new SecureRandom();
byte[] aesKey = new byte[16];
random.nextBytes(aesKey);
//generate a new initialization vector (iv) which is also a random sequence of 16 bytes.
byte[] iv = new byte[16];
random.nextBytes(iv);

String aesKeyAsString = Base64.getEncoder().encodeToString(aesKey);
String ivAsString = Base64.getEncoder().encodeToString(iv);
//encrypt
byte[] encrypted = encrypt(message, aesKeyAsString, ivAsString);
//enocde your encrypted byte[] to String
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
//decrypt
String decrypted = decrypt(encryptedString, aesKeyAsString, ivAsString);
//print your results
System.out.println("Encrypted: " + encryptedString + " Decrypted: " + decrypted);


Outputs:



Encrypted: |encrypted string depended on the generated key and iv| Decrypted: Hello World!



You can also use the more efficient way and use byte[] instead of Strings but it's your choice.






share|improve this answer



























  • omg bro... thank you so much! it's working now!

    – Shynz0
    Mar 28 at 14:15











  • @Shynz0 Happy to help

    – OughtToPrevail
    Mar 28 at 18:38










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55384527%2fbadpaddingexception-just-with-letters-like-o-b-c%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2















That happens because Strings change your bytes, you should really use Base64
if strings are a must.



If you want to test that run this code:



byte[] aByte = -45;
System.out.println(Arrays.toString(new String(aByte, StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8)));


It will output: [-17, -65, -67] (which is not -45).



Anyways so a few tips for you:



  • You cannot encrypt with "ECB" and decrypt with "CBC".

  • An IV should not be a constant. you should generate a new IV for every message and send it along with the message.

  • Don't specify "UTF-8" use StandardCharsets.UTF_8 (note if using android: StandardCharsets.UTF-8 is API 19+ so you should have a constant for Charset.forName("UTF-8"))

Here is some example code for how to do it with Base64:



public byte[] encrypt(String message, String key, String iv) throws Exception 
Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return encrypt.doFinal(/*Get bytes from your message*/message.getBytes(StandardCharsets.UTF_8));


public String decrypt(String encryptedMessage, String key, String iv) throws Exception
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
decrypt.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return new String(decrypt.doFinal(Base64.getDecoder().decode(encryptedMessage)), StandardCharsets.UTF_8);



And run it with



//your message
String message = "Hello World!";
//generate a new AES key. (an AES key is just a random sequence 16 bytes)
SecureRandom random = new SecureRandom();
byte[] aesKey = new byte[16];
random.nextBytes(aesKey);
//generate a new initialization vector (iv) which is also a random sequence of 16 bytes.
byte[] iv = new byte[16];
random.nextBytes(iv);

String aesKeyAsString = Base64.getEncoder().encodeToString(aesKey);
String ivAsString = Base64.getEncoder().encodeToString(iv);
//encrypt
byte[] encrypted = encrypt(message, aesKeyAsString, ivAsString);
//enocde your encrypted byte[] to String
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
//decrypt
String decrypted = decrypt(encryptedString, aesKeyAsString, ivAsString);
//print your results
System.out.println("Encrypted: " + encryptedString + " Decrypted: " + decrypted);


Outputs:



Encrypted: |encrypted string depended on the generated key and iv| Decrypted: Hello World!



You can also use the more efficient way and use byte[] instead of Strings but it's your choice.






share|improve this answer



























  • omg bro... thank you so much! it's working now!

    – Shynz0
    Mar 28 at 14:15











  • @Shynz0 Happy to help

    – OughtToPrevail
    Mar 28 at 18:38















2















That happens because Strings change your bytes, you should really use Base64
if strings are a must.



If you want to test that run this code:



byte[] aByte = -45;
System.out.println(Arrays.toString(new String(aByte, StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8)));


It will output: [-17, -65, -67] (which is not -45).



Anyways so a few tips for you:



  • You cannot encrypt with "ECB" and decrypt with "CBC".

  • An IV should not be a constant. you should generate a new IV for every message and send it along with the message.

  • Don't specify "UTF-8" use StandardCharsets.UTF_8 (note if using android: StandardCharsets.UTF-8 is API 19+ so you should have a constant for Charset.forName("UTF-8"))

Here is some example code for how to do it with Base64:



public byte[] encrypt(String message, String key, String iv) throws Exception 
Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return encrypt.doFinal(/*Get bytes from your message*/message.getBytes(StandardCharsets.UTF_8));


public String decrypt(String encryptedMessage, String key, String iv) throws Exception
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
decrypt.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return new String(decrypt.doFinal(Base64.getDecoder().decode(encryptedMessage)), StandardCharsets.UTF_8);



And run it with



//your message
String message = "Hello World!";
//generate a new AES key. (an AES key is just a random sequence 16 bytes)
SecureRandom random = new SecureRandom();
byte[] aesKey = new byte[16];
random.nextBytes(aesKey);
//generate a new initialization vector (iv) which is also a random sequence of 16 bytes.
byte[] iv = new byte[16];
random.nextBytes(iv);

String aesKeyAsString = Base64.getEncoder().encodeToString(aesKey);
String ivAsString = Base64.getEncoder().encodeToString(iv);
//encrypt
byte[] encrypted = encrypt(message, aesKeyAsString, ivAsString);
//enocde your encrypted byte[] to String
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
//decrypt
String decrypted = decrypt(encryptedString, aesKeyAsString, ivAsString);
//print your results
System.out.println("Encrypted: " + encryptedString + " Decrypted: " + decrypted);


Outputs:



Encrypted: |encrypted string depended on the generated key and iv| Decrypted: Hello World!



You can also use the more efficient way and use byte[] instead of Strings but it's your choice.






share|improve this answer



























  • omg bro... thank you so much! it's working now!

    – Shynz0
    Mar 28 at 14:15











  • @Shynz0 Happy to help

    – OughtToPrevail
    Mar 28 at 18:38













2














2










2









That happens because Strings change your bytes, you should really use Base64
if strings are a must.



If you want to test that run this code:



byte[] aByte = -45;
System.out.println(Arrays.toString(new String(aByte, StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8)));


It will output: [-17, -65, -67] (which is not -45).



Anyways so a few tips for you:



  • You cannot encrypt with "ECB" and decrypt with "CBC".

  • An IV should not be a constant. you should generate a new IV for every message and send it along with the message.

  • Don't specify "UTF-8" use StandardCharsets.UTF_8 (note if using android: StandardCharsets.UTF-8 is API 19+ so you should have a constant for Charset.forName("UTF-8"))

Here is some example code for how to do it with Base64:



public byte[] encrypt(String message, String key, String iv) throws Exception 
Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return encrypt.doFinal(/*Get bytes from your message*/message.getBytes(StandardCharsets.UTF_8));


public String decrypt(String encryptedMessage, String key, String iv) throws Exception
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
decrypt.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return new String(decrypt.doFinal(Base64.getDecoder().decode(encryptedMessage)), StandardCharsets.UTF_8);



And run it with



//your message
String message = "Hello World!";
//generate a new AES key. (an AES key is just a random sequence 16 bytes)
SecureRandom random = new SecureRandom();
byte[] aesKey = new byte[16];
random.nextBytes(aesKey);
//generate a new initialization vector (iv) which is also a random sequence of 16 bytes.
byte[] iv = new byte[16];
random.nextBytes(iv);

String aesKeyAsString = Base64.getEncoder().encodeToString(aesKey);
String ivAsString = Base64.getEncoder().encodeToString(iv);
//encrypt
byte[] encrypted = encrypt(message, aesKeyAsString, ivAsString);
//enocde your encrypted byte[] to String
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
//decrypt
String decrypted = decrypt(encryptedString, aesKeyAsString, ivAsString);
//print your results
System.out.println("Encrypted: " + encryptedString + " Decrypted: " + decrypted);


Outputs:



Encrypted: |encrypted string depended on the generated key and iv| Decrypted: Hello World!



You can also use the more efficient way and use byte[] instead of Strings but it's your choice.






share|improve this answer















That happens because Strings change your bytes, you should really use Base64
if strings are a must.



If you want to test that run this code:



byte[] aByte = -45;
System.out.println(Arrays.toString(new String(aByte, StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8)));


It will output: [-17, -65, -67] (which is not -45).



Anyways so a few tips for you:



  • You cannot encrypt with "ECB" and decrypt with "CBC".

  • An IV should not be a constant. you should generate a new IV for every message and send it along with the message.

  • Don't specify "UTF-8" use StandardCharsets.UTF_8 (note if using android: StandardCharsets.UTF-8 is API 19+ so you should have a constant for Charset.forName("UTF-8"))

Here is some example code for how to do it with Base64:



public byte[] encrypt(String message, String key, String iv) throws Exception 
Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return encrypt.doFinal(/*Get bytes from your message*/message.getBytes(StandardCharsets.UTF_8));


public String decrypt(String encryptedMessage, String key, String iv) throws Exception
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
decrypt.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return new String(decrypt.doFinal(Base64.getDecoder().decode(encryptedMessage)), StandardCharsets.UTF_8);



And run it with



//your message
String message = "Hello World!";
//generate a new AES key. (an AES key is just a random sequence 16 bytes)
SecureRandom random = new SecureRandom();
byte[] aesKey = new byte[16];
random.nextBytes(aesKey);
//generate a new initialization vector (iv) which is also a random sequence of 16 bytes.
byte[] iv = new byte[16];
random.nextBytes(iv);

String aesKeyAsString = Base64.getEncoder().encodeToString(aesKey);
String ivAsString = Base64.getEncoder().encodeToString(iv);
//encrypt
byte[] encrypted = encrypt(message, aesKeyAsString, ivAsString);
//enocde your encrypted byte[] to String
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
//decrypt
String decrypted = decrypt(encryptedString, aesKeyAsString, ivAsString);
//print your results
System.out.println("Encrypted: " + encryptedString + " Decrypted: " + decrypted);


Outputs:



Encrypted: |encrypted string depended on the generated key and iv| Decrypted: Hello World!



You can also use the more efficient way and use byte[] instead of Strings but it's your choice.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 28 at 3:14

























answered Mar 28 at 2:11









OughtToPrevailOughtToPrevail

3501 silver badge9 bronze badges




3501 silver badge9 bronze badges















  • omg bro... thank you so much! it's working now!

    – Shynz0
    Mar 28 at 14:15











  • @Shynz0 Happy to help

    – OughtToPrevail
    Mar 28 at 18:38

















  • omg bro... thank you so much! it's working now!

    – Shynz0
    Mar 28 at 14:15











  • @Shynz0 Happy to help

    – OughtToPrevail
    Mar 28 at 18:38
















omg bro... thank you so much! it's working now!

– Shynz0
Mar 28 at 14:15





omg bro... thank you so much! it's working now!

– Shynz0
Mar 28 at 14:15













@Shynz0 Happy to help

– OughtToPrevail
Mar 28 at 18:38





@Shynz0 Happy to help

– OughtToPrevail
Mar 28 at 18:38








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55384527%2fbadpaddingexception-just-with-letters-like-o-b-c%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript