2016-06-15 60 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?非常有用。

相關問題