Note that there are some explanatory texts on larger screens.

plurals
  1. POJava encryption by client and decryption by server, using PBKDF2WithHmacSHA1 and AES/CBC/PKCS5Padding
    text
    copied!<p>I'm going for secure confidentiality as long as the private key stays secret, and I get following error in my app when decrypting: javax.crypto.BadPaddingException: Given final block not properly padded</p> <p>The code: </p> <pre><code>// Encryption, client side byte[] plainData = "hello plaintext!".getBytes("UTF-8"); byte[] salt = new byte[64]; new SecureRandom().nextBytes(salt); KeySpec spec = new javax.crypto.spec.PBEKeySpec("password".toCharArray(), salt, 1024, 256); SecretKey sk = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sk.getEncoded(), "AES")); byte[] iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); byte[] ciphertext = cipher.doFinal(plainData); System.out.println("ciphertext: "+new String(ciphertext, "UTF-8")); // cipher // Decryption, server side KeySpec spec2 = new javax.crypto.spec.PBEKeySpec("password".toCharArray(), salt, 1024, 256); SecretKey sk2 = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec2); Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher2.init(Cipher.DECRYPT_MODE, new SecretKeySpec(sk2.getEncoded(), "AES"), new IvParameterSpec(iv)); // Get the same IV value from client/encryptor aswell, still random String plaintext = new String(cipher2.doFinal(ciphertext), "UTF-8"); System.out.println("decrypted plaintext: "+plaintext); // plain </code></pre> <p>Is it the randomness of salt that causing the problem?</p> <p>I can decrypt it fine when I make use of the object references on the client side, but I need my own instances on the server.</p> <p>Great thanks in advance for correcting my error(s)!</p> <p>*<em>EDIT: *</em> Code updated and corrected</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload