I am implementing a hierarchical key system with a randomly generated master key and many randomly generated data keys that should be encrypted using the master key. I am wondering what the best way to encrypt the data keys using the master key is. I am thinking that if I XOR the master key with the data key, that should be simple and safe. Is it? I couldn't find any documentation on this.
XORing a master key (presumably a long term key) with data is a very dangerous idea. If any data key is leaked, then the master key may be easily calculated, thus leaking all keys. ($m$ for the master key, $d_x$ for all data keys) $$c_x = d_x \oplus m$$ then somehow $d_4$ is leaked $$m = d_4 \oplus c_4$$ $$d_x = c_x \oplus m$$ You'd be better off applying a block cipher (like AES) instead. One of the main properties of block ciphers is that given the plaintext and ciphertext, it is infeasible to generate the key. $$c_x = E_m(d_x)$$ then again $d_4$ is leaked (who keeps doing that..) yet $m$ is still hidden.
You have to be sure that blocks of data would have sufficient size such that equivalent key size remains secure. Also the key should only be used once. Once you have a secure PRG then you can employ a stream cipher like XOR encryption. This comes however with the disadvantage of having key size equal your data, and the key should be used once
Are you implementing this for cryptographic purpose ? If so, you should use True Random Number Generators (TRNGs) to generate your master key.Your key should have following properties:
- Statistical independence = For a given generated sequence of values, a particular value should not be more likely to appear next.
- Uniform distribution = All numbers are equally likely and none appear more frequently within the output.
- Unpredictability = An attacker should not be able to guess some or all of the values in a generated sequence.
If done right, XOR can be used to encrypt data. One way to do this, is to generate a pseudo-random key-stream using your master key and XOR the key-stream, which needs to be as long as the data, with the data.
The key-stream can be generated using a block-cipher like AES.
This is how AES-CTR (Counter) Mode works.