|
发表于 2024-12-15 03:07:18
|
显示全部楼层
湖北省武汉市
这是stl版本的,纯字节集的:
std::vector<unsigned char> endecode( const std::vector<unsigned char> & data, const std::vector<unsigned char> & key, char level, std::vector<unsigned char> rand )
{
if ( key.empty() ) return std::vector<unsigned char>();
std::vector<unsigned char> result( data.size(), 0 );
for ( size_t i = 0; i < data.size(); i++ ) {
result [ i ] = ( data [ i ] ^ key [ ( ( i + 1 ) % key.size() ) ] ) ^ rand [ ( i + 1 ) % level ];
}
return result;
}
std::vector<unsigned char> encode( const std::vector<unsigned char> & data, const std::vector<unsigned char> & key, char level ) {
if ( level == 0 ) level = 1;
auto len = data.size() - level;
if ( !len ) return std::vector<unsigned char>();
std::vector<unsigned char> _you( data.end() - len, data.end() );
std::vector<unsigned char> _zuo( data.begin(), data.begin() + level );
return endecode( _you, key, level, _zuo );
}
std::vector<unsigned char> decode( const std::vector<unsigned char> & data, const std::vector<unsigned char> & key, char level )
{
if( data.empty()) return std::vector<unsigned char>();
if ( level == 0 ) level = 1;
std::vector<unsigned char> random( level, 0 );
std::vector<unsigned char> result;
std::srand( static_cast< unsigned int >( std::time( nullptr ) ) );
for ( int i = 0; i < level; ++i ) {
random [ i ] = std::rand() % 256;
}
auto code = endecode( data, key, level, random );
if ( code.empty() ) return result;
result.insert( result.end(), random.begin(), random.end() );
result.insert( result.end(), code.begin(), code.end() );
return result;
}
int main()
{
std::vector<unsigned char> fff = { 'w','r','n','m','s',',','b' ,'!','\0' };
std::vector<unsigned char> keys = { 'k','e','y','s' };
auto de = decode( fff, keys, 3 );
auto en = encode( de, keys, 3 );
std::cout << en.data() << std::endl;
return 0;
} |
|