本文整理汇总了C++中SecByteBlock类的典型用法代码示例。如果您正苦于以下问题:C++ SecByteBlock类的具体用法?C++ SecByteBlock怎么用?C++ SecByteBlock使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SecByteBlock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: AES_CTR_Encrypt
void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile)
{
SecByteBlock key = HexDecodeString(hexKey);
SecByteBlock iv = HexDecodeString(hexIV);
CTR_Mode<AES>::Encryption aes(key, key.size(), iv);
FileSource(infile, true, new StreamTransformationFilter(aes, new FileSink(outfile)));
}
示例2: PEM_IsEncrypted
bool PEM_IsEncrypted(SecByteBlock& sb)
{
SecByteBlock::iterator it = search(sb.begin(), sb.end(), SBB_PROC_TYPE.begin(), SBB_PROC_TYPE.end());
if (it == sb.end()) return false;
it = search(it + SBB_PROC_TYPE.size(), sb.end(), SBB_ENCRYPTED.begin(), SBB_ENCRYPTED.end());
return it != sb.end();
}
示例3: encrypt
string RNEncryptor::encrypt(string plaintext, string password, RNCryptorSchema schemaVersion)
{
this->configureSettings(schemaVersion);
RNCryptorPayloadComponents components;
components.schema = (char)schemaVersion;
components.options = (char)this->options;
components.salt = this->generateSalt();
components.hmacSalt = this->generateSalt();
components.iv = this->generateIv(this->ivLength);
SecByteBlock key = this->generateKey(components.salt, password);
switch (this->aesMode) {
case MODE_CTR: {
CTR_Mode<AES>::Encryption encryptor;
encryptor.SetKeyWithIV((const byte *)key.data(), key.size(), (const byte *)components.iv.data());
StringSource(plaintext, true,
// StreamTransformationFilter adds padding as required.
new StreamTransformationFilter(encryptor,
new StringSink(components.ciphertext)
)
);
break;
}
case MODE_CBC: {
CBC_Mode<AES>::Encryption encryptor;
encryptor.SetKeyWithIV(key.BytePtr(), key.size(), (const byte *)components.iv.data());
StringSource(plaintext, true,
// StreamTransformationFilter adds padding as required.
new StreamTransformationFilter(encryptor,
new StringSink(components.ciphertext)
)
);
break;
}
}
stringstream binaryData;
binaryData << components.schema;
binaryData << components.options;
binaryData << components.salt;
binaryData << components.hmacSalt;
binaryData << components.iv;
binaryData << components.ciphertext;
std::cout << "Hex encoded: " << this->hex_encode(binaryData.str()) << std::endl;
binaryData << this->generateHmac(components, password);
return this->base64_encode(binaryData.str());
}
示例4: BERDecodePoint
ECP::Point ECP::BERDecodePoint(BufferedTransformation &bt) const
{
SecByteBlock str;
BERDecodeOctetString(bt, str);
Point P;
if (!DecodePoint(P, str, str.size()))
BERDecodeError();
return P;
}
示例5: SecByteBlockToString
std::string Converter::SecByteBlockToString(SecByteBlock data){
Integer a;
a.Decode(data.BytePtr(), data.SizeInBytes());
//cout<< "ze secbyteblock do integera: "<<a<<endl;
std::ostrstream oss;
oss << std::hex << a;
std::string s(oss.str());
s = s.substr(0, 2*data.SizeInBytes()+1); //Do zapamiêtania. d³ugoœæ stringa z s wynosi 2*d³ugoœæ w bytach plus 1.
return s;
}
示例6: PEM_StripEncapsulatedBoundary
void PEM_StripEncapsulatedBoundary(BufferedTransformation& bt, const SecByteBlock& pre, const SecByteBlock& post)
{
ByteQueue temp;
SecByteBlock::const_iterator it;
int n = 1, prePos = -1, postPos = -1;
while(bt.AnyRetrievable() && n++)
{
SecByteBlock line, unused;
PEM_ReadLine(bt, line, unused);
// The write associated with an empty line must to occur. Otherwise, we loose the CR or LF
// in an ecrypted private key between the control fields and the encapsulated text.
//if(line.empty())
// continue;
it = Search(line, pre);
if(it != line.end())
{
prePos = n;
continue;
}
it = Search(line, post);
if(it != line.end())
{
postPos = n;
continue;
}
PEM_WriteLine(temp, line);
}
if(prePos == -1)
{
string msg = "PEM_StripEncapsulatedBoundary: '";
msg += string((char*)pre.data(), pre.size()) + "' not found";
throw InvalidDataFormat(msg);
}
if(postPos == -1)
{
string msg = "PEM_StripEncapsulatedBoundary: '";
msg += string((char*)post.data(), post.size()) + "' not found";
throw InvalidDataFormat(msg);
}
if(prePos > postPos)
throw InvalidDataFormat("PEM_StripEncapsulatedBoundary: header boundary follows footer boundary");
temp.TransferTo(bt);
}
示例7: encryptFile
bool encryptFile(string filename, SecByteBlock key, byte* iv){
ifstream file;
file.open(filename);
if(file.is_open()){
string line;
ofstream encFile;
encFile.open("encText.txt", ios::app);
CBC_Mode<AES>::Encryption enc;
enc.SetKeyWithIV(key, key.size(), iv);
while(getline(file, line)){
string cipher;
//cout << line << endl;
StringSource ss(line, true, new StreamTransformationFilter(enc, new StringSink(cipher)));
if(encFile.is_open()){
encFile.write(cipher.c_str(), cipher.size());
encFile << '\r\n';
}
else
cout << "couldn't write" << endl;
//cout << cipher << endl;
}
cout << "finished encrypting" << endl;
encFile.close();
file.close();
return true;
}
else{
cout << "Unable to open file." << endl;
return false;
}
}
示例8: decodeSecByteBlock
SecByteBlock Converter::encodeSecByteBlockWithLength(Integer key, int length)
{
//int length = key.MinEncodedSize();
byte * byteX;
key.Encode(byteX, length);
SecByteBlock pubKeyA;
pubKeyA.Assign(byteX, length);
std::cout<<"Key: " << key <<std::endl;
std::cout<<"Decoded: " << decodeSecByteBlock(pubKeyA) <<std::endl;
//check
if (key != decodeSecByteBlock(pubKeyA))
std::cout << "Error while encoding Integer to SecByteBlock" << std::endl;
return pubKeyA;
}
示例9: InvalidArgument
void InvertibleESIGNFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs ¶m)
{
int modulusSize = 1023*2;
param.GetIntValue("ModulusSize", modulusSize) || param.GetIntValue("KeySize", modulusSize);
if (modulusSize < 24)
throw InvalidArgument("InvertibleESIGNFunction: specified modulus size is too small");
if (modulusSize % 3 != 0)
throw InvalidArgument("InvertibleESIGNFunction: modulus size must be divisible by 3");
m_e = param.GetValueWithDefault("PublicExponent", Integer(32));
if (m_e < 8)
throw InvalidArgument("InvertibleESIGNFunction: public exponents less than 8 may not be secure");
// VC70 workaround: putting these after primeParam causes overlapped stack allocation
ConstByteArrayParameter seedParam;
SecByteBlock seed;
const Integer minP = Integer(204) << (modulusSize/3-8);
const Integer maxP = Integer::Power2(modulusSize/3)-1;
AlgorithmParameters primeParam = MakeParameters("Min", minP)("Max", maxP)("RandomNumberType", Integer::PRIME);
if (param.GetValue("Seed", seedParam))
{
seed.resize(seedParam.size() + 4);
memcpy(seed + 4, seedParam.begin(), seedParam.size());
PutWord(false, BIG_ENDIAN_ORDER, seed, (word32)0);
m_p.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("Seed", ConstByteArrayParameter(seed))));
PutWord(false, BIG_ENDIAN_ORDER, seed, (word32)1);
m_q.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("Seed", ConstByteArrayParameter(seed))));
}
else
{
m_p.GenerateRandom(rng, primeParam);
m_q.GenerateRandom(rng, primeParam);
}
m_n = m_p * m_p * m_q;
CRYPTOPP_ASSERT(m_n.BitCount() == (unsigned int)modulusSize);
}
示例10: extension
void
CertificateExtension::decode(CryptoPP::BufferedTransformation& in)
{
using namespace CryptoPP;
// Extension ::= SEQUENCE {
// extnID OBJECT IDENTIFIER,
// critical BOOLEAN DEFAULT FALSE,
// extnValue OCTET STRING }
BERSequenceDecoder extension(in);
{
m_extensionId.decode(extension);
BERDecodeUnsigned(extension, m_isCritical, BOOLEAN);
// the extra copy operation can be optimized, but not trivial,
// since the length is not known in advance
SecByteBlock tmpBlock;
BERDecodeOctetString(extension, tmpBlock);
m_extensionValue.assign(tmpBlock.begin(), tmpBlock.end());
}
extension.MessageEnd();
}
示例11: decryptFile
bool decryptFile(string filename, SecByteBlock key, byte* iv){
ifstream file;
file.open(filename);
if(file.is_open()){
string line;
CBC_Mode<AES>::Decryption dec;
dec.SetKeyWithIV(key, key.size(), iv);
while(getline(file, line)){
string plain;
//cout << line << endl;
StringSource ss(line, true, new StreamTransformationFilter(dec, new StringSink(plain)));
//cout << plain << endl;
}
file.close();
return true;
}
else{
cout << "Unable to open file." << endl;
return false;
}
}
示例12: seq
void DL_PrivateKey_EC<EC>::BERDecodeKey2(BufferedTransformation &bt, bool parametersPresent, unsigned int size)
{
BERSequenceDecoder seq(bt);
word32 version;
BERDecodeUnsigned<word32>(seq, version, INTEGER, 1, 1); // check version
BERGeneralDecoder dec(seq, OCTET_STRING);
if (!dec.IsDefiniteLength())
BERDecodeError();
Integer x;
x.Decode(dec, dec.RemainingLength());
dec.MessageEnd();
if (!parametersPresent && seq.PeekByte() != (CONTEXT_SPECIFIC | CONSTRUCTED | 0))
BERDecodeError();
if (!seq.EndReached() && seq.PeekByte() == (CONTEXT_SPECIFIC | CONSTRUCTED | 0))
{
BERGeneralDecoder parameters(seq, CONTEXT_SPECIFIC | CONSTRUCTED | 0);
AccessGroupParameters().BERDecode(parameters);
parameters.MessageEnd();
}
if (!seq.EndReached())
{
// skip over the public element
SecByteBlock subjectPublicKey;
unsigned int unusedBits;
BERGeneralDecoder publicKey(seq, CONTEXT_SPECIFIC | CONSTRUCTED | 1);
BERDecodeBitString(publicKey, subjectPublicKey, unusedBits);
publicKey.MessageEnd();
Element Q;
if (!(unusedBits == 0 && GetGroupParameters().GetCurve().DecodePoint(Q, subjectPublicKey, subjectPublicKey.size())))
BERDecodeError();
}
seq.MessageEnd();
SetPrivateExponent(x);
}
示例13: main
int main()
{
using namespace CryptoPP;
AutoSeededRandomPool rng;
DH dhA; //< Diffie-Hellman structure
DH2 dh2A(dhA); //< Diffie-Hellman structure
SecByteBlock sprivA; //< static private key
SecByteBlock spubA; //< static public key
SecByteBlock eprivA; //< ephemeral private key
SecByteBlock epubA; //< ephemeral public key
SecByteBlock sharedA; //< shared key
DH dhB; //< Diffie-Hellman structure
DH2 dh2B(dhA); //< Diffie-Hellman structure
SecByteBlock sprivB; //< static private key
SecByteBlock spubB; //< static public key
SecByteBlock eprivB; //< ephemeral private key
SecByteBlock epubB; //< ephemeral public key
SecByteBlock sharedB; //< shared key
std::cout << "Initializing DH parameters" << std::endl;;
dhA.AccessCryptoParameters().GenerateRandomWithKeySize(rng,1024);
dhB.AccessCryptoParameters().GenerateRandomWithKeySize(rng,1024);
std::cout << "Generating Keys" << std::endl;;
sprivA = SecByteBlock( dh2A.StaticPrivateKeyLength() );
spubA = SecByteBlock( dh2A.StaticPublicKeyLength() );
eprivA = SecByteBlock( dh2A.EphemeralPrivateKeyLength() );
epubA = SecByteBlock( dh2A.EphemeralPublicKeyLength() );
dh2A.GenerateStaticKeyPair(rng,sprivA,spubA);
dh2A.GenerateEphemeralKeyPair(rng,eprivA, epubA);
sharedA= SecByteBlock( dh2A.AgreedValueLength() );
sprivB = SecByteBlock( dh2B.StaticPrivateKeyLength() );
spubB = SecByteBlock( dh2B.StaticPublicKeyLength() );
eprivB = SecByteBlock( dh2B.EphemeralPrivateKeyLength() );
epubB = SecByteBlock( dh2B.EphemeralPublicKeyLength() );
dh2B.GenerateStaticKeyPair(rng,sprivB,spubB);
dh2B.GenerateEphemeralKeyPair(rng,eprivB, epubB);
sharedB= SecByteBlock( dh2B.AgreedValueLength() );
if(!dh2A.Agree(sharedA, sprivA, eprivA, spubB, epubB) )
std::cerr << "A failed to agree " << std::endl;
if(!dh2B.Agree(sharedB, sprivB, eprivB, spubA, epubA) )
std::cerr << "B failed to agree " << std::endl;
Integer sharedAOut, sharedBOut;
sharedAOut.Decode(sharedA.BytePtr(), sharedA.SizeInBytes());
sharedBOut.Decode(sharedB.BytePtr(), sharedB.SizeInBytes());
std::cout << "shared secret:"
<< "\n A: " << std::hex << sharedAOut
<< "\n B: " << std::hex << sharedBOut
<< std::endl;
}
示例14: main
//.........这里部分代码省略.........
unlink(aes_file_name);
delete [] aes_file_name;
fclose(mp3_file);
exit(-1);
}
fseek(mp3_file, -4, SEEK_CUR);
// Generate an IV (with no FFs)
srand((unsigned)time(NULL));
for (int i = 0; i < 16; ++i) {
do { iv_buf[i] = rand(); } while (iv_buf[i] == 0xff);
}
// Write the DoRM box
DoRM_Box dormBox;
memcpy(dormBox.dorm, "DoRM", 4);
memset(dormBox.version, 0, 2);
memset(dormBox.reserved, 0, 2);
size_t dormBoxLen = sizeof(DoRM_Box) - 10;
dormBox.length[3] = (dormBoxLen & 0x0000007f);
dormBox.length[2] = (dormBoxLen & 0x00003f80) >> 7;
dormBox.length[1] = (dormBoxLen & 0x001fc000) >> 14;
dormBox.length[0] = (dormBoxLen & 0x0fe00000) >> 21;
unsigned dormProtId = 0x010000E0; // 0xE0000001 in big endian
memcpy(dormBox.prot_id, &dormProtId, 4);
//memset(dormBox.cid, 0, 16); // cid is 0 for now
for (int i = 0; i < 16; ++i) {
dormBox.cid[i] = (hex2bin(str_cid[i * 2 + 0]) << 4) |
(hex2bin(str_cid[i * 2 + 1]));
}
memcpy(dormBox.iv, iv_buf, 16);
fwrite(&dormBox, sizeof(DoRM_Box), 1, aes_file);
}
// Instantiate AES
SecByteBlock key = HexDecodeString(str_key);
SecByteBlock iv(iv_buf, 16);
OFB_Mode<AES>::Encryption aes(key, key.size(), iv);
// Write whatever exists between ID3v2 and the 1st frame
{
long nbPreambleToGo = pos_1st_frame - id3v2_len - (hasDoRMBox ? sizeof(DoRM_Box) : 0);
while (nbPreambleToGo > 0) {
nbToRead = ((nbPreambleToGo >= sizeof(buffer)) ? sizeof(buffer) : nbPreambleToGo);
nbRead = fread(buffer, 1, nbToRead, mp3_file);
fwrite(buffer, 1, nbRead, aes_file);
nbPreambleToGo -= (long)nbRead;
}
}
assert(ftell(mp3_file) == pos_1st_frame);
long last_pos = 0;
size_t buf_size = 4096;
char * pBuffer = new char[buf_size];
int frame_length = 0;
MP3Header mp3_header, mp3_nextHeader;
for (;;) {
for (;;) {
last_pos = ftell(mp3_file);
if (!readHeader(mp3_file, &mp3_header, true) ||
!checkHeader(&mp3_header)) {
fseek(mp3_file, last_pos, SEEK_SET);
break;
}
frame_length = getFrameLength(&mp3_header);
if (!(frame_length > 0)) break;
示例15: source
bool
SecTpm::importPrivateKeyPkcs5IntoTpm(const Name& keyName,
const uint8_t* buf, size_t size,
const std::string& passwordStr)
{
using namespace CryptoPP;
Oid pbes2Id;
Oid pbkdf2Id;
SecByteBlock saltBlock;
uint32_t iterationCount;
Oid pbes2encsId;
SecByteBlock ivBlock;
SecByteBlock encryptedDataBlock;
try {
// decode some decoding processes are not necessary for now,
// because we assume only one encryption scheme.
StringSource source(buf, size, true);
// EncryptedPrivateKeyInfo ::= SEQUENCE {
// encryptionAlgorithm EncryptionAlgorithmIdentifier,
// encryptedData OCTET STRING }
BERSequenceDecoder encryptedPrivateKeyInfo(source);
{
// EncryptionAlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER {{PBES2-id}},
// parameters SEQUENCE {{PBES2-params}} }
BERSequenceDecoder encryptionAlgorithm(encryptedPrivateKeyInfo);
{
pbes2Id.decode(encryptionAlgorithm);
// PBES2-params ::= SEQUENCE {
// keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
// encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} }
BERSequenceDecoder pbes2Params(encryptionAlgorithm);
{
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER {{PBKDF2-id}},
// parameters SEQUENCE {{PBKDF2-params}} }
BERSequenceDecoder pbes2KDFs(pbes2Params);
{
pbkdf2Id.decode(pbes2KDFs);
// AlgorithmIdentifier ::= SEQUENCE {
// salt OCTET STRING,
// iterationCount INTEGER (1..MAX),
// keyLength INTEGER (1..MAX) OPTIONAL,
// prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 }
BERSequenceDecoder pbkdf2Params(pbes2KDFs);
{
BERDecodeOctetString(pbkdf2Params, saltBlock);
BERDecodeUnsigned<uint32_t>(pbkdf2Params, iterationCount, INTEGER);
}
pbkdf2Params.MessageEnd();
}
pbes2KDFs.MessageEnd();
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER {{DES-EDE3-CBC-PAD}},
// parameters OCTET STRING} {{iv}} }
BERSequenceDecoder pbes2Encs(pbes2Params);
{
pbes2encsId.decode(pbes2Encs);
BERDecodeOctetString(pbes2Encs, ivBlock);
}
pbes2Encs.MessageEnd();
}
pbes2Params.MessageEnd();
}
encryptionAlgorithm.MessageEnd();
BERDecodeOctetString(encryptedPrivateKeyInfo, encryptedDataBlock);
}
encryptedPrivateKeyInfo.MessageEnd();
}
catch (const CryptoPP::Exception& e) {
return false;
}
PKCS5_PBKDF2_HMAC<SHA1> keyGenerator;
size_t derivedLen = 24; //For DES-EDE3-CBC-PAD
byte derived[24] = {0};
byte purpose = 0;
try {
keyGenerator.DeriveKey(derived, derivedLen,
purpose,
reinterpret_cast<const byte*>(passwordStr.c_str()), passwordStr.size(),
saltBlock.BytePtr(), saltBlock.size(),
iterationCount);
}
catch (const CryptoPP::Exception& e) {
return false;
}
//decrypt
CBC_Mode< DES_EDE3 >::Decryption d;
d.SetKeyWithIV(derived, derivedLen, ivBlock.BytePtr());
OBufferStream privateKeyOs;
try {
//.........这里部分代码省略.........