Path: blob/a-new-beginning/SharedDependencies/Sources/cryptopp/blowfish.cpp
2 views
// blowfish.cpp - originally written and placed in the public domain by Wei Dai12#include "pch.h"3#include "blowfish.h"4#include "misc.h"56NAMESPACE_BEGIN(CryptoPP)78void Blowfish::Base::UncheckedSetKey(const byte *key_string, unsigned int keylength, const NameValuePairs &)9{10AssertValidKeyLength(keylength);1112unsigned i, j=0, k;13word32 data, dspace[2] = {0, 0};1415std::memcpy(pbox, p_init, sizeof(p_init));16std::memcpy(sbox, s_init, sizeof(s_init));1718// Xor key string into encryption key vector19for (i=0 ; i<ROUNDS+2 ; ++i)20{21data = 0 ;22for (k=0 ; k<4 ; ++k )23data = (data << 8) | key_string[j++ % keylength];24pbox[i] ^= data;25}2627crypt_block(dspace, pbox);2829for (i=0; i<ROUNDS; i+=2)30crypt_block(pbox+i, pbox+i+2);3132crypt_block(pbox+ROUNDS, sbox);3334for (i=0; i<4*256-2; i+=2)35crypt_block(sbox+i, sbox+i+2);3637if (!IsForwardTransformation())38for (i=0; i<(ROUNDS+2)/2; i++)39std::swap(pbox[i], pbox[ROUNDS+1-i]);40}4142// this version is only used to make pbox and sbox43void Blowfish::Base::crypt_block(const word32 in[2], word32 out[2]) const44{45word32 left = in[0];46word32 right = in[1];4748const word32 *const s=sbox;49const word32 *p=pbox;5051left ^= p[0];5253for (unsigned i=0; i<ROUNDS/2; i++)54{55right ^= (((s[GETBYTE(left,3)] + s[256+GETBYTE(left,2)])56^ s[2*256+GETBYTE(left,1)]) + s[3*256+GETBYTE(left,0)])57^ p[2*i+1];5859left ^= (((s[GETBYTE(right,3)] + s[256+GETBYTE(right,2)])60^ s[2*256+GETBYTE(right,1)]) + s[3*256+GETBYTE(right,0)])61^ p[2*i+2];62}6364right ^= p[ROUNDS+1];6566out[0] = right;67out[1] = left;68}6970void Blowfish::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const71{72typedef BlockGetAndPut<word32, BigEndian> Block;7374word32 left, right;75Block::Get(inBlock)(left)(right);7677const word32 *const s=sbox;78const word32 *p=pbox;7980left ^= p[0];8182for (unsigned i=0; i<ROUNDS/2; i++)83{84right ^= (((s[GETBYTE(left,3)] + s[256+GETBYTE(left,2)])85^ s[2*256+GETBYTE(left,1)]) + s[3*256+GETBYTE(left,0)])86^ p[2*i+1];8788left ^= (((s[GETBYTE(right,3)] + s[256+GETBYTE(right,2)])89^ s[2*256+GETBYTE(right,1)]) + s[3*256+GETBYTE(right,0)])90^ p[2*i+2];91}9293right ^= p[ROUNDS+1];9495Block::Put(xorBlock, outBlock)(right)(left);96}9798NAMESPACE_END99100101