Search code examples
javascriptrubyencryptionencryption-symmetric

Simplest way to "encrypt" string with another string key?


I want to encrypt an input and get an encrypted output, by supplying my own key.

The key points here (which differentiate me from post SO posts and things i've googled so far)

  1. I need to encrypt/decrypt between ruby and javascript, so ideally a library which belongs to both
  2. SIMPLICITY OVER SECURITY. This is the main differentiator... I've tried looking at openSSL tutorials and they're quite advanced. I literally just need to encrypt a string, this doesn't have anything to do with security or sensitive info, as obviously in that case you would use proper encryption. For this I just need to obscure something that isn't very important.

Solution

  • Here's a basic XOR cipher in Ruby:

    key = 'private_key'
    
    def xor_cypher(text, key)
      text.each_byte.zip(key.each_byte.cycle).map { |a, b| (a ^ b).chr }.join
    end
    
    p xor_cypher('This is my secret message', key)
    # "$\x1A\x00\x05A\x1D\x16\x7F\x06\x1CY\x03\x17\n\x04\x04\x00E2\x0E\x16\n\x11\x15\f"
    p xor_cypher("$\x1A\x00\x05A\x1D\x16\x7F\x06\x1CY\x03\x17\n\x04\x04\x00E2\x0E\x16\n\x11\x15\f", key)
    # "This is my secret message"
    

    It shouldn't be too hard to write the same in JS.

    It would be a good idea to use a long, random binary key (not just usual alpha characters) and binary data as well.

    If not, you might compress the data first and encrypt it later.