Ruby中的DES解密

时间:2014-10-21 18:02:52

标签: ruby encryption des

以下是我对DES解密的java代码:

public static byte[] decrypt(final byte[] value, final String key) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {
    final DESKeySpec objDesKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
    final SecretKeyFactory objKeyFactory = SecretKeyFactory.getInstance("DES");
    final SecretKey objSecretKey = objKeyFactory.generateSecret(objDesKeySpec);
    final byte[] rgbIV = key.getBytes();
    final IvParameterSpec iv = new IvParameterSpec(rgbIV);
    final Cipher objCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    objCipher.init(2, objSecretKey, iv);
    return objCipher.doFinal(value);
}

我尝试将其转换为Ruby代码,如下所示:

def decryption(key, decodeString)
    ALG = 'des'
    cipher = OpenSSL::Cipher::Cipher.new(ALG)
    cipher.decrypt  #choose descryption mode.
    cipher.key = key
    plain = cipher.update(decodeString )
    plain << cipher.final
end

执行java和ruby代码后,我得到了相同大小的字节,但字节的内容不同。我哪里出错了?

2 个答案:

答案 0 :(得分:3)

根据这篇文章:http://43n141e.blogspot.tw/2008/08/des-encryption-java-to-openssl-to-ruby.html,我尝试以下两个步骤: 1.用Java计算iv值:

String key = "123456"
final byte[] rgbIV = key.getBytes();
final IvParameterSpec iv = new IvParameterSpec(rgbIV);
byte[] ivBytes = iv.getIV();
StringBuffer sbuf = new StringBuffer();
for (byte b : ivBytes) {
    sbuf.append(String.format("%02x", (b & 0xFF)));
}
System.out.println("iv: " + sbuf);

2。解密Ruby:

def decode(encryptedString, key, iv)
    decrypt = OpenSSL::Cipher::Cipher.new('des-cbc')
    decrypt.decrypt
    decrypt.key = key
    decrypt.iv = iv.scan(/../).map{|b|b.hex}.pack('c*')
    decrypt.update(encryptedString) + decrypt.final
end

它有效!

答案 1 :(得分:2)

感谢您的提问!

为此,请使用OpenSSL :: Cipher库。以下是AES的一些示例代码的链接:http://www.ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/Cipher.html#class-OpenSSL::Cipher-label-Encrypting+and+decrypting+some+data

要使用DES,请运行此命令以查看您的Ruby安装是否支持DES。

puts OpenSSL::Cipher.ciphers