word32 EncodeDSA_Signature(const Integer& r, const Integer& s, byte* output) { word32 rSz = r.ByteCount(); word32 sSz = s.ByteCount(); byte rLen[MAX_LENGTH_SZ + 1]; byte sLen[MAX_LENGTH_SZ + 1]; rLen[0] = INTEGER; sLen[0] = INTEGER; word32 rLenSz = SetLength(rSz, &rLen[1]) + 1; word32 sLenSz = SetLength(sSz, &sLen[1]) + 1; byte seqArray[MAX_SEQ_SZ]; word32 seqSz = SetSequence(rLenSz + rSz + sLenSz + sSz, seqArray); // seq memcpy(output, seqArray, seqSz); // r memcpy(output + seqSz, rLen, rLenSz); r.Encode(output + seqSz + rLenSz, rSz); // s memcpy(output + seqSz + rLenSz + rSz, sLen, sLenSz); s.Encode(output + seqSz + rLenSz + rSz + sLenSz, sSz); return seqSz + rLenSz + rSz + sLenSz + sSz; }
bool WestwoodRSA::Encrypt(unsigned char *in_buffer, unsigned int length, unsigned char *out_buffer) { bool success = false; if (length > 0) { Integer e(WWRSA_e); Integer N(WWRSA_N); Integer M; Integer C; unsigned int offset = 0; unsigned int remaining = length; while (remaining >= WWRSA_BLOCK_SIZE) { M.Decode(in_buffer + offset, WWRSA_BLOCK_SIZE); C = a_exp_b_mod_c(M, e, N); C.Encode(out_buffer + offset, WWRSA_BLOCK_SIZE); offset += WWRSA_BLOCK_SIZE; remaining -= WWRSA_BLOCK_SIZE; } if (remaining > 0) { unsigned char buffer[WWRSA_BLOCK_SIZE]; memcpy(buffer, in_buffer + offset, remaining); memset(buffer + remaining, 0, WWRSA_BLOCK_SIZE - remaining); M.Decode(buffer, WWRSA_BLOCK_SIZE); C = a_exp_b_mod_c(M, e, N); C.Encode(out_buffer + offset, WWRSA_BLOCK_SIZE); } success = true; } return success; };
void DiffieHellman::get_parms(byte* bp, byte* bg, byte* bpub) const { using TaoCrypt::Integer; Integer p = pimpl_->dh_.GetP(); Integer g = pimpl_->dh_.GetG(); p.Encode(bp, p.ByteCount()); g.Encode(bg, g.ByteCount()); memcpy(bpub, pimpl_->publicKey_, pimpl_->dh_.GetByteLength()); }
void NRDigestSigner::SignDigest(RandomNumberGenerator &rng, const byte *digest, unsigned int digestLen, byte *signature) const { assert(digestLen <= MaxDigestLength()); Integer h = EncodeDigest(digest, digestLen); Integer r; Integer s; RawSign(rng, h, r, s); unsigned int qLen = m_q.ByteCount(); r.Encode(signature, qLen); s.Encode(signature+qLen, qLen); }
unsigned int ElGamalDecryptor::Decrypt(const byte *cipherText, byte *plainText) { Integer a(cipherText, modulusLen); Integer b(cipherText+modulusLen, modulusLen); Integer m; RawDecrypt(a, b, m); m.Encode(plainText, 1); unsigned int plainTextLength = plainText[0]; if (plainTextLength > MaxPlainTextLength()) return 0; m >>= 8; m.Encode(plainText, plainTextLength); return plainTextLength; }
void DH::GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const { Integer x(rng, ExponentBitLength()); Integer y = gpc.Exponentiate(x); x.Encode(privateKey, PrivateKeyLength()); y.Encode(publicKey, PublicKeyLength()); }
void TF_VerifierBase::InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, unsigned int signatureLength) const { PK_MessageAccumulatorBase &ma = static_cast<PK_MessageAccumulatorBase &>(messageAccumulator); ma.m_representative.New(MessageRepresentativeLength()); Integer x = GetTrapdoorFunctionInterface().ApplyFunction(Integer(signature, signatureLength)); if (x.BitCount() > MessageRepresentativeBitLength()) x = Integer::Zero(); // don't return false here to prevent timing attack x.Encode(ma.m_representative, ma.m_representative.size()); }
// TODO remove it // verify the signature using crypto++ verifier int cryptopp_test(ECPPoint Q, Integer r, Integer s, byte *message, unsigned message_length){ std::vector<byte> signature(64); r.Encode(signature.data(), 32); s.Encode(signature.data()+32, 32); ECDSA<ECP, SHA256>::PublicKey publicKey; publicKey.Initialize(ASN1::secp256k1(), Q); ECDSA<ECP, SHA256>::Signer signer; ECDSA<ECP, SHA256>::Verifier verifier(publicKey); bool result = verifier.VerifyMessage( message, message_length, signature.data(), 64); if(!result){ // cerr << "FAIL cryptopp" << endl; return 1; } return 0; }
std::string Node::RSAdecrypt(Integer raw){ AutoSeededRandomPool prng; raw = privKey.CalculateInverse(prng, raw); std::string recovered; recovered.resize(raw.MinEncodedSize()); raw.Encode((byte *)recovered.data(), recovered.size()); return recovered; }
void OutputPair(const NameValuePairs &v, const char *name) { Integer x; bool b = v.GetValue(name, x); assert(b); cout << name << ": \\\n "; x.Encode(HexEncoder(new FileSink(cout), false, 64, "\\\n ").Ref(), x.MinEncodedSize()); cout << endl; }
DecodingResult TF_DecryptorBase::Decrypt(RandomNumberGenerator &rng, const byte *ciphertext, size_t ciphertextLength, byte *plaintext, const NameValuePairs ¶meters) const { SecByteBlock paddedBlock(PaddedBlockByteLength()); Integer x = GetTrapdoorFunctionInterface().CalculateInverse(rng, Integer(ciphertext, FixedCiphertextLength())); if (x.ByteCount() > paddedBlock.size()) x = Integer::Zero(); // don't return false here to prevent timing attack x.Encode(paddedBlock, paddedBlock.size()); return GetMessageEncodingInterface().Unpad(paddedBlock, PaddedBlockBitLength(), plaintext, parameters); }
bool DH::Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey) const { Integer w(otherPublicKey, PublicKeyLength()); if (validateOtherPublicKey && !(w > 1 && w < p && Jacobi(w, p) == 1)) return false; Integer s(privateKey, PrivateKeyLength()); Integer z = a_exp_b_mod_c(w, s, p); z.Encode(agreedValue, AgreedValueLength()); return true; }
DecodingResult TF_DecryptorBase::Decrypt(RandomNumberGenerator &rng, const byte *ciphertext, size_t ciphertextLength, byte *plaintext, const NameValuePairs ¶meters) const { if (ciphertextLength != FixedCiphertextLength()) throw InvalidArgument(AlgorithmName() + ": ciphertext length of " + IntToString(ciphertextLength) + " doesn't match the required length of " + IntToString(FixedCiphertextLength()) + " for this key"); SecByteBlock paddedBlock(PaddedBlockByteLength()); Integer x = GetTrapdoorFunctionInterface().CalculateInverse(rng, Integer(ciphertext, ciphertextLength)); if (x.ByteCount() > paddedBlock.size()) x = Integer::Zero(); // don't return false here to prevent timing attack x.Encode(paddedBlock, paddedBlock.size()); return GetMessageEncodingInterface().Unpad(paddedBlock, PaddedBlockBitLength(), plaintext, parameters); }
Signature Secp256k1PP::sign(Secret const& _key, h256 const& _hash) { // assumption made by signing alogrithm assert(m_q == m_qs); Signature sig; Integer k(kdf(_key, _hash).data(), 32); if (k == 0) BOOST_THROW_EXCEPTION(InvalidState()); k = 1 + (k % (m_qs - 1)); ECP::Point rp; Integer r; { Guard l(x_params); rp = m_params.ExponentiateBase(k); r = m_params.ConvertElementToInteger(rp); } sig[64] = 0; // sig[64] = (r >= m_q) ? 2 : 0; Integer kInv = k.InverseMod(m_q); Integer z(_hash.asBytes().data(), 32); Integer s = (kInv * (Integer(_key.data(), 32) * r + z)) % m_q; if (r == 0 || s == 0) BOOST_THROW_EXCEPTION(InvalidState()); // if (s > m_qs) // { // s = m_q - s; // if (sig[64]) // sig[64] ^= 1; // } sig[64] |= rp.y.IsOdd() ? 1 : 0; r.Encode(sig.data(), 32); s.Encode(sig.data() + 32, 32); return sig; }
int crypto_dh( unsigned char *s, const unsigned char *pk, const unsigned char *sk ) { Integer base(pk, PUBLICKEY_BYTES); Integer a(sk+PUBLICKEY_BYTES, SECRETKEY_BYTES-PUBLICKEY_BYTES); static Integer p("106711310550942323238863446954494903303206603796265590798875260590060843568007841918927773348877395895791048832517368787533445258799160241834659776192282820736018472427221910874308833884006430888272214561307777629540843737689598751552666502301405808925850579645658786877473119117134988654123934303586903124139"); Integer result = a_exp_b_mod_c(base, a, p); result.Encode(s, SHAREDSECRET_BYTES); return 0; }
word32 SSL_Decrypt(const RSA_PublicKey& key, const byte* sig, byte* plain) { PK_Lengths lengths(key.GetModulus()); ByteBlock paddedBlock(BitsToBytes(lengths.PaddedBlockBitLength())); Integer x = key.ApplyFunction(Integer(sig, lengths.FixedCiphertextLength())); if (x.ByteCount() > paddedBlock.size()) x = Integer::Zero(); x.Encode(paddedBlock.get_buffer(), paddedBlock.size()); return RSA_BlockType1().UnPad(paddedBlock.get_buffer(), lengths.PaddedBlockBitLength(), plain); }
void TF_VerifierBase::InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const { PK_MessageAccumulatorBase &ma = static_cast<PK_MessageAccumulatorBase &>(messageAccumulator); HashIdentifier id = GetHashIdentifier(); const MessageEncodingInterface &encoding = GetMessageEncodingInterface(); if (MessageRepresentativeBitLength() < encoding.MinRepresentativeBitLength(id.second, ma.AccessHash().DigestSize())) throw PK_SignatureScheme::KeyTooShort(); ma.m_representative.New(MessageRepresentativeLength()); Integer x = GetTrapdoorFunctionInterface().ApplyFunction(Integer(signature, signatureLength)); if (x.BitCount() > MessageRepresentativeBitLength()) x = Integer::Zero(); // don't return false here to prevent timing attack x.Encode(ma.m_representative, ma.m_representative.size()); }
//*************************************************************** Integer HashClass::getSHA1Integer(string m, Integer r) { byte *encodedMessage = (byte *)m.c_str(); int messageSize = m.length(); int rSize = r.MinEncodedSize(); byte * encodedR = new byte[rSize]; r.Encode(encodedR, rSize); byte * hashInput = new byte[rSize + messageSize]; copy(encodedMessage, encodedMessage + messageSize, hashInput); copy(encodedR, encodedR + rSize, hashInput + messageSize); byte *hashOutput = getSHA1(hashInput, rSize+messageSize); Integer result; r.Decode(hashOutput, HashClass::size); return r; }
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; }
word32 RSA_Decryptor<Pad>::Decrypt(const byte* cipher, word32 sz, byte* plain, RandomNumberGenerator& rng) { PK_Lengths lengths(key_.GetModulus()); if (sz != lengths.FixedCiphertextLength()) return 0; ByteBlock paddedBlock(lengths.PaddedBlockByteLength()); Integer x = key_.CalculateInverse(rng, Integer(cipher, lengths.FixedCiphertextLength()).Ref()); if (x.ByteCount() > paddedBlock.size()) x = Integer::Zero(); // don't return false, prevents timing attack x.Encode(paddedBlock.get_buffer(), paddedBlock.size()); return padding_.UnPad(paddedBlock.get_buffer(), lengths.PaddedBlockBitLength(), plain); }
bool WestwoodRSA::Decrypt(unsigned char *in_buffer, unsigned int length, unsigned char *out_buffer) { bool success = false; unsigned int blocks = length / WWRSA_BLOCK_SIZE; if (blocks * WWRSA_BLOCK_SIZE == length) { Integer d(WWRSA_d); Integer N(WWRSA_N); Integer C; Integer M; unsigned int offset = 0; for (unsigned int i = 0; i < blocks; i++) { C.Decode(in_buffer + offset, WWRSA_BLOCK_SIZE); M = a_exp_b_mod_c(C, d, N); M.Encode(out_buffer + offset, WWRSA_BLOCK_SIZE); offset += WWRSA_BLOCK_SIZE; } success = true; } return success; };