Ruby OpenSSL :: Cipher :: CipherError(未设置密钥)

时间:2018-11-05 07:59:10

标签: asp.net ruby encryption openssl aes

我正在尝试将现有的.net加密代码移植到ruby。但是遇到了key not set错误。

下面是.net代码,用于加密字符串。

private static string Encrypt(string strToEncrypt, string saltValue, string password)
        {

            using (var csp = new AesCryptoServiceProvider())
            {
                ICryptoTransform e = GetCryptoTransform(csp, true, saltValue, password);
                byte[] inputBuffer = Encoding.UTF8.GetBytes(strToEncrypt);
                byte[] output = e.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);

                string encrypted = Convert.ToBase64String(output);

                return encrypted;
            }
        }

private static ICryptoTransform GetCryptoTransform(AesCryptoServiceProvider csp, bool encrypting, string saltValue, string password)
        {          

            csp.Mode = CipherMode.CBC;
            csp.Padding = PaddingMode.PKCS7;
            var passWord = password;

            var salt = saltValue;

            //a random Init. Vector. just for testing
            String iv = "e675f725e675f123";

            var spec = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes(passWord), Encoding.UTF8.GetBytes(salt), 1000);
            byte[] key = spec.GetBytes(16);


            csp.IV = Encoding.UTF8.GetBytes(iv);
            csp.Key = key;         


            if (encrypting)
            {
                return csp.CreateEncryptor();
            }
            return csp.CreateDecryptor();
        }

我已经使用Ruby的OpenSSL::PKCS5库生成密钥,并使用OpenSSL::Cipher进行加密,并使用了诸如下面的AES算法。

  def aes_encrypt(input_string)
    cipher = OpenSSL::Cipher.new('AES-128-CBC')
    cipher.encrypt
    key = encryption_key
    iv  = cipher.random_iv

    cipher.update(input_string) + cipher.final
  end

  def encryption_key
    OpenSSL::PKCS5.pbkdf2_hmac_sha1(PASSWORD, SALT, 1000, 16)
  end

谁能告诉我我想念的地方吗? (填充?)

0 个答案:

没有答案