Note that there are some explanatory texts on larger screens.

plurals
  1. POEncrypt by "DES-EDE3-CBC" in ruby and decrypt in Java
    text
    copied!<p>I am trying to encrypt data by the cipher "DES-EDE3-CBC" in Ruby, then decrypt the encrypted data in Java.</p> <p>Here is the code in Ruby I do the encrypting: </p> <pre><code>require 'digest' require 'openssl' require 'base64' ALG = "DES-EDE3-CBC" key = "80f28a1ef4aa9df6ee2ee3210316b98f383eb344" cipher = OpenSSL::Cipher::Cipher.new(ALG) cipher.pkcs5_keyivgen(key, nil) cipher.encrypt data = "hello" result = cipher.update(data) result &lt;&lt; cipher.final # Write the data to file. File.open("enc.txt", "wb"){|f| f.write result} </code></pre> <p>Then decrypt in Java:</p> <pre><code>import java.security.*; import java.*; import java.io.*; import javax.crypto.*; import javax.crypto.spec.*; public class Test{ public static void main(String[] args) throws Exception { String key = "80f28a1ef4aa9df6ee2ee3210316b98f383eb344"; // Init the key DESKeySpec desKeySpec = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); Key secretKey = keyFactory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] buf = new byte[1024]; InputStream input = new FileInputStream(new File("enc.txt")); FileOutputStream output = new FileOutputStream(new File("dec.txt")); int count = input.read(buf); // Read and decrypt file content while (count &gt;= 0) { output.write(cipher.update(buf, 0, count)); count = input.read(buf); } output.write(cipher.doFinal()); output.flush(); } } </code></pre> <p>But I always get the exception when running the Java code:</p> <pre><code>Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811) at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676) at com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:314) at javax.crypto.Cipher.doFinal(Cipher.java:1969) at Test.main(Test.java:29) </code></pre> <p>I think the problem is the "DES-EDE3-CBC" cipher in Ruby is not compatible with Java "DES/ECB/PKCS5Padding". How I can do it?</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