Skip to content

OpenSSL::Cipher::Cipher produces garbage result if #encrypt is called after setting key #73

@tarcieri

Description

@tarcieri

OpenSSL::Cipher::Cipher ostensibly depends on #encrypt or #decrypt being called first before setting #key=. However, if #key= is called first, it seems to be silently replaced with a different value, and the encrypt operation instead produces a garbage result.

Personally I would prefer #key= to raise an exception unless #encrypt or #decrypt has already been called. A garbage encryption is undesirable and confusing.

Repro code:

require 'openssl'

# AES-128 ECB mode test vectors
# Taken from https://boringssl.googlesource.com/boringssl/+/2272/crypto/cipher/cipher_test.txt#24
KEY        = ["2b7e151628aed2a6abf7158809cf4f3c"].pack("H*")
PLAINTEXT  = ["6bc1bee22e409f96e93d7e117393172a"].pack("H*")
CIPHERTEXT = ["3ad77bb40d7a3660a89ecaf32466ef97"].pack("H*")

cipher = OpenSSL::Cipher::Cipher.new("aes-128-ecb")
cipher.key = KEY
cipher.padding = 0 # Padding is enabled by default, but makes no sense with ECB mode

print "Testing encryption: "

cipher.encrypt
ciphertext = cipher.update(PLAINTEXT) << cipher.final

if ciphertext == CIPHERTEXT
  puts "OK!"
else
  puts "FAILED! Got #{ciphertext.inspect} instead of #{CIPHERTEXT.inspect}"
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions