Search code examples
javascriptrubyruby-on-rails-3cryptographycryptojs

decrypt using cryptojs not working


I m trying to send a encrypted data via json to client and decrypt it in client using cryptojs

My ROR code

def getkey

  aes = OpenSSL::Cipher::Cipher.new('AES-128-CBC') 
  aes.encrypt
  key = aes.random_key

  session[:key] = key

  render :json => {:mkey => Base64.encode64(key).gsub(/\n/, '')}
end

def getdata
    js = "SOME DATA"

    aes = OpenSSL::Cipher::Cipher.new('AES-128-CBC')
    aes.encrypt
    aes.key = session[:key]
    encrypted = aes.update(js) + aes.final

    encrypted = Base64.encode64(encrypted).gsub(/\n/, '')

    render :json => {:data => encrypted}
end

My Javascript code

var key = btoa(BASE64_ENCODED_KEY);
$http({method: 'GET', url: '/appi/getdata/', params: {SOME_PARAMS}})
.success(function(data, status, headers, config) {
  var dat = btoa(data.data);
  var decrypted = CryptoJS.AES.decrypt(dat, key);
  console.log(decrypted.toString(CryptoJS.enc.Utf8));
});

Getting javascript error "Error: Malformed UTF-8 data." in chrome

Below is a url for simplified jsfiddle for above query

http://jsfiddle.net/7DRdK/1/


Solution

  • Thanks owlstead, I already figured that out it last couple of days.

    I raised this query in crypto-js thread, the problem was I was not specifying IV in crypto-js decryption, as in Ruby if you dont specify any IV it adds \0 as IV.

    Below is working code

    var encrypted = {};
    encrypted.ciphertext = CryptoJS.enc.Base64.parse(data.data);
    
    var decrypted = CryptoJS.AES.decrypt(encrypted, CryptoJS.enc.Base64.parse(BASE64_ENCODED_KEY),
              { iv: CryptoJS.enc.Hex.parse('00000000000000000000000000000000') });;
    console.log(decrypted.toString(CryptoJS.enc.Utf8));
    

    This worked for me, this solution was provided to me yesterday by Jeff.Mott.OR (current cryptojs lead dev)