At first glance I wasn't sure what you're up to here (I'm still not to be honest) as:-
-
char(lpBuf[i])
is completely redundant - it's already a
char
- you're XORing your character with a value more than than 255 (0xFF)
- the cast to
int
is also redundant as you immediately cast back to a
char
Then I had a thought: As you say you're inexperienced. Are you using a crypto method (like RSA) which relies on exponentiation under modulus? If you are then you might think that ^ (the bitwise XOR operator) is actually exponentiation the way it is in a lot of other languages.
unsigned char initial_value = static_cast<unsigned char>( lpBuf[i] );
unsigned char value = initial_value;
for( int n = 2; n < 1230; ++n )
{
val *= initial_val;
}
unsigned mod_denominator = 15 * (36 + 1337) * (22 - 1);
lpBuf[i] = static_cast<char>( val % mod_denominator );
I might have still got this wrong... make sure you THOROUGHLY test any code you nick off me and understand why it works.
Even if that's what not you want then do yourself a favour or eight:
- Describe the algorithm you're trying to implement. If this is really something like RSA then it took me a while to work out what you're up to
- Better still use a standard implementation of a crypto algorithm. Don't do it yourself unless you're an expert and then why waste time doing it when other people have already done it and it's been reviewed?
- Break up complicated big expressions - there's no point in keeping it all on one line. I'd also move the loop into a different function as it's not clear what what's going on, I didn't bother here but probably should have done
- Know what the operators mean (you might already and I'm barking up the wrong tree) and understand operator precedence (the way I didn't when reading the code)
- Minimise casts. Compiler warnings are there for a reason! If you have to use casts use C++ style casts and NOT function style casts or C-style casts as they stick out like sore thumbs
- Use unsigned numbers for anyhing that acts on a stream of bytes or logical operations
- Don't use pointers, use
std::vector
- Don't used magic numbers, EVER. Had you called 1230 exponent (if I'm right) or bit_mask (if I'm wrong) it would have helped no end. And presumably that collection of constants at the end is four numbers because they mean something in the context of the algorithm so name them with their meaning. Don't comment it either, call them what they are
I hope this lot helps,
Ash
Edit to improve the whole XORing a bit. Move along, nothing to see here apart from my dead ego :-) Fixed a few other bollocks up as well.