Botan  1.11.15
src/lib/pubkey/pubkey.cpp
Go to the documentation of this file.
00001 /*
00002 * Public Key Base
00003 * (C) 1999-2010 Jack Lloyd
00004 *
00005 * Botan is released under the Simplified BSD License (see license.txt)
00006 */
00007 
00008 #include <botan/pubkey.h>
00009 #include <botan/der_enc.h>
00010 #include <botan/ber_dec.h>
00011 #include <botan/bigint.h>
00012 #include <botan/parsing.h>
00013 #include <botan/internal/algo_registry.h>
00014 #include <botan/internal/bit_ops.h>
00015 
00016 #if defined(BOTAN_HAS_SYSTEM_RNG)
00017   #include <botan/system_rng.h>
00018 #else
00019   #include <botan/auto_rng.h>
00020 #endif
00021 
00022 namespace Botan {
00023 
00024 namespace {
00025 
00026 template<typename T, typename Key>
00027 T* get_pk_op(const Key& key, const std::string& pad)
00028    {
00029    return Algo_Registry<T>::global_registry().make(typename T::Spec(key, pad));
00030    }
00031 
00032 }
00033 
00034 /*
00035 * PK_Encryptor_EME Constructor
00036 */
00037 PK_Encryptor_EME::PK_Encryptor_EME(const Public_Key& key,
00038                                    const std::string& eme_name)
00039    {
00040    m_op.reset(get_pk_op<PK_Ops::Encryption>(key, eme_name));
00041 
00042    if(!m_op)
00043       throw Lookup_Error("Encryption with " + key.algo_name() + " not supported");
00044 
00045    m_eme.reset(get_eme(eme_name));
00046    }
00047 
00048 /*
00049 * Encrypt a message
00050 */
00051 std::vector<byte>
00052 PK_Encryptor_EME::enc(const byte in[],
00053                       size_t length,
00054                       RandomNumberGenerator& rng) const
00055    {
00056    if(m_eme)
00057       {
00058       secure_vector<byte> encoded =
00059          m_eme->encode(in, length, m_op->max_input_bits(), rng);
00060 
00061       if(8*(encoded.size() - 1) + high_bit(encoded[0]) > m_op->max_input_bits())
00062          throw Invalid_Argument("PK_Encryptor_EME: Input is too large");
00063 
00064       return unlock(m_op->encrypt(&encoded[0], encoded.size(), rng));
00065       }
00066    else
00067       {
00068       if(8*(length - 1) + high_bit(in[0]) > m_op->max_input_bits())
00069          throw Invalid_Argument("PK_Encryptor_EME: Input is too large");
00070 
00071       return unlock(m_op->encrypt(&in[0], length, rng));
00072       }
00073    }
00074 
00075 /*
00076 * Return the max size, in bytes, of a message
00077 */
00078 size_t PK_Encryptor_EME::maximum_input_size() const
00079    {
00080    if(!m_eme)
00081       return (m_op->max_input_bits() / 8);
00082    else
00083       return m_eme->maximum_input_size(m_op->max_input_bits());
00084    }
00085 
00086 /*
00087 * PK_Decryptor_EME Constructor
00088 */
00089 PK_Decryptor_EME::PK_Decryptor_EME(const Private_Key& key,
00090                                    const std::string& eme_name)
00091    {
00092    m_op.reset(get_pk_op<PK_Ops::Decryption>(key, eme_name));
00093    m_eme.reset(get_eme(eme_name));
00094    }
00095 
00096 /*
00097 * Decrypt a message
00098 */
00099 secure_vector<byte> PK_Decryptor_EME::dec(const byte msg[],
00100                                           size_t length) const
00101    {
00102    try {
00103       const secure_vector<byte> decrypted = m_op->decrypt(msg, length);
00104       if(m_eme)
00105          return m_eme->decode(decrypted, m_op->max_input_bits());
00106       else
00107          return decrypted;
00108       }
00109    catch(Invalid_Argument)
00110       {
00111       throw Decoding_Error("PK_Decryptor_EME: Input is invalid");
00112       }
00113    }
00114 
00115 /*
00116 * PK_Signer Constructor
00117 */
00118 PK_Signer::PK_Signer(const Private_Key& key,
00119                      const std::string& emsa_name,
00120                      Signature_Format format,
00121                      Fault_Protection prot)
00122    {
00123    m_op.reset(get_pk_op<PK_Ops::Signature>(key, emsa_name));
00124 
00125    if(prot == ENABLE_FAULT_PROTECTION)
00126       m_verify_op.reset(get_pk_op<PK_Ops::Verification>(key, emsa_name));
00127 
00128    if(!m_op || (prot == ENABLE_FAULT_PROTECTION && !m_verify_op))
00129       throw Lookup_Error("Signing with " + key.algo_name() + " not supported");
00130 
00131    m_emsa.reset(get_emsa(emsa_name));
00132    m_sig_format = format;
00133    }
00134 
00135 /*
00136 * Sign a message
00137 */
00138 std::vector<byte> PK_Signer::sign_message(const byte msg[], size_t length,
00139                                            RandomNumberGenerator& rng)
00140    {
00141    update(msg, length);
00142    return signature(rng);
00143    }
00144 
00145 /*
00146 * Add more to the message to be signed
00147 */
00148 void PK_Signer::update(const byte in[], size_t length)
00149    {
00150    m_emsa->update(in, length);
00151    }
00152 
00153 /*
00154 * Check the signature we just created, to help prevent fault attacks
00155 */
00156 bool PK_Signer::self_test_signature(const std::vector<byte>& msg,
00157                                     const std::vector<byte>& sig) const
00158    {
00159    if(!m_verify_op)
00160       return true; // checking disabled, assume ok
00161 
00162    if(m_verify_op->with_recovery())
00163       {
00164       std::vector<byte> recovered =
00165          unlock(m_verify_op->verify_mr(&sig[0], sig.size()));
00166 
00167       if(msg.size() > recovered.size())
00168          {
00169          size_t extra_0s = msg.size() - recovered.size();
00170 
00171          for(size_t i = 0; i != extra_0s; ++i)
00172             if(msg[i] != 0)
00173                return false;
00174 
00175          return same_mem(&msg[extra_0s], &recovered[0], recovered.size());
00176          }
00177 
00178       return (recovered == msg);
00179       }
00180    else
00181       return m_verify_op->verify(&msg[0], msg.size(),
00182                                &sig[0], sig.size());
00183    }
00184 
00185 /*
00186 * Create a signature
00187 */
00188 std::vector<byte> PK_Signer::signature(RandomNumberGenerator& rng)
00189    {
00190    std::vector<byte> encoded = unlock(m_emsa->encoding_of(m_emsa->raw_data(),
00191                                                  m_op->max_input_bits(),
00192                                                         rng));
00193 
00194    std::vector<byte> plain_sig = unlock(m_op->sign(&encoded[0], encoded.size(), rng));
00195 
00196    BOTAN_ASSERT(self_test_signature(encoded, plain_sig), "Signature was consistent");
00197 
00198    if(m_op->message_parts() == 1 || m_sig_format == IEEE_1363)
00199       return plain_sig;
00200 
00201    if(m_sig_format == DER_SEQUENCE)
00202       {
00203       if(plain_sig.size() % m_op->message_parts())
00204          throw Encoding_Error("PK_Signer: strange signature size found");
00205       const size_t SIZE_OF_PART = plain_sig.size() / m_op->message_parts();
00206 
00207       std::vector<BigInt> sig_parts(m_op->message_parts());
00208       for(size_t j = 0; j != sig_parts.size(); ++j)
00209          sig_parts[j].binary_decode(&plain_sig[SIZE_OF_PART*j], SIZE_OF_PART);
00210 
00211       return DER_Encoder()
00212          .start_cons(SEQUENCE)
00213             .encode_list(sig_parts)
00214          .end_cons()
00215       .get_contents_unlocked();
00216       }
00217    else
00218       throw Encoding_Error("PK_Signer: Unknown signature format " +
00219                            std::to_string(m_sig_format));
00220    }
00221 
00222 /*
00223 * PK_Verifier Constructor
00224 */
00225 PK_Verifier::PK_Verifier(const Public_Key& key,
00226                          const std::string& emsa_name,
00227                          Signature_Format format)
00228    {
00229    m_op.reset(get_pk_op<PK_Ops::Verification>(key, emsa_name));
00230 
00231    if(!m_op)
00232       throw Lookup_Error("Verification with " + key.algo_name() + " not supported");
00233 
00234    m_emsa.reset(get_emsa(emsa_name));
00235    m_sig_format = format;
00236    }
00237 
00238 /*
00239 * Set the signature format
00240 */
00241 void PK_Verifier::set_input_format(Signature_Format format)
00242    {
00243    if(m_op->message_parts() == 1 && format != IEEE_1363)
00244       throw Invalid_State("PK_Verifier: This algorithm always uses IEEE 1363");
00245    m_sig_format = format;
00246    }
00247 
00248 /*
00249 * Verify a message
00250 */
00251 bool PK_Verifier::verify_message(const byte msg[], size_t msg_length,
00252                                  const byte sig[], size_t sig_length)
00253    {
00254    update(msg, msg_length);
00255    return check_signature(sig, sig_length);
00256    }
00257 
00258 /*
00259 * Append to the message
00260 */
00261 void PK_Verifier::update(const byte in[], size_t length)
00262    {
00263    m_emsa->update(in, length);
00264    }
00265 
00266 /*
00267 * Check a signature
00268 */
00269 bool PK_Verifier::check_signature(const byte sig[], size_t length)
00270    {
00271    try {
00272       if(m_sig_format == IEEE_1363)
00273          return validate_signature(m_emsa->raw_data(), sig, length);
00274       else if(m_sig_format == DER_SEQUENCE)
00275          {
00276          BER_Decoder decoder(sig, length);
00277          BER_Decoder ber_sig = decoder.start_cons(SEQUENCE);
00278 
00279          size_t count = 0;
00280          std::vector<byte> real_sig;
00281          while(ber_sig.more_items())
00282             {
00283             BigInt sig_part;
00284             ber_sig.decode(sig_part);
00285             real_sig += BigInt::encode_1363(sig_part, m_op->message_part_size());
00286             ++count;
00287             }
00288 
00289          if(count != m_op->message_parts())
00290             throw Decoding_Error("PK_Verifier: signature size invalid");
00291 
00292          return validate_signature(m_emsa->raw_data(),
00293                                    &real_sig[0], real_sig.size());
00294          }
00295       else
00296          throw Decoding_Error("PK_Verifier: Unknown signature format " +
00297                               std::to_string(m_sig_format));
00298       }
00299    catch(Invalid_Argument) { return false; }
00300    }
00301 
00302 /*
00303 * Verify a signature
00304 */
00305 bool PK_Verifier::validate_signature(const secure_vector<byte>& msg,
00306                                      const byte sig[], size_t sig_len)
00307    {
00308    if(m_op->with_recovery())
00309       {
00310       secure_vector<byte> output_of_key = m_op->verify_mr(sig, sig_len);
00311       return m_emsa->verify(output_of_key, msg, m_op->max_input_bits());
00312       }
00313    else
00314       {
00315       Null_RNG rng;
00316 
00317       secure_vector<byte> encoded =
00318          m_emsa->encoding_of(msg, m_op->max_input_bits(), rng);
00319 
00320       return m_op->verify(&encoded[0], encoded.size(), sig, sig_len);
00321       }
00322    }
00323 
00324 /*
00325 * PK_Key_Agreement Constructor
00326 */
00327 PK_Key_Agreement::PK_Key_Agreement(const Private_Key& key,
00328                                    const std::string& kdf_name)
00329    {
00330    m_op.reset(get_pk_op<PK_Ops::Key_Agreement>(key, kdf_name));
00331 
00332    if(!m_op)
00333       throw Lookup_Error("Key agreement with " + key.algo_name() + " not supported");
00334 
00335    m_kdf.reset(get_kdf(kdf_name));
00336    }
00337 
00338 SymmetricKey PK_Key_Agreement::derive_key(size_t key_len, const byte in[],
00339                                           size_t in_len, const byte params[],
00340                                           size_t params_len) const
00341    {
00342    secure_vector<byte> z = m_op->agree(in, in_len);
00343 
00344    if(!m_kdf)
00345       return z;
00346 
00347    return m_kdf->derive_key(key_len, z, params, params_len);
00348    }
00349 
00350 }