void sapphire::initialize(unsigned char *key, unsigned char keysize) { // Key size may be up to 256 bytes. // Pass phrases may be used directly, with longer length // compensating for the low entropy expected in such keys. // Alternatively, shorter keys hashed from a pass phrase or // generated randomly may be used. For random keys, lengths // of from 4 to 16 bytes are recommended, depending on how // secure you want this to be. int i; unsigned char toswap, swaptemp, rsum; unsigned keypos; // If we have been given no key, assume the default hash setup. if (keysize < 1) { hash_init(); return; } // Start with cards all in order, one of each. for (i=0;i<256;i++) cards[i] = i; // Swap the card at each position with some other card. toswap = 0; keypos = 0; // Start with first byte of user key. rsum = 0; for (i=255;i>=0;i--) { toswap = keyrand(i, key, keysize, &rsum, &keypos); swaptemp = cards[i]; cards[i] = cards[toswap]; cards[toswap] = swaptemp; } // Initialize the indices and data dependencies. // Indices are set to different values instead of all 0 // to reduce what is known about the state of the cards // when the first byte is emitted. rotor = cards[1]; ratchet = cards[3]; avalanche = cards[5]; last_plain = cards[7]; last_cipher = cards[rsum]; toswap = swaptemp = rsum = 0; keypos = 0; }
SapphireBase::SapphireBase(const byte *key, unsigned int keysize) : cards(256) { assert(keysize < 256); // Key size may be up to 256 bytes. // Pass phrases may be used directly, with longer length // compensating for the low entropy expected in such keys. // Alternatively, shorter keys hashed from a pass phrase or // generated randomly may be used. For random keys, lengths // of from 4 to 16 bytes are recommended, depending on how // secure you want this to be. int i; byte rsum; unsigned keypos; // Start with cards all in order, one of each. for (i=0;i<256;i++) cards[i] = i; // Swap the card at each position with some other card. keypos = 0; // Start with first byte of user key. rsum = 0; for (i=255;i;i--) std::swap(cards[i], cards[keyrand(i, key, keysize, &rsum, &keypos)]); // Initialize the indices and data dependencies. // Indices are set to different values instead of all 0 // to reduce what is known about the state of the cards // when the first byte is emitted. rotor = cards[1]; ratchet = cards[3]; avalanche = cards[5]; last_plain = cards[7]; last_cipher = cards[rsum]; rsum = 0; keypos = 0; }