Module: SJCL

Defined in:
lib/sjcl.rb,
lib/sjcl/pbkdf2.rb,
lib/sjcl/version.rb

Defined Under Namespace

Modules: BitArray, Cipher, Codec, Misc, Mode, Random

Constant Summary collapse

DEFAULT =
{
  v:1, iter:100_000, ks:256, ts:64,
  mode:"ccm", adata:"", cipher:"aes"
}
VERSION =
"1.0.1"

Class Method Summary collapse

Class Method Details

.decrypt(password, jsonstr) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/sjcl.rb', line 19

def self.decrypt(password, jsonstr)
  cipher_obj = JSON.parse(jsonstr, :symbolize_names => true)
  key = SJCL::Misc.pbkdf2(password,
                          cipher_obj[:salt],
                          cipher_obj[:iter],
                          cipher_obj[:ks])
  cipher = SJCL::Cipher::AES.new(key)

  ct = SJCL::Codec::Base64.toBits(cipher_obj[:ct])
  iv = SJCL::Codec::Base64.toBits(cipher_obj[:iv])
  adata = SJCL::Codec::Base64.toBits(cipher_obj[:adata])
  out = SJCL::Mode::CCM.decrypt(cipher, ct, iv, adata)
  SJCL::Codec::UTF8String.fromBits(out)
end

.encrypt(password, str, opts = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/sjcl.rb', line 34

def self.encrypt(password, str, opts={})
  opts = DEFAULT.merge(opts)
  iv = SJCL::Random.randomWords(4)
  salt = SJCL::Codec::Base64.fromBits(SJCL::Random.randomWords(2))
  key = SJCL::Misc.pbkdf2(password,
                          salt,
                          opts[:iter],
                          opts[:ks])
  cipher = SJCL::Cipher::AES.new(key)
  pt = SJCL::Codec::UTF8String.toBits(str)
  adata = SJCL::Codec::UTF8String.toBits(opts[:adata])
  ct = SJCL::Mode::CCM.encrypt(cipher, pt, iv, adata)
  ct = SJCL::Codec::Base64.fromBits(ct)
  out = opts.merge({
    :ct => ct,
    :iv => SJCL::Codec::Base64.fromBits(iv),
    :salt => salt
    })
  out.to_json
end