Class: Origami::Encryption::AES
- Inherits:
-
Object
- Object
- Origami::Encryption::AES
- Defined in:
- lib/origami/encryption.rb
Overview
Class wrapper for AES mode CBC.
Constant Summary collapse
- BLOCKSIZE =
16
Instance Attribute Summary collapse
-
#iv ⇒ Object
writeonly
Sets the attribute iv.
Class Method Summary collapse
Instance Method Summary collapse
- #decrypt(data) ⇒ Object
- #encrypt(data) ⇒ Object
-
#initialize(key, iv, use_padding = true) ⇒ AES
constructor
A new instance of AES.
Constructor Details
#initialize(key, iv, use_padding = true) ⇒ AES
Returns a new instance of AES.
580 581 582 583 584 585 586 587 588 589 590 591 592 |
# File 'lib/origami/encryption.rb', line 580 def initialize(key, iv, use_padding = true) unless [16, 24, 32].include?(key.size) raise EncryptionError, "Key must have a length of 128, 192 or 256 bits." end if not iv.nil? and iv.size != BLOCKSIZE raise EncryptionError, "Initialization vector must have a length of #{BLOCKSIZE} bytes." end @key = key @iv = iv @use_padding = use_padding end |
Instance Attribute Details
#iv=(value) ⇒ Object (writeonly)
Sets the attribute iv
570 571 572 |
# File 'lib/origami/encryption.rb', line 570 def iv=(value) @iv = value end |
Class Method Details
Instance Method Details
#decrypt(data) ⇒ Object
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 |
# File 'lib/origami/encryption.rb', line 612 def decrypt(data) unless data.size % BLOCKSIZE == 0 raise EncryptionError, "Data must be 16-bytes padded (data size = #{data.size} bytes)" end @iv = data.slice!(0, BLOCKSIZE) aes = OpenSSL::Cipher.new("aes-#{@key.length << 3}-cbc").decrypt aes.iv = @iv aes.key = @key aes.padding = 0 plain = (aes.update(data) + aes.final).unpack("C*") if @use_padding padlen = plain[-1] unless padlen.between?(1, 16) raise EncryptionError, "Incorrect padding length : #{padlen}" end padlen.times do pad = plain.pop raise EncryptionError, "Incorrect padding byte : 0x#{pad.to_s 16}" if pad != padlen end end plain.pack("C*") end |
#encrypt(data) ⇒ Object
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 |
# File 'lib/origami/encryption.rb', line 594 def encrypt(data) if @iv.nil? raise EncryptionError, "No initialization vector has been set." end if @use_padding padlen = BLOCKSIZE - (data.size % BLOCKSIZE) data << (padlen.chr * padlen) end aes = OpenSSL::Cipher.new("aes-#{@key.length << 3}-cbc").encrypt aes.iv = @iv aes.key = @key aes.padding = 0 @iv + aes.update(data) + aes.final end |