Last active
August 29, 2015 14:08
-
-
Save sheldonh/589a636ef91b66e8c8a8 to your computer and use it in GitHub Desktop.
Trying to encode ciphertext and its metadata as CMS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def self.encrypt(password, cleartext) | |
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") | |
cipher.encrypt | |
iv = cipher.random_iv | |
salt = Time.now.nsec.to_s | |
iterations = ITERATIONS | |
key_len = cipher.key_len | |
cipher.key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(password, salt, iterations, key_len) | |
ciphertext = cipher.update(cleartext) + cipher.final | |
return ciphertext | |
end | |
=begin | |
Instead of returning ciphertext, I'd like to return the ciphertext and metadata in RFC5652 Cryptographic Message Syntax. | |
Asn1::Sequence.new('contentInfo', [ | |
Asn1::OID.new('{iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1) contentInfo(6)}'), | |
Asn1::Sequence.new('envelopedData', [ | |
Asn1::OID.new('{iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-7(7) envelopedData(3)}'), | |
Asn1::Integer.new('version', :unsure), | |
Asn1::Set.new('recipientInfos', [ | |
Asn1::Sequence.new('passwordRecipientInfo', [ | |
Asn1::Integer.new('version', 0), | |
Asn1::Sequence.new('key_derivation_algorithm_identifier', [ | |
Asn1::OID.new('{iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-5(5) pBKDF2(12)}'), | |
Asn1::Sequence.new('params', [ | |
Asn1::OctetString.new('salt', salt), | |
Asn1::Integer.new('iteration_count', iterations), | |
Asn1::Integer.new('key_length', key_len), | |
Asn1::Sequence.new('prf', [ | |
Asn1::OID.new('{iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) hmacWithSHA1(7)}') | |
]), | |
]) | |
]), | |
Asn1::Sequence.new('key_encryption_algorithm_identifier', [ | |
Asn1::OID.new('{joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) aes(1) aes256-CBC(42)}'), | |
Asn1::Sequence.new('params', [ | |
Asn1::OctetString.new('AES-IV', 16, iv) | |
]) | |
]), | |
# This feels SOOO wrong! Surely the ciphertext goes in EncryptedContentInfo or EncryptedData below?! | |
# But then what goes in here? Is it safe to encrypt the CEK with the KEK and expose that here? | |
Asn1::OctetString('encrypted_key', ciphertext), | |
]), | |
]), | |
#EncryptedContentInfo.new('...'), # Surely this is where I put the ciphertext? | |
#UnprotectedAttributes.new('...') | |
]), | |
#EncryptedData.new('...'), | |
]) | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment