本文整理汇总了C++中cipher函数的典型用法代码示例。如果您正苦于以下问题:C++ cipher函数的具体用法?C++ cipher怎么用?C++ cipher使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了cipher函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: ValidateRC2
bool ValidateRC2()
{
cout << "\nRC2 validation suite running...\n\n";
FileSource valdata("rc2val.dat", true, new HexDecoder);
HexEncoder output(new FileSink(cout));
SecByteBlock plain(RC2Encryption::BLOCKSIZE), cipher(RC2Encryption::BLOCKSIZE), out(RC2Encryption::BLOCKSIZE), outplain(RC2Encryption::BLOCKSIZE);
SecByteBlock key(128);
bool pass=true, fail;
while (valdata.MaxRetrievable())
{
byte keyLen, effectiveLen;
valdata.Get(keyLen);
valdata.Get(effectiveLen);
valdata.Get(key, keyLen);
valdata.Get(plain, RC2Encryption::BLOCKSIZE);
valdata.Get(cipher, RC2Encryption::BLOCKSIZE);
apbt transE(new RC2Encryption(key, keyLen, effectiveLen));
transE->ProcessBlock(plain, out);
fail = memcmp(out, cipher, RC2Encryption::BLOCKSIZE) != 0;
apbt transD(new RC2Decryption(key, keyLen, effectiveLen));
transD->ProcessBlock(out, outplain);
fail=fail || memcmp(outplain, plain, RC2Encryption::BLOCKSIZE);
pass = pass && !fail;
cout << (fail ? "FAILED " : "passed ");
output.Put(key, keyLen);
cout << " ";
output.Put(outplain, RC2Encryption::BLOCKSIZE);
cout << " ";
output.Put(out, RC2Encryption::BLOCKSIZE);
cout << endl;
}
return pass;
}
示例2: ValidateRC2
bool ValidateRC2()
{
std::cout << "\nRC2 validation suite running...\n\n";
FileSource valdata("TestData/rc2val.dat", true, new HexDecoder);
HexEncoder output(new FileSink(std::cout));
SecByteBlock plain(RC2Encryption::BLOCKSIZE), cipher(RC2Encryption::BLOCKSIZE), out(RC2Encryption::BLOCKSIZE), outplain(RC2Encryption::BLOCKSIZE);
SecByteBlock key(128);
bool pass=true, fail;
while (valdata.MaxRetrievable())
{
byte keyLen, effectiveLen;
valdata.Get(keyLen);
valdata.Get(effectiveLen);
valdata.Get(key, keyLen);
valdata.Get(plain, RC2Encryption::BLOCKSIZE);
valdata.Get(cipher, RC2Encryption::BLOCKSIZE);
auto_ptr<BlockTransformation> transE(new RC2Encryption(key, keyLen, effectiveLen));
transE->ProcessBlock(plain, out);
fail = !VerifyBufsEqual(out, cipher, RC2Encryption::BLOCKSIZE);
auto_ptr<BlockTransformation> transD(new RC2Decryption(key, keyLen, effectiveLen));
transD->ProcessBlock(out, outplain);
fail=fail || !VerifyBufsEqual(outplain, plain, RC2Encryption::BLOCKSIZE);
pass = pass && !fail;
std::cout << (fail ? "FAILED " : "passed ");
output.Put(key, keyLen);
std::cout << " ";
output.Put(outplain, RC2Encryption::BLOCKSIZE);
std::cout << " ";
output.Put(out, RC2Encryption::BLOCKSIZE);
std::cout << std::endl;
}
return pass;
}
示例3: main
int main(int argc, char* argv[])
{
//stops the program if there are no command line arguments
if (argc != 2)
{
printf("You must enter an argument.\n");
return 1;
}
else
{
//key is changed to integer
int k = atoi(argv[1]);
printf("Enter a string you would like to encrypt with Caesar's cipher: \n");
//gets the string from the user that we would like to encrypt
char* s = GetString();
char cipheredNum;
int result;
//loops through each char of the string
for (int i = 0, n = strlen(s); i < n; i++)
{
//if the char is a capital or lowercase letter
if (capital(s[i]) == 1 || lowerCase(s[i]) == 1)
{
//change to alphanumeric value, run the cipher, then change back to ascii
int alphaNum = toAlpha(s[i]);
cipheredNum = cipher(alphaNum, k);
result = toAscii(cipheredNum);
}
//if the char is neither capital or lowercase, it stays the same
else
result = s[i];
//prints the ciphered char before moving on to next char
printf("%c", result);
}
printf("\n");
return 0;
}
}
示例4: decrypt_input
static int decrypt_input()
{
Util::CipherInfo ci;
ci.name = opt_decrypt;
ci.password = opt_password;
ci.encrypt = false;
ci.aead = is_aead(ci);
Util::Cipher cipher(ci);
{ // restore IV
std::string iv;
auto params= cipher.get_cipher_params();
ci.iv.resize(params.ivsize);
if (ci.aead) {
opt_read_size += params.tag_size;
}
std::ifstream read_iv(opt_iv, std::ifstream::in | std::ifstream::binary);
read_iv.read(&ci.iv[0], ci.iv.size());
}
cipher.accept();
process_with(cipher);
return 0;
}
示例5: Q_D
bool Exporter::write(const SecureByteArray &data, const SecureString &pwd)
{
Q_D(Exporter);
Q_ASSERT((data.size() % Crypter::AESBlockSize) == 0);
QByteArray salt = Crypter::generateSalt();
SecureByteArray iv;
SecureByteArray key;
Crypter::makeKeyAndIVFromPassword(pwd.toUtf8(), salt, key, iv);
CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption enc;
enc.SetKeyWithIV(reinterpret_cast<const byte*>(key.constData()), key.size(), reinterpret_cast<const byte*>(iv.constData()));
const int cipherSize = data.size();
QByteArray cipher(cipherSize, static_cast<char>(0));
CryptoPP::ArraySource s(
reinterpret_cast<const byte*>(data.constData()), data.size(),
true,
new CryptoPP::StreamTransformationFilter(
enc,
new CryptoPP::ArraySink(reinterpret_cast<byte*>(cipher.data()), cipher.size()),
CryptoPP::StreamTransformationFilter::NO_PADDING
)
);
Q_UNUSED(s); // just to please the compiler
QFile file(d->filename);
bool opened = file.open(QIODevice::WriteOnly);
if (!opened)
return false;
QByteArray block = salt + cipher;
file.write(PemPreamble.toUtf8());
file.write("\n");
const SecureByteArray &b64 = block.toBase64();
for (int i = 0; i < b64.size(); i += 64) {
file.write(b64.mid(i, qMin(64, b64.size() - i)));
file.write("\n");
}
file.write(PemEpilog.toUtf8());
file.write("\n");
file.close();
return true;
}
示例6: while
QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
{
QCA::Initializer init;
QByteArray temp = cipherText;
// do padding ourselves
if (direction) {
while ((temp.length() % 8) != 0)
temp.append('\0');
}
else {
// ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input
if ((temp.length() % 12) != 0)
return cipherText;
temp = b64ToByte(temp);
while ((temp.length() % 8) != 0)
temp.append('\0');
}
QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
temp2 += cipher.final().toByteArray();
if (!cipher.ok())
return cipherText;
if (direction) {
// Sanity check
if ((temp2.length() % 8) != 0)
return cipherText;
temp2 = byteToB64(temp2);
}
return temp2;
}
示例7: EncContent
inline void EncContent(std::string& encryptedPackage, const std::string& org, const CipherParam& param, const std::string& key, const std::string& salt)
{
uint64_t orgSize = org.size();
const size_t blockSize = 4096;
std::string data = org;
data.resize(RoundUp(data.size(), size_t(16)));
#ifdef SAME_KEY
data[data.size() - 2] = 0x4b; // QQQ remove this
data[data.size() - 1] = 0x6a;
#endif
encryptedPackage.reserve(data.size() + 8);
encryptedPackage.resize(8);
cybozu::Set64bitAsLE(&encryptedPackage[0], orgSize);
const size_t n = (data.size() + blockSize - 1) / blockSize;
for (size_t i = 0; i < n; i++) {
const size_t len = (i < n - 1) ? blockSize : (data.size() % blockSize);
std::string blockKey(4, 0);
cybozu::Set32bitAsLE(&blockKey[0], static_cast<uint32_t>(i));
const std::string iv = generateKey(param, salt, blockKey);
encryptedPackage.append(cipher(param.cipherName, data.c_str() + i * blockSize, len, key, iv, cybozu::crypto::Cipher::Encoding));
}
}
示例8: decrypt
/* Decrypt stdin to stdout, and exit */
int
decrypt()
{
char buf[8*1024], *cp;
int n;
while ((n = fread(buf, 1, sizeof buf, stdin)) > 0) {
if ((cp = cipher(buf, n, 0)) == NULL) {
fprintf(stderr, "ermt: Error decoding input; see daemon.err syslog\n");
exit(1);
}
fwrite(cp, 1, n, stdout);
}
if (ferror(stdin)) {
perror("ermt: stdin: read");
exit(1);
}
if (fflush(stdout)) {
perror("ermt: stdout: write");
exit(1);
}
exit(0);
}
示例9: LLSD
LLSD LLInventoryItem::asLLSD() const
{
LLSD sd = LLSD();
sd[INV_ITEM_ID_LABEL] = mUUID;
sd[INV_PARENT_ID_LABEL] = mParentUUID;
sd[INV_PERMISSIONS_LABEL] = ll_create_sd_from_permissions(mPermissions);
U32 mask = mPermissions.getMaskBase();
if(((mask & PERM_ITEM_UNRESTRICTED) == PERM_ITEM_UNRESTRICTED)
|| (mAssetUUID.isNull()))
{
sd[INV_ASSET_ID_LABEL] = mAssetUUID;
}
else
{
// *TODO: get rid of this. Phoenix 2008-01-30
LLUUID shadow_id(mAssetUUID);
LLXORCipher cipher(MAGIC_ID.mData, UUID_BYTES);
cipher.encrypt(shadow_id.mData, UUID_BYTES);
sd[INV_SHADOW_ID_LABEL] = shadow_id;
}
sd[INV_ASSET_TYPE_LABEL] = LLAssetType::lookup(mType);
sd[INV_INVENTORY_TYPE_LABEL] = mInventoryType;
const char* inv_type_str = LLInventoryType::lookup(mInventoryType);
if(inv_type_str)
{
sd[INV_INVENTORY_TYPE_LABEL] = inv_type_str;
}
//sd[INV_FLAGS_LABEL] = (S32)mFlags;
sd[INV_FLAGS_LABEL] = ll_sd_from_U32(mFlags);
sd[INV_SALE_INFO_LABEL] = mSaleInfo;
sd[INV_NAME_LABEL] = mName;
sd[INV_DESC_LABEL] = mDescription;
sd[INV_CREATION_DATE_LABEL] = (S32) mCreationDate;
return sd;
}
示例10: size
bool Packet::dearmor(const void *key)
{
unsigned char mangledKey[32];
unsigned char macKey[32];
unsigned char mac[16];
const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
unsigned int cs = cipher();
if ((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)||(cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)) {
_salsa20MangleKey((const unsigned char *)key,mangledKey);
Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8)/*,ZT_PROTO_SALSA20_ROUNDS*/);
s20.encrypt12(ZERO_KEY,macKey,sizeof(macKey));
Poly1305::compute(mac,payload,payloadLen,macKey);
if (!Utils::secureEq(mac,field(ZT_PACKET_IDX_MAC,8),8))
return false;
if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
s20.decrypt12(payload,payload,payloadLen);
return true;
} else return false; // unrecognized cipher suite
}
示例11: run
std::vector<Test::Result> run() override
{
Test::Result result("Package transform");
std::unique_ptr<Botan::BlockCipher> cipher(Botan::BlockCipher::create("AES-128"));
std::vector<uint8_t> input = unlock(Test::rng().random_vec(Test::rng().next_byte()));
std::vector<uint8_t> output(input.size() + cipher->block_size());
// aont_package owns/deletes the passed cipher object, kind of a bogus API
Botan::aont_package(Test::rng(),
cipher->clone(),
input.data(), input.size(),
output.data());
std::vector<uint8_t> decoded(output.size() - cipher->block_size());
Botan::aont_unpackage(cipher->clone(),
output.data(), output.size(),
decoded.data());
result.test_eq("Package transform is reversible", decoded, input);
output[0] ^= 1;
Botan::aont_unpackage(cipher->clone(),
output.data(), output.size(),
decoded.data());
result.test_ne("Bitflip breaks package transform", decoded, input);
output[0] ^= 1;
Botan::aont_unpackage(cipher->clone(),
output.data(), output.size(),
decoded.data());
result.test_eq("Package transform is still reversible", decoded, input);
// More tests including KATs would be useful for these functions
return std::vector<Test::Result>{result};
}
示例12: while
// virtual
BOOL LLInventoryItem::importLegacyStream(std::istream& input_stream)
{
// *NOTE: Changing the buffer size will require changing the scanf
// calls below.
char buffer[MAX_STRING]; /* Flawfinder: ignore */
char keyword[MAX_STRING]; /* Flawfinder: ignore */
char valuestr[MAX_STRING]; /* Flawfinder: ignore */
char junk[MAX_STRING]; /* Flawfinder: ignore */
BOOL success = TRUE;
keyword[0] = '\0';
valuestr[0] = '\0';
mInventoryType = LLInventoryType::IT_NONE;
mAssetUUID.setNull();
while(success && input_stream.good())
{
input_stream.getline(buffer, MAX_STRING);
sscanf( /* Flawfinder: ignore */
buffer,
" %254s %254s",
keyword, valuestr);
if(0 == strcmp("{",keyword))
{
continue;
}
if(0 == strcmp("}", keyword))
{
break;
}
else if(0 == strcmp("item_id", keyword))
{
mUUID.set(valuestr);
}
else if(0 == strcmp("parent_id", keyword))
{
mParentUUID.set(valuestr);
}
else if(0 == strcmp("permissions", keyword))
{
success = mPermissions.importLegacyStream(input_stream);
}
else if(0 == strcmp("sale_info", keyword))
{
// Sale info used to contain next owner perm. It is now in
// the permissions. Thus, we read that out, and fix legacy
// objects. It's possible this op would fail, but it
// should pick up the vast majority of the tasks.
BOOL has_perm_mask = FALSE;
U32 perm_mask = 0;
success = mSaleInfo.importLegacyStream(input_stream, has_perm_mask, perm_mask);
if(has_perm_mask)
{
if(perm_mask == PERM_NONE)
{
perm_mask = mPermissions.getMaskOwner();
}
// fair use fix.
if(!(perm_mask & PERM_COPY))
{
perm_mask |= PERM_TRANSFER;
}
mPermissions.setMaskNext(perm_mask);
}
}
else if(0 == strcmp("shadow_id", keyword))
{
mAssetUUID.set(valuestr);
LLXORCipher cipher(MAGIC_ID.mData, UUID_BYTES);
cipher.decrypt(mAssetUUID.mData, UUID_BYTES);
}
else if(0 == strcmp("asset_id", keyword))
{
mAssetUUID.set(valuestr);
}
else if(0 == strcmp("type", keyword))
{
mType = LLAssetType::lookup(valuestr);
}
else if(0 == strcmp("inv_type", keyword))
{
mInventoryType = LLInventoryType::lookup(std::string(valuestr));
}
else if(0 == strcmp("flags", keyword))
{
sscanf(valuestr, "%x", &mFlags);
}
else if(0 == strcmp("name", keyword))
{
//strcpy(valuestr, buffer + strlen(keyword) + 3);
// *NOTE: Not ANSI C, but widely supported.
sscanf( /* Flawfinder: ignore */
buffer,
" %254s%254[\t]%254[^|]",
keyword, junk, valuestr);
// IW: sscanf chokes and puts | in valuestr if there's no name
if (valuestr[0] == '|')
{
//.........这里部分代码省略.........
示例13: cipher
Key_Length_Specification ECB_Mode::key_spec() const
{
return cipher().key_spec();
}
示例14: run_one_test
Test::Result run_one_test(const std::string& algo, const VarMap& vars) override
{
const std::vector<uint8_t> key = get_req_bin(vars, "Key");
const std::vector<uint8_t> expected = get_req_bin(vars, "Out");
const std::vector<uint8_t> nonce = get_opt_bin(vars, "Nonce");
const size_t seek = get_opt_sz(vars, "Seek", 0);
std::vector<uint8_t> input = get_opt_bin(vars, "In");
if(input.empty())
input.resize(expected.size());
Test::Result result(algo);
const std::vector<std::string> providers =
provider_filter(Botan::StreamCipher::providers(algo));
if(providers.empty())
{
result.note_missing("block cipher " + algo);
return result;
}
for(auto&& provider_ask : providers)
{
std::unique_ptr<Botan::StreamCipher> cipher(Botan::StreamCipher::create(algo, provider_ask));
if(!cipher)
{
result.test_failure("Stream " + algo + " supported by " + provider_ask + " but not found");
continue;
}
const std::string provider(cipher->provider());
result.test_is_nonempty("provider", provider);
result.test_eq(provider, cipher->name(), algo);
cipher->set_key(key);
if(nonce.size())
{
if(!cipher->valid_iv_length(nonce.size()))
throw Test_Error("Invalid nonce for " + algo);
cipher->set_iv(nonce.data(), nonce.size());
}
else
{
/*
* If no nonce was set then implicitly the cipher is using a
* null/empty nonce. Call set_iv with such a nonce to make sure
* set_iv accepts it.
*/
if(!cipher->valid_iv_length(0))
throw Test_Error("Stream cipher " + algo + " requires nonce but none provided");
cipher->set_iv(nullptr, 0);
}
if (seek != 0)
cipher->seek(seek);
// Test that clone works and does not affect parent object
std::unique_ptr<Botan::StreamCipher> clone(cipher->clone());
result.confirm("Clone has different pointer", cipher.get() != clone.get());
result.test_eq("Clone has same name", cipher->name(), clone->name());
clone->set_key(Test::rng().random_vec(cipher->maximum_keylength()));
std::vector<uint8_t> buf = input;
cipher->encrypt(buf);
cipher->clear();
result.test_eq(provider, "encrypt", buf, expected);
}
return result;
}
示例15: blacklist_data_stream
void FSWSAssetBlacklist::loadBlacklist()
{
if (gDirUtilp->fileExists(mBlacklistFileName))
{
llifstream blacklist_data_stream(mBlacklistFileName);
if (blacklist_data_stream.is_open())
{
LLSD data;
if (LLSDSerialize::fromXML(data, blacklist_data_stream) >= 1)
{
for (LLSD::map_const_iterator itr = data.beginMap(); itr != data.endMap(); ++itr)
{
LLUUID uid = LLUUID(itr->first);
LLXORCipher cipher(MAGIC_ID.mData, UUID_BYTES);
cipher.decrypt(uid.mData, UUID_BYTES);
LLSD data = itr->second;
if (uid.isNull())
{
continue;
}
LLAssetType::EType type = S32toAssetType(data["asset_type"].asInteger());
if (type == LLAssetType::AT_NONE)
{
continue;
}
addNewItemToBlacklistData(uid, data, false);
}
}
}
blacklist_data_stream.close();
}
else
{
// Try to import old blacklist data from Phoenix
std::string old_file = gDirUtilp->getOSUserDir() + gDirUtilp->getDirDelimiter() + "SecondLife" + gDirUtilp->getDirDelimiter() + "user_settings" + gDirUtilp->getDirDelimiter() + "floater_blist_settings.xml";
if (gDirUtilp->fileExists(old_file))
{
LLSD datallsd;
llifstream oldfile;
oldfile.open(old_file.c_str());
if (oldfile.is_open())
{
LLSDSerialize::fromXMLDocument(datallsd, oldfile);
for (LLSD::map_const_iterator itr = datallsd.beginMap(); itr != datallsd.endMap(); ++itr)
{
LLUUID uid = LLUUID(itr->first);
LLSD data = itr->second;
if (uid.isNull() || !data.has("entry_name") || !data.has("entry_type") || !data.has("entry_date"))
{
continue;
}
LLAssetType::EType type = S32toAssetType(data["entry_type"].asInteger());
LLSD newdata;
newdata["asset_name"] = "[PHOENIX] " + data["entry_name"].asString();
newdata["asset_type"] = type;
newdata["asset_date"] = data["entry_date"].asString();
//if (!data["ID_hashed"].asBoolean())
//{
// uid = LLUUID::generateNewID(uid.asString() + "hash");
//}
addNewItemToBlacklistData(uid, newdata, false);
}
}
oldfile.close();
saveBlacklist();
llinfos << "Using old Phoenix file: " << old_file << llendl;
}
else
{
llinfos << "No Settings file found." << old_file << llendl;
}
}
}