2016-06-15 98 views
1

我是Ruby的新手,所以如果这个问题很简单,我很抱歉。我必须更新一个Rails应用程序,以便使用密钥来加密字符串。这被传递给一个用django写的api,在那里加密的字符串将使用相同的密钥进行解密。我在Python中有以下代码,但我不确定如何在Ruby中加密关联的消息。任何帮助,将不胜感激。在Ruby中加密字符串并在Python中解密

import base64 
from Crypto.Cipher import AES 
from Crypto import Random 

class AESCipher: 
    def __init__(self, key): 
     self.key = key 

    def encrypt(self, raw): 
     raw = pad(raw) 
     iv = Random.new().read(AES.block_size) 
     cipher = AES.new(self.key, AES.MODE_CBC, iv) 
     return base64.b64encode(iv + cipher.encrypt(raw)) 

    def decrypt(self, enc): 
     enc = base64.b64decode(enc) 
     iv = enc[:16] 
     cipher = AES.new(self.key, AES.MODE_CBC, iv) 
     return unpad(cipher.decrypt(enc[16:])) 
+0

我认为这对日常Ruby用户来说确实不是一个简单的问题。也许将加密/解密委派给底层系统更容易(即运行shell命令)。这样Ruby和Python都可以使用相同的API。 –

+0

答案已更新,应完全解答您的问题。 –

回答

1

经过ArtjomB的反馈,我深入了解了拟议的图书馆。这仅仅是一个围绕ruby openssl的薄包装。所以你可以自己编写一个你的AESCipher的ruby版本。 它采取了一些摆弄和研究,以找到正确的方法:

require 'base64' 
require 'securerandom' 
require 'openssl' 

class AESCipher 
    attr_reader :key 

    def initialize(key) 
    @key = key 
    end 

    def encrypt(raw) 
    iv = SecureRandom.random_bytes(16) 
    cipher = build_encription_cipher(iv) 
    encrypted = cipher.update(raw) + cipher.final 
    Base64.encode64(iv + encrypted) 
    end 

    def decrypt(data) 
    data = Base64.decode64(data) 
    iv, raw = data[0..15], data[16..-1] 
    cipher = build_decrypt_cipher(iv) 
    cipher.update(raw) + cipher.final 
    end 

    private 

    def build_encription_cipher(iv) 
    OpenSSL::Cipher::AES.new(128, :CBC).tap do |cipher| 
     cipher.encrypt 
     cipher.key = key 
     cipher.iv = iv 
     cipher.padding = 0 
    end 
    end 

    def build_decrypt_cipher(iv) 
    OpenSSL::Cipher::AES.new(128, :CBC).tap do |cipher| 
     cipher.decrypt 
     cipher.key = key 
     cipher.iv = iv 
     cipher.padding = 0 
    end 
    end 
end 

在我的测试用例的蟒蛇,反之亦然加密的红宝石版本解密字符串。我对你的python代码做了一个修改:删除了对pad的调用,因为我不知道它是如何填充的,而只是使用了长度为16的长度的字符串)。

的答案colinm in AES Python encryption and Ruby encryption - different behaviour?非常有用。