diff options
Diffstat (limited to 'src')
167 files changed, 1084 insertions, 1997 deletions
diff --git a/src/algo_base/algo_base.h b/src/algo_base/algo_base.h index 813216a36..f757a9a83 100644 --- a/src/algo_base/algo_base.h +++ b/src/algo_base/algo_base.h @@ -19,7 +19,6 @@ namespace Botan { class BOTAN_DLL Algorithm { public: - /** * Zeroize internal state */ @@ -31,10 +30,10 @@ class BOTAN_DLL Algorithm virtual std::string name() const = 0; Algorithm() {} + Algorithm(const Algorithm&) = delete; + Algorithm& operator=(const Algorithm&) = delete; + virtual ~Algorithm() {} - private: - Algorithm(const Algorithm&) {} - Algorithm& operator=(const Algorithm&) { return (*this); } }; } diff --git a/src/algo_factory/algo_cache.h b/src/algo_factory/algo_cache.h index 25f2db023..3a792c994 100644 --- a/src/algo_factory/algo_cache.h +++ b/src/algo_factory/algo_cache.h @@ -8,8 +8,9 @@ #ifndef BOTAN_ALGORITHM_CACHE_TEMPLATE_H__ #define BOTAN_ALGORITHM_CACHE_TEMPLATE_H__ -#include <botan/internal/mutex.h> +#include <botan/types.h> #include <botan/internal/stl_util.h> +#include <mutex> #include <string> #include <vector> #include <map> @@ -67,21 +68,12 @@ class Algorithm_Cache */ void clear_cache(); - /** - * Constructor - * @param m a mutex to serialize internal access - */ - Algorithm_Cache(Mutex* m) : mutex(m) {} - ~Algorithm_Cache() { clear_cache(); delete mutex; } + ~Algorithm_Cache() { clear_cache(); } private: - typedef typename std::map<std::string, std::map<std::string, T*> >::iterator - algorithms_iterator; - - typedef typename std::map<std::string, T*>::iterator provider_iterator; + typename std::map<std::string, std::map<std::string, T*> >::const_iterator + find_algorithm(const std::string& algo_spec); - algorithms_iterator find_algorithm(const std::string& algo_spec); - - Mutex* mutex; + std::mutex mutex; std::map<std::string, std::string> aliases; std::map<std::string, std::string> pref_providers; std::map<std::string, std::map<std::string, T*> > algorithms; @@ -92,16 +84,15 @@ class Algorithm_Cache * Assumes object lock is held */ template<typename T> -typename Algorithm_Cache<T>::algorithms_iterator +typename std::map<std::string, std::map<std::string, T*> >::const_iterator Algorithm_Cache<T>::find_algorithm(const std::string& algo_spec) { - algorithms_iterator algo = algorithms.find(algo_spec); + auto algo = algorithms.find(algo_spec); // Not found? Check if a known alias if(algo == algorithms.end()) { - std::map<std::string, std::string>::const_iterator alias = - aliases.find(algo_spec); + auto alias = aliases.find(algo_spec); if(alias != aliases.end()) algo = algorithms.find(alias->second); @@ -117,16 +108,16 @@ template<typename T> const T* Algorithm_Cache<T>::get(const std::string& algo_spec, const std::string& requested_provider) { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); - algorithms_iterator algo = find_algorithm(algo_spec); + auto algo = find_algorithm(algo_spec); if(algo == algorithms.end()) // algo not found at all (no providers) return 0; // If a provider is requested specifically, return it or fail entirely if(requested_provider != "") { - provider_iterator prov = algo->second.find(requested_provider); + auto prov = algo->second.find(requested_provider); if(prov != algo->second.end()) return prov->second; return 0; @@ -138,7 +129,7 @@ const T* Algorithm_Cache<T>::get(const std::string& algo_spec, const std::string pref_provider = search_map(pref_providers, algo_spec); - for(provider_iterator i = algo->second.begin(); i != algo->second.end(); ++i) + for(auto i = algo->second.begin(); i != algo->second.end(); ++i) { const std::string prov_name = i->first; const size_t prov_weight = static_provider_weight(prov_name); @@ -147,7 +138,7 @@ const T* Algorithm_Cache<T>::get(const std::string& algo_spec, if(prov_name == pref_provider) return i->second; - if(prototype == 0 || prov_weight > prototype_prov_weight) + if(prototype == nullptr || prov_weight > prototype_prov_weight) { prototype = i->second; prototype_provider = i->first; @@ -169,7 +160,7 @@ void Algorithm_Cache<T>::add(T* algo, if(!algo) return; - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); if(algo->name() != requested_name && aliases.find(requested_name) == aliases.end()) @@ -189,15 +180,14 @@ void Algorithm_Cache<T>::add(T* algo, template<typename T> std::vector<std::string> Algorithm_Cache<T>::providers_of(const std::string& algo_name) { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); std::vector<std::string> providers; - algorithms_iterator algo = find_algorithm(algo_name); - + auto algo = find_algorithm(algo_name); if(algo != algorithms.end()) { - provider_iterator provider = algo->second.begin(); + auto provider = algo->second.begin(); while(provider != algo->second.end()) { @@ -216,7 +206,7 @@ template<typename T> void Algorithm_Cache<T>::set_preferred_provider(const std::string& algo_spec, const std::string& provider) { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); pref_providers[algo_spec] = provider; } @@ -227,11 +217,11 @@ void Algorithm_Cache<T>::set_preferred_provider(const std::string& algo_spec, template<typename T> void Algorithm_Cache<T>::clear_cache() { - algorithms_iterator algo = algorithms.begin(); + auto algo = algorithms.begin(); while(algo != algorithms.end()) { - provider_iterator provider = algo->second.begin(); + auto provider = algo->second.begin(); while(provider != algo->second.end()) { diff --git a/src/algo_factory/algo_factory.cpp b/src/algo_factory/algo_factory.cpp index 3d640ab8a..9e4f78569 100644 --- a/src/algo_factory/algo_factory.cpp +++ b/src/algo_factory/algo_factory.cpp @@ -94,13 +94,13 @@ const T* factory_prototype(const std::string& algo_spec, /* * Setup caches */ -Algorithm_Factory::Algorithm_Factory(Mutex_Factory& mf) +Algorithm_Factory::Algorithm_Factory() { - block_cipher_cache = new Algorithm_Cache<BlockCipher>(mf.make()); - stream_cipher_cache = new Algorithm_Cache<StreamCipher>(mf.make()); - hash_cache = new Algorithm_Cache<HashFunction>(mf.make()); - mac_cache = new Algorithm_Cache<MessageAuthenticationCode>(mf.make()); - pbkdf_cache = new Algorithm_Cache<PBKDF>(mf.make()); + block_cipher_cache = new Algorithm_Cache<BlockCipher>(); + stream_cipher_cache = new Algorithm_Cache<StreamCipher>(); + hash_cache = new Algorithm_Cache<HashFunction>(); + mac_cache = new Algorithm_Cache<MessageAuthenticationCode>(); + pbkdf_cache = new Algorithm_Cache<PBKDF>(); } /* @@ -114,7 +114,8 @@ Algorithm_Factory::~Algorithm_Factory() delete mac_cache; delete pbkdf_cache; - std::for_each(engines.begin(), engines.end(), del_fun<Engine>()); + for(auto i = engines.begin(); i != engines.end(); ++i) + delete *i; } void Algorithm_Factory::clear_caches() diff --git a/src/algo_factory/algo_factory.h b/src/algo_factory/algo_factory.h index b9f15757d..1bec2adf7 100644 --- a/src/algo_factory/algo_factory.h +++ b/src/algo_factory/algo_factory.h @@ -26,7 +26,6 @@ class PBKDF; template<typename T> class Algorithm_Cache; class Engine; -class Mutex_Factory; /** * Algorithm Factory @@ -38,7 +37,7 @@ class BOTAN_DLL Algorithm_Factory * Constructor * @param mf a mutex factory */ - Algorithm_Factory(Mutex_Factory& mf); + Algorithm_Factory(); /** * Destructor diff --git a/src/algo_factory/info.txt b/src/algo_factory/info.txt index eae4b3934..236fdda0e 100644 --- a/src/algo_factory/info.txt +++ b/src/algo_factory/info.txt @@ -20,6 +20,5 @@ block engine hash mac -mutex stream </requires> diff --git a/src/alloc/alloc_mmap/mmap_mem.cpp b/src/alloc/alloc_mmap/mmap_mem.cpp index e4b602764..bdc3fcab9 100644 --- a/src/alloc/alloc_mmap/mmap_mem.cpp +++ b/src/alloc/alloc_mmap/mmap_mem.cpp @@ -123,7 +123,7 @@ void* MemoryMapping_Allocator::alloc_block(size_t n) */ void MemoryMapping_Allocator::dealloc_block(void* ptr, size_t n) { - if(ptr == 0) + if(ptr == nullptr) return; const byte PATTERNS[] = { 0x00, 0xF5, 0x5A, 0xAF, 0x00 }; diff --git a/src/alloc/alloc_mmap/mmap_mem.h b/src/alloc/alloc_mmap/mmap_mem.h index fa4e5e715..c9983ed23 100644 --- a/src/alloc/alloc_mmap/mmap_mem.h +++ b/src/alloc/alloc_mmap/mmap_mem.h @@ -21,10 +21,6 @@ namespace Botan { class MemoryMapping_Allocator : public Pooling_Allocator { public: - /** - * @param mutex used for internal locking - */ - MemoryMapping_Allocator(Mutex* mutex) : Pooling_Allocator(mutex) {} std::string type() const { return "mmap"; } private: void* alloc_block(size_t); diff --git a/src/alloc/mem_pool/info.txt b/src/alloc/mem_pool/info.txt index 5097c325f..f87ea4c4c 100644 --- a/src/alloc/mem_pool/info.txt +++ b/src/alloc/mem_pool/info.txt @@ -6,7 +6,3 @@ mem_pool.cpp <header:internal> mem_pool.h </header:internal> - -<requires> -mutex -</requires> diff --git a/src/alloc/mem_pool/mem_pool.cpp b/src/alloc/mem_pool/mem_pool.cpp index f32eb9604..770622149 100644 --- a/src/alloc/mem_pool/mem_pool.cpp +++ b/src/alloc/mem_pool/mem_pool.cpp @@ -46,7 +46,7 @@ byte* Pooling_Allocator::Memory_Block::alloc(size_t n) if(n == BITMAP_SIZE) { if(bitmap) - return 0; + return nullptr; else { bitmap = ~bitmap; @@ -69,7 +69,7 @@ byte* Pooling_Allocator::Memory_Block::alloc(size_t n) } if(bitmap & mask) - return 0; + return nullptr; bitmap |= mask; return buffer + offset * BLOCK_SIZE; @@ -96,7 +96,7 @@ void Pooling_Allocator::Memory_Block::free(void* ptr, size_t blocks) /* * Pooling_Allocator Constructor */ -Pooling_Allocator::Pooling_Allocator(Mutex* m) : mutex(m) +Pooling_Allocator::Pooling_Allocator() { last_used = blocks.begin(); } @@ -106,7 +106,6 @@ Pooling_Allocator::Pooling_Allocator(Mutex* m) : mutex(m) */ Pooling_Allocator::~Pooling_Allocator() { - delete mutex; if(blocks.size()) throw Invalid_State("Pooling_Allocator: Never released memory"); } @@ -116,7 +115,7 @@ Pooling_Allocator::~Pooling_Allocator() */ void Pooling_Allocator::destroy() { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); blocks.clear(); @@ -133,7 +132,7 @@ void* Pooling_Allocator::allocate(size_t n) const size_t BITMAP_SIZE = Memory_Block::bitmap_size(); const size_t BLOCK_SIZE = Memory_Block::block_size(); - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); if(n <= BITMAP_SIZE * BLOCK_SIZE) { @@ -167,10 +166,10 @@ void Pooling_Allocator::deallocate(void* ptr, size_t n) const size_t BITMAP_SIZE = Memory_Block::bitmap_size(); const size_t BLOCK_SIZE = Memory_Block::block_size(); - if(ptr == 0 && n == 0) + if(ptr == nullptr && n == 0) return; - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); if(n > BITMAP_SIZE * BLOCK_SIZE) dealloc_block(ptr, n); @@ -178,8 +177,8 @@ void Pooling_Allocator::deallocate(void* ptr, size_t n) { const size_t block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE; - std::vector<Memory_Block>::iterator i = - std::lower_bound(blocks.begin(), blocks.end(), Memory_Block(ptr)); + auto i = std::lower_bound(blocks.begin(), blocks.end(), + Memory_Block(ptr)); if(i == blocks.end() || !i->contains(ptr, block_no)) throw Invalid_State("Pointer released to the wrong allocator"); @@ -194,9 +193,9 @@ void Pooling_Allocator::deallocate(void* ptr, size_t n) byte* Pooling_Allocator::allocate_blocks(size_t n) { if(blocks.empty()) - return 0; + return nullptr; - std::vector<Memory_Block>::iterator i = last_used; + auto i = last_used; do { @@ -213,7 +212,7 @@ byte* Pooling_Allocator::allocate_blocks(size_t n) } while(i != last_used); - return 0; + return nullptr; } /* @@ -233,7 +232,7 @@ void Pooling_Allocator::get_more_core(size_t in_bytes) const size_t to_allocate = in_blocks * TOTAL_BLOCK_SIZE; void* ptr = alloc_block(to_allocate); - if(ptr == 0) + if(ptr == nullptr) throw Memory_Exhaustion(); allocated.push_back(std::make_pair(ptr, to_allocate)); diff --git a/src/alloc/mem_pool/mem_pool.h b/src/alloc/mem_pool/mem_pool.h index 28d4dd903..f2225e573 100644 --- a/src/alloc/mem_pool/mem_pool.h +++ b/src/alloc/mem_pool/mem_pool.h @@ -10,7 +10,7 @@ #include <botan/allocate.h> #include <botan/exceptn.h> -#include <botan/internal/mutex.h> +#include <mutex> #include <utility> #include <vector> @@ -27,10 +27,7 @@ class Pooling_Allocator : public Allocator void destroy(); - /** - * @param mutex used for internal locking - */ - Pooling_Allocator(Mutex* mutex); + Pooling_Allocator(); ~Pooling_Allocator(); private: void get_more_core(size_t); @@ -69,7 +66,7 @@ class Pooling_Allocator : public Allocator std::vector<Memory_Block> blocks; std::vector<Memory_Block>::iterator last_used; std::vector<std::pair<void*, size_t> > allocated; - Mutex* mutex; + std::mutex mutex; }; } diff --git a/src/alloc/system_alloc/defalloc.h b/src/alloc/system_alloc/defalloc.h index 6fba0e511..c4b90d081 100644 --- a/src/alloc/system_alloc/defalloc.h +++ b/src/alloc/system_alloc/defalloc.h @@ -30,11 +30,6 @@ class Malloc_Allocator : public Allocator class Locking_Allocator : public Pooling_Allocator { public: - /** - * @param mutex used for internal locking - */ - Locking_Allocator(Mutex* mutex) : Pooling_Allocator(mutex) {} - std::string type() const { return "locking"; } private: void* alloc_block(size_t); diff --git a/src/asn1/asn1_alt.cpp b/src/asn1/asn1_alt.cpp index 2d8e3a1d2..1a5c699cd 100644 --- a/src/asn1/asn1_alt.cpp +++ b/src/asn1/asn1_alt.cpp @@ -58,9 +58,8 @@ void AlternativeName::add_attribute(const std::string& type, if(type == "" || str == "") return; - typedef std::multimap<std::string, std::string>::iterator iter; - std::pair<iter, iter> range = alt_info.equal_range(type); - for(iter j = range.first; j != range.second; ++j) + auto range = alt_info.equal_range(type); + for(auto j = range.first; j != range.second; ++j) if(j->second == str) return; @@ -101,13 +100,11 @@ std::multimap<std::string, std::string> AlternativeName::contents() const { std::multimap<std::string, std::string> names; - typedef std::multimap<std::string, std::string>::const_iterator rdn_iter; - for(rdn_iter j = alt_info.begin(); j != alt_info.end(); ++j) - multimap_insert(names, j->first, j->second); + for(auto i = alt_info.begin(); i != alt_info.end(); ++i) + multimap_insert(names, i->first, i->second); - typedef std::multimap<OID, ASN1_String>::const_iterator on_iter; - for(on_iter j = othernames.begin(); j != othernames.end(); ++j) - multimap_insert(names, OIDS::lookup(j->first), j->second.value()); + for(auto i = othernames.begin(); i != othernames.end(); ++i) + multimap_insert(names, OIDS::lookup(i->first), i->second.value()); return names; } @@ -129,19 +126,18 @@ void encode_entries(DER_Encoder& encoder, const std::multimap<std::string, std::string>& attr, const std::string& type, ASN1_Tag tagging) { - typedef std::multimap<std::string, std::string>::const_iterator iter; + auto range = attr.equal_range(type); - std::pair<iter, iter> range = attr.equal_range(type); - for(iter j = range.first; j != range.second; ++j) + for(auto i = range.first; i != range.second; ++i) { if(type == "RFC822" || type == "DNS" || type == "URI") { - ASN1_String asn1_string(j->second, IA5_STRING); + ASN1_String asn1_string(i->second, IA5_STRING); encoder.add_object(tagging, CONTEXT_SPECIFIC, asn1_string.iso_8859()); } else if(type == "IP") { - const u32bit ip = string_to_ipv4(j->second); + const u32bit ip = string_to_ipv4(i->second); byte ip_buf[4] = { 0 }; store_be(ip, ip_buf); encoder.add_object(tagging, CONTEXT_SPECIFIC, ip_buf, 4); @@ -163,8 +159,7 @@ void AlternativeName::encode_into(DER_Encoder& der) const encode_entries(der, alt_info, "URI", ASN1_Tag(6)); encode_entries(der, alt_info, "IP", ASN1_Tag(7)); - std::multimap<OID, ASN1_String>::const_iterator i; - for(i = othernames.begin(); i != othernames.end(); ++i) + for(auto i = othernames.begin(); i != othernames.end(); ++i) { der.start_explicit(0) .encode(i->first) diff --git a/src/asn1/asn1_int.cpp b/src/asn1/asn1_int.cpp index 75cb1f90c..bb4a3ecf7 100644 --- a/src/asn1/asn1_int.cpp +++ b/src/asn1/asn1_int.cpp @@ -20,11 +20,11 @@ BER_Decoding_Error::BER_Decoding_Error(const std::string& str) : Decoding_Error("BER: " + str) {} BER_Bad_Tag::BER_Bad_Tag(const std::string& str, ASN1_Tag tag) : - BER_Decoding_Error(str + ": " + to_string(tag)) {} + BER_Decoding_Error(str + ": " + std::to_string(tag)) {} BER_Bad_Tag::BER_Bad_Tag(const std::string& str, ASN1_Tag tag1, ASN1_Tag tag2) : - BER_Decoding_Error(str + ": " + to_string(tag1) + "/" + to_string(tag2)) {} + BER_Decoding_Error(str + ": " + std::to_string(tag1) + "/" + std::to_string(tag2)) {} namespace ASN1 { diff --git a/src/asn1/asn1_obj.h b/src/asn1/asn1_obj.h index 692a6fde6..3cd8422e6 100644 --- a/src/asn1/asn1_obj.h +++ b/src/asn1/asn1_obj.h @@ -15,6 +15,7 @@ #include <botan/alg_id.h> #include <vector> #include <map> +#include <chrono> namespace Botan { @@ -53,7 +54,7 @@ class BOTAN_DLL X509_Time : public ASN1_Object void set_to(const std::string&); void set_to(const std::string&, ASN1_Tag); - X509_Time(u64bit); + X509_Time(const std::chrono::system_clock::time_point& time); X509_Time(const std::string& = ""); X509_Time(const std::string&, ASN1_Tag); private: diff --git a/src/asn1/asn1_oid.cpp b/src/asn1/asn1_oid.cpp index ae3d48ce2..750eb90f7 100644 --- a/src/asn1/asn1_oid.cpp +++ b/src/asn1/asn1_oid.cpp @@ -52,7 +52,7 @@ std::string OID::as_string() const std::string oid_str; for(size_t i = 0; i != id.size(); ++i) { - oid_str += to_string(id[i]); + oid_str += std::to_string(id[i]); if(i != id.size() - 1) oid_str += '.'; } diff --git a/src/asn1/asn1_str.cpp b/src/asn1/asn1_str.cpp index b28f36d90..44db189f9 100644 --- a/src/asn1/asn1_str.cpp +++ b/src/asn1/asn1_str.cpp @@ -77,7 +77,7 @@ ASN1_String::ASN1_String(const std::string& str, ASN1_Tag t) : tag(t) tag != UTF8_STRING && tag != BMP_STRING) throw Invalid_Argument("ASN1_String: Unknown string type " + - to_string(tag)); + std::to_string(tag)); } /* diff --git a/src/asn1/asn1_tm.cpp b/src/asn1/asn1_tm.cpp index a059e0528..b8095a41c 100644 --- a/src/asn1/asn1_tm.cpp +++ b/src/asn1/asn1_tm.cpp @@ -10,7 +10,7 @@ #include <botan/ber_dec.h> #include <botan/charset.h> #include <botan/parsing.h> -#include <botan/time.h> +#include <botan/calendar.h> namespace Botan { @@ -23,11 +23,11 @@ X509_Time::X509_Time(const std::string& time_str) } /* -* Create an X509_Time +* Create a X509_Time from a time point */ -X509_Time::X509_Time(u64bit timer) +X509_Time::X509_Time(const std::chrono::system_clock::time_point& time) { - calendar_point cal = calendar_value(timer); + calendar_point cal = calendar_value(time); year = cal.year; month = cal.month; @@ -98,7 +98,7 @@ void X509_Time::set_to(const std::string& time_str) void X509_Time::set_to(const std::string& t_spec, ASN1_Tag spec_tag) { if(spec_tag != GENERALIZED_TIME && spec_tag != UTC_TIME) - throw Invalid_Argument("X509_Time: Invalid tag " + to_string(spec_tag)); + throw Invalid_Argument("X509_Time: Invalid tag " + std::to_string(spec_tag)); if(spec_tag == GENERALIZED_TIME && t_spec.size() != 13 && t_spec.size() != 15) throw Invalid_Argument("Invalid GeneralizedTime: " + t_spec); @@ -182,24 +182,30 @@ std::string X509_Time::as_string() const if(time_is_set() == false) throw Invalid_State("X509_Time::as_string: No time set"); - std::string asn1rep; - if(tag == GENERALIZED_TIME) - asn1rep = to_string(year, 4); - else if(tag == UTC_TIME) + u32bit full_year = year; + + if(tag == UTC_TIME) { if(year < 1950 || year >= 2050) throw Encoding_Error("X509_Time: The time " + readable_string() + " cannot be encoded as a UTCTime"); - u32bit asn1year = (year >= 2000) ? (year - 2000) : (year - 1900); - asn1rep = to_string(asn1year, 2); + + full_year = (year >= 2000) ? (year - 2000) : (year - 1900); } - else - throw Invalid_Argument("X509_Time: Invalid tag " + to_string(tag)); - asn1rep += to_string(month, 2) + to_string(day, 2); - asn1rep += to_string(hour, 2) + to_string(minute, 2) + to_string(second, 2); - asn1rep += "Z"; - return asn1rep; + std::string repr = std::to_string(full_year*10000000000 + + month*100000000 + + day*1000000 + + hour*10000 + + minute*100 + + second) + "Z"; + + u32bit desired_size = (tag == UTC_TIME) ? 13 : 15; + + while(repr.size() < desired_size) + repr = "0" + repr; + + return repr; } /* @@ -218,14 +224,12 @@ std::string X509_Time::readable_string() const if(time_is_set() == false) throw Invalid_State("X509_Time::readable_string: No time set"); - std::string readable; - readable += to_string(year, 4) + "/"; - readable += to_string(month ) + "/"; - readable += to_string(day ) + " "; - readable += to_string(hour ) + ":"; - readable += to_string(minute, 2) + ":"; - readable += to_string(second, 2) + " UTC"; - return readable; + std::string output(24, 0); + + std::sprintf(&output[0], "%04d/%02d/%02d %02d:%02d:%02d UTC", + year, month, day, hour, minute, second); + + return output; } /* diff --git a/src/asn1/ber_dec.cpp b/src/asn1/ber_dec.cpp index 164226e69..3754bb158 100644 --- a/src/asn1/ber_dec.cpp +++ b/src/asn1/ber_dec.cpp @@ -142,10 +142,10 @@ void BER_Object::assert_is_a(ASN1_Tag type_tag, ASN1_Tag class_tag) { if(this->type_tag != type_tag || this->class_tag != class_tag) throw BER_Decoding_Error("Tag mismatch when decoding got " + - to_string(this->type_tag) + "/" + - to_string(this->class_tag) + " expected " + - to_string(type_tag) + "/" + - to_string(class_tag)); + std::to_string(this->type_tag) + "/" + + std::to_string(this->class_tag) + " expected " + + std::to_string(type_tag) + "/" + + std::to_string(class_tag)); } /* diff --git a/src/asn1/ber_dec.h b/src/asn1/ber_dec.h index f8b8a704a..87039ed93 100644 --- a/src/asn1/ber_dec.h +++ b/src/asn1/ber_dec.h @@ -103,14 +103,14 @@ class BOTAN_DLL BER_Decoder ASN1_Tag real_type, u16bit type_no); + BER_Decoder& operator=(const BER_Decoder&) = delete; + BER_Decoder(DataSource&); BER_Decoder(const byte[], size_t); BER_Decoder(const MemoryRegion<byte>&); BER_Decoder(const BER_Decoder&); ~BER_Decoder(); private: - BER_Decoder& operator=(const BER_Decoder&) { return (*this); } - BER_Decoder* parent; DataSource* source; BER_Object pushed; diff --git a/src/asn1/der_enc.cpp b/src/asn1/der_enc.cpp index a14b3c5e2..d19e434f0 100644 --- a/src/asn1/der_enc.cpp +++ b/src/asn1/der_enc.cpp @@ -24,7 +24,7 @@ SecureVector<byte> encode_tag(ASN1_Tag type_tag, ASN1_Tag class_tag) { if((class_tag | 0xE0) != 0xE0) throw Encoding_Error("DER_Encoder: Invalid class tag " + - to_string(class_tag)); + std::to_string(class_tag)); SecureVector<byte> encoded_tag; if(type_tag <= 30) diff --git a/src/asn1/x509_dn.cpp b/src/asn1/x509_dn.cpp index f91303296..984645cfe 100644 --- a/src/asn1/x509_dn.cpp +++ b/src/asn1/x509_dn.cpp @@ -26,9 +26,8 @@ X509_DN::X509_DN() */ X509_DN::X509_DN(const std::multimap<OID, std::string>& args) { - std::multimap<OID, std::string>::const_iterator j; - for(j = args.begin(); j != args.end(); ++j) - add_attribute(j->first, j->second); + for(auto i = args.begin(); i != args.end(); ++i) + add_attribute(i->first, i->second); } /* @@ -36,9 +35,8 @@ X509_DN::X509_DN(const std::multimap<OID, std::string>& args) */ X509_DN::X509_DN(const std::multimap<std::string, std::string>& args) { - std::multimap<std::string, std::string>::const_iterator j; - for(j = args.begin(); j != args.end(); ++j) - add_attribute(OIDS::lookup(j->first), j->second); + for(auto i = args.begin(); i != args.end(); ++i) + add_attribute(OIDS::lookup(i->first), i->second); } /* @@ -59,11 +57,9 @@ void X509_DN::add_attribute(const OID& oid, const std::string& str) if(str == "") return; - typedef std::multimap<OID, ASN1_String>::iterator rdn_iter; - - std::pair<rdn_iter, rdn_iter> range = dn_info.equal_range(oid); - for(rdn_iter j = range.first; j != range.second; ++j) - if(j->second.value() == str) + auto range = dn_info.equal_range(oid); + for(auto i = range.first; i != range.second; ++i) + if(i->second.value() == str) return; multimap_insert(dn_info, oid, ASN1_String(str)); @@ -75,11 +71,9 @@ void X509_DN::add_attribute(const OID& oid, const std::string& str) */ std::multimap<OID, std::string> X509_DN::get_attributes() const { - typedef std::multimap<OID, ASN1_String>::const_iterator rdn_iter; - std::multimap<OID, std::string> retval; - for(rdn_iter j = dn_info.begin(); j != dn_info.end(); ++j) - multimap_insert(retval, j->first, j->second.value()); + for(auto i = dn_info.begin(); i != dn_info.end(); ++i) + multimap_insert(retval, i->first, i->second.value()); return retval; } @@ -88,11 +82,9 @@ std::multimap<OID, std::string> X509_DN::get_attributes() const */ std::multimap<std::string, std::string> X509_DN::contents() const { - typedef std::multimap<OID, ASN1_String>::const_iterator rdn_iter; - std::multimap<std::string, std::string> retval; - for(rdn_iter j = dn_info.begin(); j != dn_info.end(); ++j) - multimap_insert(retval, OIDS::lookup(j->first), j->second.value()); + for(auto i = dn_info.begin(); i != dn_info.end(); ++i) + multimap_insert(retval, OIDS::lookup(i->first), i->second.value()); return retval; } @@ -101,14 +93,13 @@ std::multimap<std::string, std::string> X509_DN::contents() const */ std::vector<std::string> X509_DN::get_attribute(const std::string& attr) const { - typedef std::multimap<OID, ASN1_String>::const_iterator rdn_iter; - const OID oid = OIDS::lookup(deref_info_field(attr)); - std::pair<rdn_iter, rdn_iter> range = dn_info.equal_range(oid); + + auto range = dn_info.equal_range(oid); std::vector<std::string> values; - for(rdn_iter j = range.first; j != range.second; ++j) - values.push_back(j->second.value()); + for(auto i = range.first; i != range.second; ++i) + values.push_back(i->second.value()); return values; } @@ -142,15 +133,13 @@ std::string X509_DN::deref_info_field(const std::string& info) */ bool operator==(const X509_DN& dn1, const X509_DN& dn2) { - typedef std::multimap<OID, std::string>::const_iterator rdn_iter; - - std::multimap<OID, std::string> attr1 = dn1.get_attributes(); - std::multimap<OID, std::string> attr2 = dn2.get_attributes(); + auto attr1 = dn1.get_attributes(); + auto attr2 = dn2.get_attributes(); if(attr1.size() != attr2.size()) return false; - rdn_iter p1 = attr1.begin(); - rdn_iter p2 = attr2.begin(); + auto p1 = attr1.begin(); + auto p2 = attr2.begin(); while(true) { @@ -180,18 +169,15 @@ bool operator!=(const X509_DN& dn1, const X509_DN& dn2) */ bool operator<(const X509_DN& dn1, const X509_DN& dn2) { - typedef std::multimap<OID, std::string>::const_iterator rdn_iter; - - std::multimap<OID, std::string> attr1 = dn1.get_attributes(); - std::multimap<OID, std::string> attr2 = dn2.get_attributes(); + auto attr1 = dn1.get_attributes(); + auto attr2 = dn2.get_attributes(); if(attr1.size() < attr2.size()) return true; if(attr1.size() > attr2.size()) return false; - for(rdn_iter p1 = attr1.begin(); p1 != attr1.end(); ++p1) + for(auto p1 = attr1.begin(); p1 != attr1.end(); ++p1) { - std::multimap<OID, std::string>::const_iterator p2; - p2 = attr2.find(p1->first); + auto p2 = attr2.find(p1->first); if(p2 == attr2.end()) return false; if(p1->second > p2->second) return false; if(p1->second < p2->second) return true; @@ -209,8 +195,6 @@ void do_ava(DER_Encoder& encoder, ASN1_Tag string_type, const std::string& oid_str, bool must_exist = false) { - typedef std::multimap<OID, std::string>::const_iterator rdn_iter; - const OID oid = OIDS::lookup(oid_str); const bool exists = (dn_info.find(oid) != dn_info.end()); @@ -218,14 +202,14 @@ void do_ava(DER_Encoder& encoder, throw Encoding_Error("X509_DN: No entry for " + oid_str); if(!exists) return; - std::pair<rdn_iter, rdn_iter> range = dn_info.equal_range(oid); + auto range = dn_info.equal_range(oid); - for(rdn_iter j = range.first; j != range.second; ++j) + for(auto i = range.first; i != range.second; ++i) { encoder.start_cons(SET) .start_cons(SEQUENCE) .encode(oid) - .encode(ASN1_String(j->second, string_type)) + .encode(ASN1_String(i->second, string_type)) .end_cons() .end_cons(); } @@ -238,7 +222,7 @@ void do_ava(DER_Encoder& encoder, */ void X509_DN::encode_into(DER_Encoder& der) const { - std::multimap<OID, std::string> dn_info = get_attributes(); + auto dn_info = get_attributes(); der.start_cons(SEQUENCE); diff --git a/src/benchmark/benchmark.cpp b/src/benchmark/benchmark.cpp index dbccd45c1..a9b84f252 100644 --- a/src/benchmark/benchmark.cpp +++ b/src/benchmark/benchmark.cpp @@ -1,6 +1,6 @@ /* * Runtime benchmarking -* (C) 2008 Jack Lloyd +* (C) 2008-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ @@ -11,33 +11,40 @@ #include <botan/stream_cipher.h> #include <botan/hash.h> #include <botan/mac.h> -#include <botan/time.h> #include <memory> +#include <vector> +#include <chrono> namespace Botan { namespace { +typedef std::chrono::high_resolution_clock benchmark_clock; + /** * Benchmark Buffered_Computation (hash or MAC) */ std::pair<u64bit, u64bit> bench_buf_comp(Buffered_Computation* buf_comp, - u64bit nanoseconds_max, + std::chrono::nanoseconds max_time, const byte buf[], size_t buf_len) { u64bit reps = 0; - u64bit nanoseconds_used = 0; - while(nanoseconds_used < nanoseconds_max) + std::chrono::nanoseconds time_used(0); + + while(time_used < max_time) { - const u64bit start = get_nanoseconds_clock(); + auto start = benchmark_clock::now(); buf_comp->update(buf, buf_len); - nanoseconds_used += get_nanoseconds_clock() - start; + time_used += std::chrono::duration_cast<std::chrono::nanoseconds>(benchmark_clock::now() - start); ++reps; } - return std::make_pair(reps * buf_len, nanoseconds_used); + u64bit ns_taken = + std::chrono::duration_cast<std::chrono::nanoseconds>(time_used).count(); + + return std::make_pair(reps * buf_len, ns_taken); } /** @@ -45,27 +52,32 @@ std::pair<u64bit, u64bit> bench_buf_comp(Buffered_Computation* buf_comp, */ std::pair<u64bit, u64bit> bench_block_cipher(BlockCipher* block_cipher, - u64bit nanoseconds_max, + std::chrono::nanoseconds max_time, byte buf[], size_t buf_len) { const size_t in_blocks = buf_len / block_cipher->block_size(); u64bit reps = 0; - u64bit nanoseconds_used = 0; + + std::chrono::nanoseconds time_used(0); block_cipher->set_key(buf, block_cipher->maximum_keylength()); - while(nanoseconds_used < nanoseconds_max) + while(time_used < max_time) { - const u64bit start = get_nanoseconds_clock(); + auto start = benchmark_clock::now(); block_cipher->encrypt_n(buf, buf, in_blocks); - nanoseconds_used += get_nanoseconds_clock() - start; + time_used += std::chrono::duration_cast<std::chrono::nanoseconds>(benchmark_clock::now() - start); + //time_used += benchmark_clock::now() - start; ++reps; } + u64bit ns_taken = + std::chrono::duration_cast<std::chrono::nanoseconds>(time_used).count(); + return std::make_pair(reps * in_blocks * block_cipher->block_size(), - nanoseconds_used); + ns_taken); } /** @@ -73,24 +85,28 @@ bench_block_cipher(BlockCipher* block_cipher, */ std::pair<u64bit, u64bit> bench_stream_cipher(StreamCipher* stream_cipher, - u64bit nanoseconds_max, + std::chrono::nanoseconds max_time, byte buf[], size_t buf_len) { u64bit reps = 0; - u64bit nanoseconds_used = 0; stream_cipher->set_key(buf, stream_cipher->maximum_keylength()); - while(nanoseconds_used < nanoseconds_max) + std::chrono::nanoseconds time_used(0); + + while(time_used < max_time) { - const u64bit start = get_nanoseconds_clock(); + auto start = benchmark_clock::now(); stream_cipher->cipher1(buf, buf_len); - nanoseconds_used += get_nanoseconds_clock() - start; + time_used += benchmark_clock::now() - start; ++reps; } - return std::make_pair(reps * buf_len, nanoseconds_used); + u64bit ns_taken = + std::chrono::duration_cast<std::chrono::nanoseconds>(time_used).count(); + + return std::make_pair(reps * buf_len, ns_taken); } /** @@ -98,10 +114,10 @@ bench_stream_cipher(StreamCipher* stream_cipher, */ std::pair<u64bit, u64bit> bench_hash(HashFunction* hash, - u64bit nanoseconds_max, + std::chrono::nanoseconds max_time, const byte buf[], size_t buf_len) { - return bench_buf_comp(hash, nanoseconds_max, buf, buf_len); + return bench_buf_comp(hash, max_time, buf, buf_len); } /** @@ -109,11 +125,11 @@ bench_hash(HashFunction* hash, */ std::pair<u64bit, u64bit> bench_mac(MessageAuthenticationCode* mac, - u64bit nanoseconds_max, + std::chrono::nanoseconds max_time, const byte buf[], size_t buf_len) { mac->set_key(buf, mac->maximum_keylength()); - return bench_buf_comp(mac, nanoseconds_max, buf, buf_len); + return bench_buf_comp(mac, max_time, buf, buf_len); } } @@ -122,7 +138,7 @@ std::map<std::string, double> algorithm_benchmark(const std::string& name, Algorithm_Factory& af, RandomNumberGenerator& rng, - u32bit milliseconds, + std::chrono::milliseconds milliseconds, size_t buf_size) { std::vector<std::string> providers = af.providers_of(name); @@ -131,8 +147,7 @@ algorithm_benchmark(const std::string& name, if(providers.empty()) // no providers, nothing to do return all_results; - const u64bit ns_per_provider = - (static_cast<u64bit>(milliseconds) * 1000 * 1000) / providers.size(); + std::chrono::nanoseconds ns_per_provider = milliseconds / providers.size(); std::vector<byte> buf(buf_size * 1024); rng.randomize(&buf[0], buf.size()); @@ -146,7 +161,7 @@ algorithm_benchmark(const std::string& name, if(const BlockCipher* proto = af.prototype_block_cipher(name, provider)) { - std::auto_ptr<BlockCipher> block_cipher(proto->clone()); + std::unique_ptr<BlockCipher> block_cipher(proto->clone()); results = bench_block_cipher(block_cipher.get(), ns_per_provider, &buf[0], buf.size()); @@ -154,7 +169,7 @@ algorithm_benchmark(const std::string& name, else if(const StreamCipher* proto = af.prototype_stream_cipher(name, provider)) { - std::auto_ptr<StreamCipher> stream_cipher(proto->clone()); + std::unique_ptr<StreamCipher> stream_cipher(proto->clone()); results = bench_stream_cipher(stream_cipher.get(), ns_per_provider, &buf[0], buf.size()); @@ -162,14 +177,14 @@ algorithm_benchmark(const std::string& name, else if(const HashFunction* proto = af.prototype_hash_function(name, provider)) { - std::auto_ptr<HashFunction> hash(proto->clone()); + std::unique_ptr<HashFunction> hash(proto->clone()); results = bench_hash(hash.get(), ns_per_provider, &buf[0], buf.size()); } else if(const MessageAuthenticationCode* proto = af.prototype_mac(name, provider)) { - std::auto_ptr<MessageAuthenticationCode> mac(proto->clone()); + std::unique_ptr<MessageAuthenticationCode> mac(proto->clone()); results = bench_mac(mac.get(), ns_per_provider, &buf[0], buf.size()); } diff --git a/src/benchmark/benchmark.h b/src/benchmark/benchmark.h index c47fdc166..17df85e4e 100644 --- a/src/benchmark/benchmark.h +++ b/src/benchmark/benchmark.h @@ -1,6 +1,6 @@ /* * Runtime benchmarking -* (C) 2008 Jack Lloyd +* (C) 2008-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ @@ -12,6 +12,7 @@ #include <botan/rng.h> #include <map> #include <string> +#include <chrono> namespace Botan { @@ -28,7 +29,7 @@ std::map<std::string, double> BOTAN_DLL algorithm_benchmark(const std::string& name, Algorithm_Factory& af, RandomNumberGenerator& rng, - u32bit milliseconds, + std::chrono::milliseconds milliseconds, size_t buf_size); } diff --git a/src/block/camellia/camellia.cpp b/src/block/camellia/camellia.cpp index 30e638451..054558c35 100644 --- a/src/block/camellia/camellia.cpp +++ b/src/block/camellia/camellia.cpp @@ -115,52 +115,30 @@ void Camellia::encrypt_n(const byte in[], byte out[], size_t blocks) const u64bit D1 = load_be<u64bit>(in, 0); u64bit D2 = load_be<u64bit>(in, 1); - D1 ^= K[0]; - D2 ^= K[1]; - D2 ^= F(D1, K[2]); - D1 ^= F(D2, K[3]); - D2 ^= F(D1, K[4]); - D1 ^= F(D2, K[5]); - D2 ^= F(D1, K[6]); - D1 ^= F(D2, K[7]); - D1 = FL (D1, K[8]); - D2 = FLINV(D2, K[9]); - - D2 ^= F(D1, K[10]); - D1 ^= F(D2, K[11]); - D2 ^= F(D1, K[12]); - D1 ^= F(D2, K[13]); - D2 ^= F(D1, K[14]); - D1 ^= F(D2, K[15]); - D1 = FL (D1, K[16]); - D2 = FLINV(D2, K[17]); - - D2 ^= F(D1, K[18]); - D1 ^= F(D2, K[19]); - D2 ^= F(D1, K[20]); - D1 ^= F(D2, K[21]); - D2 ^= F(D1, K[22]); - D1 ^= F(D2, K[23]); - - if(K.size() == 34) - { - D1 = FL (D1, K[24]); - D2 = FLINV(D2, K[25]); - D2 ^= F(D1, K[26]); - D1 ^= F(D2, K[27]); - D2 ^= F(D1, K[28]); - D1 ^= F(D2, K[29]); - D2 ^= F(D1, K[30]); - D1 ^= F(D2, K[31]); - D2 ^= K[32]; - D1 ^= K[33]; - } - else + const u64bit* K = &SK[0]; + + D1 ^= *K++; + D2 ^= *K++; + + while(true) { - D2 ^= K[24]; - D1 ^= K[25]; + D2 ^= F(D1, *K++); + D1 ^= F(D2, *K++); + D2 ^= F(D1, *K++); + D1 ^= F(D2, *K++); + D2 ^= F(D1, *K++); + D1 ^= F(D2, *K++); + + if(K == &SK[SK.size()-2]) + break; + + D1 = FL (D1, *K++); + D2 = FLINV(D2, *K++); } + D2 ^= *K++; + D1 ^= *K++; + store_be(out, D2, D1); in += BLOCK_SIZE; @@ -180,52 +158,29 @@ void Camellia::decrypt_n(const byte in[], byte out[], size_t blocks) const u64bit D1 = load_be<u64bit>(in, 0); u64bit D2 = load_be<u64bit>(in, 1); - if(K.size() == 34) - { - D1 ^= K[32]; - D2 ^= K[33]; - - D2 ^= F(D1, K[31]); - D1 ^= F(D2, K[30]); - D2 ^= F(D1, K[29]); - D1 ^= F(D2, K[28]); - D2 ^= F(D1, K[27]); - D1 ^= F(D2, K[26]); - D1 = FL (D1, K[25]); - D2 = FLINV(D2, K[24]); - } - else + const u64bit* K = &SK[SK.size()-1]; + + D2 ^= *K--; + D1 ^= *K--; + + while(true) { - D1 ^= K[24]; - D2 ^= K[25]; + D2 ^= F(D1, *K--); + D1 ^= F(D2, *K--); + D2 ^= F(D1, *K--); + D1 ^= F(D2, *K--); + D2 ^= F(D1, *K--); + D1 ^= F(D2, *K--); + + if(K == &SK[1]) + break; + + D1 = FL (D1, *K--); + D2 = FLINV(D2, *K--); } - D2 ^= F(D1, K[23]); - D1 ^= F(D2, K[22]); - D2 ^= F(D1, K[21]); - D1 ^= F(D2, K[20]); - D2 ^= F(D1, K[19]); - D1 ^= F(D2, K[18]); - D1 = FL (D1, K[17]); - D2 = FLINV(D2, K[16]); - - D2 ^= F(D1, K[15]); - D1 ^= F(D2, K[14]); - D2 ^= F(D1, K[13]); - D1 ^= F(D2, K[12]); - D2 ^= F(D1, K[11]); - D1 ^= F(D2, K[10]); - D1 = FL (D1, K[ 9]); - D2 = FLINV(D2, K[ 8]); - - D2 ^= F(D1, K[ 7]); - D1 ^= F(D2, K[ 6]); - D2 ^= F(D1, K[ 5]); - D1 ^= F(D2, K[ 4]); - D2 ^= F(D1, K[ 3]); - D1 ^= F(D2, K[ 2]); - D2 ^= K[0]; - D1 ^= K[1]; + D1 ^= *K--; + D2 ^= *K; store_be(out, D2, D1); @@ -277,79 +232,79 @@ void Camellia::key_schedule(const byte key[], size_t length) if(length == 16) { - K.resize(26); - - K[ 0] = KL_H; - K[ 1] = KL_L; - K[ 2] = KA_H; - K[ 3] = KA_L; - K[ 4] = left_rot_hi(KL_H, KL_L, 15); - K[ 5] = left_rot_lo(KL_H, KL_L, 15); - K[ 6] = left_rot_hi(KA_H, KA_L, 15); - K[ 7] = left_rot_lo(KA_H, KA_L, 15); - K[ 8] = left_rot_hi(KA_H, KA_L, 30); - K[ 9] = left_rot_lo(KA_H, KA_L, 30); - K[10] = left_rot_hi(KL_H, KL_L, 45); - K[11] = left_rot_lo(KL_H, KL_L, 45); - K[12] = left_rot_hi(KA_H, KA_L, 45); - K[13] = left_rot_lo(KL_H, KL_L, 60); - K[14] = left_rot_hi(KA_H, KA_L, 60); - K[15] = left_rot_lo(KA_H, KA_L, 60); - K[16] = left_rot_lo(KL_H, KL_L, 77-64); - K[17] = left_rot_hi(KL_H, KL_L, 77-64); - K[18] = left_rot_lo(KL_H, KL_L, 94-64); - K[19] = left_rot_hi(KL_H, KL_L, 94-64); - K[20] = left_rot_lo(KA_H, KA_L, 94-64); - K[21] = left_rot_hi(KA_H, KA_L, 94-64); - K[22] = left_rot_lo(KL_H, KL_L, 111-64); - K[23] = left_rot_hi(KL_H, KL_L, 111-64); - K[24] = left_rot_lo(KA_H, KA_L, 111-64); - K[25] = left_rot_hi(KA_H, KA_L, 111-64); + SK.resize(26); + + SK[ 0] = KL_H; + SK[ 1] = KL_L; + SK[ 2] = KA_H; + SK[ 3] = KA_L; + SK[ 4] = left_rot_hi(KL_H, KL_L, 15); + SK[ 5] = left_rot_lo(KL_H, KL_L, 15); + SK[ 6] = left_rot_hi(KA_H, KA_L, 15); + SK[ 7] = left_rot_lo(KA_H, KA_L, 15); + SK[ 8] = left_rot_hi(KA_H, KA_L, 30); + SK[ 9] = left_rot_lo(KA_H, KA_L, 30); + SK[10] = left_rot_hi(KL_H, KL_L, 45); + SK[11] = left_rot_lo(KL_H, KL_L, 45); + SK[12] = left_rot_hi(KA_H, KA_L, 45); + SK[13] = left_rot_lo(KL_H, KL_L, 60); + SK[14] = left_rot_hi(KA_H, KA_L, 60); + SK[15] = left_rot_lo(KA_H, KA_L, 60); + SK[16] = left_rot_lo(KL_H, KL_L, 77-64); + SK[17] = left_rot_hi(KL_H, KL_L, 77-64); + SK[18] = left_rot_lo(KL_H, KL_L, 94-64); + SK[19] = left_rot_hi(KL_H, KL_L, 94-64); + SK[20] = left_rot_lo(KA_H, KA_L, 94-64); + SK[21] = left_rot_hi(KA_H, KA_L, 94-64); + SK[22] = left_rot_lo(KL_H, KL_L, 111-64); + SK[23] = left_rot_hi(KL_H, KL_L, 111-64); + SK[24] = left_rot_lo(KA_H, KA_L, 111-64); + SK[25] = left_rot_hi(KA_H, KA_L, 111-64); } else { - K.resize(34); - - K[ 0] = KL_H; - K[ 1] = KL_L; - K[ 2] = KB_H; - K[ 3] = KB_L; - - K[ 4] = left_rot_hi(KR_H, KR_L, 15); - K[ 5] = left_rot_lo(KR_H, KR_L, 15); - K[ 6] = left_rot_hi(KA_H, KA_L, 15); - K[ 7] = left_rot_lo(KA_H, KA_L, 15); - - K[ 8] = left_rot_hi(KR_H, KR_L, 30); - K[ 9] = left_rot_lo(KR_H, KR_L, 30); - K[10] = left_rot_hi(KB_H, KB_L, 30); - K[11] = left_rot_lo(KB_H, KB_L, 30); - - K[12] = left_rot_hi(KL_H, KL_L, 45); - K[13] = left_rot_lo(KL_H, KL_L, 45); - K[14] = left_rot_hi(KA_H, KA_L, 45); - K[15] = left_rot_lo(KA_H, KA_L, 45); - - K[16] = left_rot_hi(KL_H, KL_L, 60); - K[17] = left_rot_lo(KL_H, KL_L, 60); - K[18] = left_rot_hi(KR_H, KR_L, 60); - K[19] = left_rot_lo(KR_H, KR_L, 60); - K[20] = left_rot_hi(KB_H, KB_L, 60); - K[21] = left_rot_lo(KB_H, KB_L, 60); - - K[22] = left_rot_lo(KL_H, KL_L, 77-64); - K[23] = left_rot_hi(KL_H, KL_L, 77-64); - K[24] = left_rot_lo(KA_H, KA_L, 77-64); - K[25] = left_rot_hi(KA_H, KA_L, 77-64); - - K[26] = left_rot_lo(KR_H, KR_L, 94-64); - K[27] = left_rot_hi(KR_H, KR_L, 94-64); - K[28] = left_rot_lo(KA_H, KA_L, 94-64); - K[29] = left_rot_hi(KA_H, KA_L, 94-64); - K[30] = left_rot_lo(KL_H, KL_L, 111-64); - K[31] = left_rot_hi(KL_H, KL_L, 111-64); - K[32] = left_rot_lo(KB_H, KB_L, 111-64); - K[33] = left_rot_hi(KB_H, KB_L, 111-64); + SK.resize(34); + + SK[ 0] = KL_H; + SK[ 1] = KL_L; + SK[ 2] = KB_H; + SK[ 3] = KB_L; + + SK[ 4] = left_rot_hi(KR_H, KR_L, 15); + SK[ 5] = left_rot_lo(KR_H, KR_L, 15); + SK[ 6] = left_rot_hi(KA_H, KA_L, 15); + SK[ 7] = left_rot_lo(KA_H, KA_L, 15); + + SK[ 8] = left_rot_hi(KR_H, KR_L, 30); + SK[ 9] = left_rot_lo(KR_H, KR_L, 30); + SK[10] = left_rot_hi(KB_H, KB_L, 30); + SK[11] = left_rot_lo(KB_H, KB_L, 30); + + SK[12] = left_rot_hi(KL_H, KL_L, 45); + SK[13] = left_rot_lo(KL_H, KL_L, 45); + SK[14] = left_rot_hi(KA_H, KA_L, 45); + SK[15] = left_rot_lo(KA_H, KA_L, 45); + + SK[16] = left_rot_hi(KL_H, KL_L, 60); + SK[17] = left_rot_lo(KL_H, KL_L, 60); + SK[18] = left_rot_hi(KR_H, KR_L, 60); + SK[19] = left_rot_lo(KR_H, KR_L, 60); + SK[20] = left_rot_hi(KB_H, KB_L, 60); + SK[21] = left_rot_lo(KB_H, KB_L, 60); + + SK[22] = left_rot_lo(KL_H, KL_L, 77-64); + SK[23] = left_rot_hi(KL_H, KL_L, 77-64); + SK[24] = left_rot_lo(KA_H, KA_L, 77-64); + SK[25] = left_rot_hi(KA_H, KA_L, 77-64); + + SK[26] = left_rot_lo(KR_H, KR_L, 94-64); + SK[27] = left_rot_hi(KR_H, KR_L, 94-64); + SK[28] = left_rot_lo(KA_H, KA_L, 94-64); + SK[29] = left_rot_hi(KA_H, KA_L, 94-64); + SK[30] = left_rot_lo(KL_H, KL_L, 111-64); + SK[31] = left_rot_hi(KL_H, KL_L, 111-64); + SK[32] = left_rot_lo(KB_H, KB_L, 111-64); + SK[33] = left_rot_hi(KB_H, KB_L, 111-64); } } diff --git a/src/block/camellia/camellia.h b/src/block/camellia/camellia.h index 7795f1fcf..aaf3ad9e3 100644 --- a/src/block/camellia/camellia.h +++ b/src/block/camellia/camellia.h @@ -21,13 +21,13 @@ class BOTAN_DLL Camellia : public Block_Cipher_Fixed_Params<16, 16, 32, 8> void encrypt_n(const byte in[], byte out[], size_t blocks) const; void decrypt_n(const byte in[], byte out[], size_t blocks) const; - void clear() { K.clear(); } + void clear() { SK.clear(); } std::string name() const { return "Camellia"; } BlockCipher* clone() const { return new Camellia; } private: void key_schedule(const byte key[], size_t length); - SecureVector<u64bit> K; + SecureVector<u64bit> SK; }; } diff --git a/src/block/lion/lion.cpp b/src/block/lion/lion.cpp index 46308e428..8c39eee65 100644 --- a/src/block/lion/lion.cpp +++ b/src/block/lion/lion.cpp @@ -83,7 +83,7 @@ std::string Lion::name() const { return "Lion(" + hash->name() + "," + cipher->name() + "," + - to_string(BLOCK_SIZE) + ")"; + std::to_string(BLOCK_SIZE) + ")"; } /* diff --git a/src/block/misty1/misty1.cpp b/src/block/misty1/misty1.cpp index 36c25a814..77d1047b1 100644 --- a/src/block/misty1/misty1.cpp +++ b/src/block/misty1/misty1.cpp @@ -255,7 +255,7 @@ MISTY1::MISTY1(size_t rounds) : EK(100), DK(100) { if(rounds != 8) throw Invalid_Argument("MISTY1: Invalid number of rounds: " - + to_string(rounds)); + + std::to_string(rounds)); } } diff --git a/src/block/rc5/rc5.cpp b/src/block/rc5/rc5.cpp index cfcc4cb64..981f73564 100644 --- a/src/block/rc5/rc5.cpp +++ b/src/block/rc5/rc5.cpp @@ -116,7 +116,7 @@ void RC5::key_schedule(const byte key[], size_t length) */ std::string RC5::name() const { - return "RC5(" + to_string(get_rounds()) + ")"; + return "RC5(" + std::to_string(get_rounds()) + ")"; } /* @@ -126,7 +126,7 @@ RC5::RC5(size_t rounds) { if(rounds < 8 || rounds > 32 || (rounds % 4 != 0)) throw Invalid_Argument("RC5: Invalid number of rounds " + - to_string(rounds)); + std::to_string(rounds)); S.resize(2*rounds + 2); } diff --git a/src/block/safer/safer_sk.cpp b/src/block/safer/safer_sk.cpp index a3a6cefd8..5275a0781 100644 --- a/src/block/safer/safer_sk.cpp +++ b/src/block/safer/safer_sk.cpp @@ -230,7 +230,7 @@ void SAFER_SK::key_schedule(const byte key[], size_t) */ std::string SAFER_SK::name() const { - return "SAFER-SK(" + to_string(get_rounds()) + ")"; + return "SAFER-SK(" + std::to_string(get_rounds()) + ")"; } /* diff --git a/src/build-data/cc/clang.txt b/src/build-data/cc/clang.txt index e5d52db3d..8860a30ba 100644 --- a/src/build-data/cc/clang.txt +++ b/src/build-data/cc/clang.txt @@ -10,7 +10,7 @@ add_include_dir_option -I add_lib_dir_option -L add_lib_option -l -lang_flags "-D_REENTRANT -ansi -Wno-long-long" +lang_flags "-D_REENTRANT -std=c++0x" warning_flags "-W -Wall" makefile_style unix diff --git a/src/build-data/cc/compaq.txt b/src/build-data/cc/compaq.txt deleted file mode 100644 index 7e7f1ea56..000000000 --- a/src/build-data/cc/compaq.txt +++ /dev/null @@ -1,26 +0,0 @@ -macro_name COMPAQ - -binary_name cxx - -compile_option "-c " -output_to_option "-o " -add_include_dir_option -I -add_lib_dir_option -L -add_lib_option -l - -# -O3 and up seem to be unhappy with Botan -lib_opt_flags "-O2" -check_opt_flags "-O2" -debug_flags -g -no_debug_flags "" -lang_flags "-std ansi -D__USE_STD_IOSTREAM" - -makefile_style unix - -<so_link_flags> -default -> "$(CXX) -shared -soname $(SONAME)" -</so_link_flags> - -<mach_opt> -alpha -> "-arch=SUBMODEL" alpha- -</mach_opt> diff --git a/src/build-data/cc/gcc.txt b/src/build-data/cc/gcc.txt index 6173f6271..835627eb0 100644 --- a/src/build-data/cc/gcc.txt +++ b/src/build-data/cc/gcc.txt @@ -1,8 +1,6 @@ macro_name GCC -binary_name g++ - -has_tr1 yes +binary_name g++-4.7.0 compile_option "-c " output_to_option "-o " @@ -10,7 +8,7 @@ add_include_dir_option -I add_lib_dir_option -L add_lib_option -l -lang_flags "-D_REENTRANT -Wno-long-long" +lang_flags "-D_REENTRANT -std=c++11" warning_flags "-W -Wall" maintainer_warning_flags "-Werror -Wall -Wextra -Wstrict-aliasing -Wstrict-overflow=5 -Wcast-align -Wmissing-declarations -Wpointer-arith -Wcast-qual -Wold-style-cast" @@ -90,18 +88,16 @@ x86_64 -> "-march=SUBMODEL -momit-leaf-frame-pointer" # The 'linking' bit means "use this for both compiling *and* linking" <mach_abi_linking> -x86_64 -> "-m64" +all -> "-pthread" + mips64 -> "-mabi=64" s390 -> "-m31" s390x -> "-m64" sparc32 -> "-m32 -mno-app-regs" sparc64 -> "-m64 -mno-app-regs" ppc64 -> "-m64" +x86_64 -> "-m64" -# This should probably be used on most/all targets, but the docs are unclear -openbsd -> "-pthread" -freebsd -> "-pthread" -dragonfly -> "-pthread" -netbsd -> "-pthread -D_NETBSD_SOURCE" -qnx -> "-fexceptions -D_QNX_SOURCE" +netbsd -> "-D_NETBSD_SOURCE" +qnx -> "-fexceptions -D_QNX_SOURCE" </mach_abi_linking> diff --git a/src/build-data/cc/icc.txt b/src/build-data/cc/icc.txt index 28c1a2816..e11875cb1 100644 --- a/src/build-data/cc/icc.txt +++ b/src/build-data/cc/icc.txt @@ -2,8 +2,6 @@ macro_name INTEL binary_name icpc -has_tr1 yes - compile_option "-c " output_to_option "-o " add_include_dir_option -I @@ -14,7 +12,7 @@ lib_opt_flags "-O2 -ip -unroll" check_opt_flags "-O2" debug_flags -g no_debug_flags "-fomit-frame-pointer" -lang_flags "" +lang_flags "-std=c++0x" warning_flags "-w1" shared_flags "-fPIC" diff --git a/src/build-data/cc/kai.txt b/src/build-data/cc/kai.txt deleted file mode 100644 index 2d9c0cd65..000000000 --- a/src/build-data/cc/kai.txt +++ /dev/null @@ -1,27 +0,0 @@ -macro_name KAI - -binary_name KCC - -compile_option "-c " -output_to_option "-o " -add_include_dir_option -I -add_lib_dir_option -L -add_lib_option -l - -ar_command "KCC -o" - -lib_opt_flags "+K3 --inline_auto_space_time=65 --abstract_pointer" -check_opt_flags "+K3" -lang_flags "-D__KAI_STRICT" -debug_flags -g -no_debug_flags "" - -makefile_style unix - -<so_link_flags> -default -> "$(CXX) --soname $(SONAME)" -</so_link_flags> - -<mach_abi_linking> -all -> "--one_per" -</mach_abi_linking> diff --git a/src/build-data/cc/mipspro.txt b/src/build-data/cc/mipspro.txt deleted file mode 100644 index 28b47b30d..000000000 --- a/src/build-data/cc/mipspro.txt +++ /dev/null @@ -1,39 +0,0 @@ -macro_name MIPSPRO - -binary_name CC - -compile_option "-c " -output_to_option "-o " -add_include_dir_option -I -add_lib_dir_option -L -add_lib_option -l - -lib_opt_flags "-O3 -OPT:alias=TYPED" -check_opt_flags "-O3 -OPT:alias=TYPED" -debug_flags "-g3" -no_debug_flags "" -shared_flags "-KPIC" -lang_flags "-ansi -LANG:ansi-for-init-scope=ON" -# Disabled, because, while my code is fine, it warns about a lot of it's own -# headers <g> -#warning_flags "-fullwarn" - -makefile_style unix - -<so_link_flags> -default -> "$(CXX) -shared -Wl,-soname,$(SONAME)" -</so_link_flags> - -<mach_opt> -mips32 -> "-mips1" -mips64 -> "-mips3" - -mips64-r5000 -> "-mips4 -r5000" -mips64-r8000 -> "-mips4 -r8000" -mips64-r10000 -> "-mips4 -r10000" -</mach_opt> - -<mach_abi_linking> -mips32 -> "-n32" -mips64 -> "-64" -</mach_abi_linking> diff --git a/src/build-data/cc/sgipro64.txt b/src/build-data/cc/sgipro64.txt deleted file mode 100644 index e6a58f16d..000000000 --- a/src/build-data/cc/sgipro64.txt +++ /dev/null @@ -1,27 +0,0 @@ -macro_name SGI_PRO64 - -binary_name sgiCC - -compile_option "-c " -output_to_option "-o " -add_include_dir_option -I -add_lib_dir_option -L -add_lib_option -l - -lib_opt_flags "-O3 -OPT:alias=TYPED" -check_opt_flags "-O3 -OPT:alias=TYPED" -debug_flags "-g3" -no_debug_flags "" -shared_flags "-KPIC" -lang_flags "-ansi -LANG:ansi-for-init-scope=ON" -warning_flags "-Wall -W" - -makefile_style unix - -<so_link_flags> -default -> "$(CXX) -shared -Wl,-soname,$(SONAME)" -</so_link_flags> - -<mach_opt> - -</mach_opt> diff --git a/src/build-data/os/windows.txt b/src/build-data/os/windows.txt index 2f344e33c..30a6b77f8 100644 --- a/src/build-data/os/windows.txt +++ b/src/build-data/os/windows.txt @@ -11,10 +11,11 @@ install_cmd_data "copy" install_cmd_exec "copy" <target_features> -win32_virtual_lock -win32_get_systemtime gmtime_s loadlibrary +win32_get_systemtime +win32_query_perf_counter +win32_virtual_lock </target_features> <aliases> diff --git a/src/cert/cvc/asn1_eac_tm.cpp b/src/cert/cvc/asn1_eac_tm.cpp index db5d2fbaf..12221b582 100644 --- a/src/cert/cvc/asn1_eac_tm.cpp +++ b/src/cert/cvc/asn1_eac_tm.cpp @@ -1,7 +1,7 @@ /* * EAC Time Types * (C) 2007 FlexSecure GmbH -* 2008 Jack Lloyd +* 2008-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ @@ -12,7 +12,7 @@ #include <botan/charset.h> #include <botan/parsing.h> #include <botan/internal/rounding.h> -#include <botan/time.h> +#include <botan/calendar.h> namespace Botan { @@ -22,7 +22,7 @@ SecureVector<byte> enc_two_digit(u32bit in) { SecureVector<byte> result; in %= 100; - if (in < 10) + if(in < 10) result.push_back(0x00); else { @@ -51,9 +51,10 @@ u32bit dec_two_digit(byte b1, byte b2) /* * Create an EAC_Time */ -EAC_Time::EAC_Time(u64bit timer, ASN1_Tag t) : tag(t) +EAC_Time::EAC_Time(const std::chrono::system_clock::time_point& time, + ASN1_Tag t) : tag(t) { - calendar_point cal = calendar_value(timer); + calendar_point cal = calendar_value(time); year = cal.year; month = cal.month; @@ -67,6 +68,7 @@ EAC_Time::EAC_Time(const std::string& t_spec, ASN1_Tag t) : tag(t) { set_to(t_spec); } + /* * Create an EAC_Time */ @@ -80,7 +82,7 @@ EAC_Time::EAC_Time(u32bit y, u32bit m, u32bit d, ASN1_Tag t) : */ void EAC_Time::set_to(const std::string& time_str) { - if (time_str == "") + if(time_str == "") { year = month = day = 0; return; @@ -89,28 +91,28 @@ void EAC_Time::set_to(const std::string& time_str) std::vector<std::string> params; std::string current; - for (u32bit j = 0; j != time_str.size(); ++j) + for(u32bit j = 0; j != time_str.size(); ++j) { - if (Charset::is_digit(time_str[j])) + if(Charset::is_digit(time_str[j])) current += time_str[j]; else { - if (current != "") + if(current != "") params.push_back(current); current.clear(); } } - if (current != "") + if(current != "") params.push_back(current); - if (params.size() != 3) + if(params.size() != 3) throw Invalid_Argument("Invalid time specification " + time_str); year = to_u32bit(params[0]); month = to_u32bit(params[1]); day = to_u32bit(params[2]); - if (!passes_sanity_check()) + if(!passes_sanity_check()) throw Invalid_Argument("Invalid time specification " + time_str); } @@ -129,15 +131,10 @@ void EAC_Time::encode_into(DER_Encoder& der) const */ std::string EAC_Time::as_string() const { - if (time_is_set() == false) + if(time_is_set() == false) throw Invalid_State("EAC_Time::as_string: No time set"); - std::string asn1rep; - asn1rep = to_string(year, 2); - - asn1rep += to_string(month, 2) + to_string(day, 2); - - return asn1rep; + return std::to_string(year * 10000 + month * 100 + day); } /* @@ -153,15 +150,14 @@ bool EAC_Time::time_is_set() const */ std::string EAC_Time::readable_string() const { - if (time_is_set() == false) + if(time_is_set() == false) throw Invalid_State("EAC_Time::readable_string: No time set"); - std::string readable; - readable += to_string(year, 2) + "/"; - readable += to_string(month, 2) + "/"; - readable += to_string(day, 2) + " "; + std::string output(11, 0); - return readable; + std::sprintf(&output[0], "%04d/%02d/%02d", year, month, day); + + return output; } /* @@ -169,11 +165,11 @@ std::string EAC_Time::readable_string() const */ bool EAC_Time::passes_sanity_check() const { - if (year < 2000 || year > 2099) + if(year < 2000 || year > 2099) return false; - if (month == 0 || month > 12) + if(month == 0 || month > 12) return false; - if (day == 0 || day > 31) + if(day == 0 || day > 31) return false; return true; @@ -182,11 +178,11 @@ bool EAC_Time::passes_sanity_check() const /* * modification functions */ - void EAC_Time::add_years(u32bit years) { year += years; } + void EAC_Time::add_months(u32bit months) { year += months/12; @@ -198,23 +194,22 @@ void EAC_Time::add_months(u32bit months) } } - /* * Compare this time against another */ s32bit EAC_Time::cmp(const EAC_Time& other) const { - if (time_is_set() == false) + if(time_is_set() == false) throw Invalid_State("EAC_Time::cmp: No time set"); const s32bit EARLIER = -1, LATER = 1, SAME_TIME = 0; - if (year < other.year) return EARLIER; - if (year > other.year) return LATER; - if (month < other.month) return EARLIER; - if (month > other.month) return LATER; - if (day < other.day) return EARLIER; - if (day > other.day) return LATER; + if(year < other.year) return EARLIER; + if(year > other.year) return LATER; + if(month < other.month) return EARLIER; + if(month > other.month) return LATER; + if(day < other.day) return EARLIER; + if(day > other.day) return LATER; return SAME_TIME; } @@ -283,21 +278,6 @@ void EAC_Time::decode_from(BER_Decoder& source) } -u32bit EAC_Time::get_year() const - { - return year; - } - -u32bit EAC_Time::get_month() const - { - return month; - } - -u32bit EAC_Time::get_day() const - { - return day; - } - /* * make the value an octet string for encoding */ @@ -310,34 +290,4 @@ SecureVector<byte> EAC_Time::encoded_eac_time() const return result; } -ASN1_Ced::ASN1_Ced(std::string const& str) : - EAC_Time(str, ASN1_Tag(37)) - {} - -ASN1_Ced::ASN1_Ced(u64bit val) : - EAC_Time(val, ASN1_Tag(37)) - {} - -ASN1_Ced::ASN1_Ced(EAC_Time const& other) : - EAC_Time(other.get_year(), - other.get_month(), - other.get_day(), - ASN1_Tag(37)) - {} - -ASN1_Cex::ASN1_Cex(std::string const& str) : - EAC_Time(str, ASN1_Tag(36)) - {} - -ASN1_Cex::ASN1_Cex(u64bit val) : - EAC_Time(val, ASN1_Tag(36)) - {} - -ASN1_Cex::ASN1_Cex(EAC_Time const& other) : - EAC_Time(other.get_year(), - other.get_month(), - other.get_day(), - ASN1_Tag(36)) - {} - } diff --git a/src/cert/cvc/cvc_self.cpp b/src/cert/cvc/cvc_self.cpp index 662a1d2be..61a1e7b64 100644 --- a/src/cert/cvc/cvc_self.cpp +++ b/src/cert/cvc/cvc_self.cpp @@ -8,7 +8,6 @@ #include <botan/cvc_self.h> #include <botan/ecc_key.h> #include <botan/point_gfp.h> -#include <botan/time.h> #include <botan/oids.h> #include <sstream> #include <memory> @@ -164,6 +163,7 @@ EAC1_1_ADO create_ado_req(Private_Key const& key, { throw Invalid_Argument("CVC_EAC::create_self_signed_cert(): unsupported key type"); } + std::string padding_and_hash = padding_and_hash_from_oid(req.signature_algorithm().oid); PK_Signer signer(*priv_key, padding_and_hash); SecureVector<byte> tbs_bits = req.BER_encode(); @@ -193,9 +193,8 @@ EAC1_1_CVC create_cvca(Private_Key const& key, } EAC1_1_CVC_Options opts; opts.car = car; - const u64bit current_time = system_time(); - opts.ced = ASN1_Ced(current_time); + opts.ced = ASN1_Ced(std::chrono::system_clock::now()); opts.cex = ASN1_Cex(opts.ced); opts.cex.add_months(cvca_validity_months); opts.holder_auth_templ = (CVCA | (iris * IRIS) | (fingerpr * FINGERPRINT)); @@ -210,12 +209,12 @@ EAC1_1_CVC link_cvca(EAC1_1_CVC const& signer, EAC1_1_CVC const& signee, RandomNumberGenerator& rng) { - ECDSA_PrivateKey const* priv_key = dynamic_cast<ECDSA_PrivateKey const*>(&key); + const ECDSA_PrivateKey* priv_key = dynamic_cast<ECDSA_PrivateKey const*>(&key); + if (priv_key == 0) - { - throw Invalid_Argument("CVC_EAC::create_self_signed_cert(): unsupported key type"); - } - ASN1_Ced ced(system_time()); + throw Invalid_Argument("link_cvca(): unsupported key type"); + + ASN1_Ced ced(std::chrono::system_clock::now()); ASN1_Cex cex(signee.get_cex()); if (*static_cast<EAC_Time*>(&ced) > *static_cast<EAC_Time*>(&cex)) { @@ -232,7 +231,7 @@ EAC1_1_CVC link_cvca(EAC1_1_CVC const& signer, AlgorithmIdentifier sig_algo = signer.signature_algorithm(); std::string padding_and_hash = padding_and_hash_from_oid(sig_algo.oid); PK_Signer pk_signer(*priv_key, padding_and_hash); - std::auto_ptr<Public_Key> pk(signee.subject_public_key()); + std::unique_ptr<Public_Key> pk(signee.subject_public_key()); ECDSA_PublicKey* subj_pk = dynamic_cast<ECDSA_PublicKey*>(pk.get()); subj_pk->set_parameter_encoding(EC_DOMPAR_ENC_EXPLICIT); @@ -262,13 +261,19 @@ EAC1_1_CVC sign_request(EAC1_1_CVC const& signer_cert, throw Invalid_Argument("CVC_EAC::create_self_signed_cert(): unsupported key type"); } std::string chr_str = signee.get_chr().value(); - chr_str += to_string(seqnr, seqnr_len); + + std::string seqnr_string = std::to_string(seqnr); + + while(seqnr_string.size() < seqnr_len) + seqnr_string = '0' + seqnr_string; + + chr_str += seqnr_string; ASN1_Chr chr(chr_str); std::string padding_and_hash = padding_and_hash_from_oid(signee.signature_algorithm().oid); PK_Signer pk_signer(*priv_key, padding_and_hash); - std::auto_ptr<Public_Key> pk(signee.subject_public_key()); + std::unique_ptr<Public_Key> pk(signee.subject_public_key()); ECDSA_PublicKey* subj_pk = dynamic_cast<ECDSA_PublicKey*>(pk.get()); - std::auto_ptr<Public_Key> signer_pk(signer_cert.subject_public_key()); + std::unique_ptr<Public_Key> signer_pk(signer_cert.subject_public_key()); // for the case that the domain parameters are not set... // (we use those from the signer because they must fit) @@ -277,8 +282,9 @@ EAC1_1_CVC sign_request(EAC1_1_CVC const& signer_cert, subj_pk->set_parameter_encoding(EC_DOMPAR_ENC_IMPLICITCA); AlgorithmIdentifier sig_algo(signer_cert.signature_algorithm()); - const u64bit current_time = system_time(); - ASN1_Ced ced(current_time); + + ASN1_Ced ced(std::chrono::system_clock::now()); + u32bit chat_val; u32bit chat_low = signer_cert.get_chat_value() & 0x3; // take the chat rights from signer ASN1_Cex cex(ced); diff --git a/src/cert/cvc/eac_asn_obj.h b/src/cert/cvc/eac_asn_obj.h index d0bab6fdd..54a9f1517 100644 --- a/src/cert/cvc/eac_asn_obj.h +++ b/src/cert/cvc/eac_asn_obj.h @@ -56,7 +56,6 @@ class BOTAN_DLL EAC_Time : public ASN1_Object * e.g. "2007 08 01" */ void set_to(const std::string& str); - //void set_to(const std::string&, ASN1_Tag); /** * Add the specified number of years to this. @@ -74,24 +73,28 @@ class BOTAN_DLL EAC_Time : public ASN1_Object * Get the year value of this objects. * @return year value */ - u32bit get_year() const; + u32bit get_year() const { return year; } /** * Get the month value of this objects. * @return month value */ - u32bit get_month() const; + u32bit get_month() const { return month; } /** * Get the day value of this objects. * @return day value */ - u32bit get_day() const; + u32bit get_day() const { return day; } - EAC_Time(u64bit, ASN1_Tag t = ASN1_Tag(0)); - //EAC_Time(const std::string& = ""); - EAC_Time(const std::string&, ASN1_Tag = ASN1_Tag(0)); - EAC_Time(u32bit year, u32bit month, u32bit day, ASN1_Tag = ASN1_Tag(0)); + EAC_Time(const std::chrono::system_clock::time_point& time, + ASN1_Tag tag = ASN1_Tag(0)); + + EAC_Time(const std::string& yyyy_mm_dd, + ASN1_Tag tag = ASN1_Tag(0)); + + EAC_Time(u32bit year, u32bit month, u32bit day, + ASN1_Tag tag = ASN1_Tag(0)); virtual ~EAC_Time() {} private: @@ -113,25 +116,25 @@ class BOTAN_DLL ASN1_Ced : public EAC_Time * @param str a string in the format "yyyy mm dd", * e.g. "2007 08 01" */ - ASN1_Ced(std::string const& str = ""); + ASN1_Ced(const std::string& str = "") : + EAC_Time(str, ASN1_Tag(37)) {} /** - * Construct a CED from a timer value. - * @param time the number of seconds elapsed midnight, 1st - * January 1970 GMT (or 7pm, 31st December 1969 EST) up to the - * desired date + * Construct a CED from a time point */ - ASN1_Ced(u64bit time); + ASN1_Ced(const std::chrono::system_clock::time_point& time) : + EAC_Time(time, ASN1_Tag(37)) {} /** * Copy constructor (for general EAC_Time objects). * @param other the object to copy from */ - ASN1_Ced(EAC_Time const& other); - //ASN1_Ced(ASN1_Cex const& cex); + ASN1_Ced(const EAC_Time& other) : + EAC_Time(other.get_year(), other.get_month(), other.get_day(), + ASN1_Tag(37)) + {} }; - /** * This class represents CVC CEXs. Only limited sanity checks of * the inputted date value are performed. @@ -140,27 +143,20 @@ class BOTAN_DLL ASN1_Cex : public EAC_Time { public: /** - * Construct a CED from a string value. + * Construct a CEX from a string value. * @param str a string in the format "yyyy mm dd", * e.g. "2007 08 01" */ - ASN1_Cex(std::string const& str=""); + ASN1_Cex(const std::string& str = "") : + EAC_Time(str, ASN1_Tag(36)) {} - /** - * Construct a CED from a timer value. - * @param time the number of seconds elapsed - * midnight, 1st - * January 1970 GMT (or 7pm, 31st December 1969 EST) - * up to the desired date - */ - ASN1_Cex(u64bit time); + ASN1_Cex(const std::chrono::system_clock::time_point& time) : + EAC_Time(time, ASN1_Tag(36)) {} - /** - * Copy constructor (for general EAC_Time objects). - * @param other the object to copy from - */ - ASN1_Cex(EAC_Time const& other); - //ASN1_Cex(ASN1_Ced const& ced); + ASN1_Cex(const EAC_Time& other) : + EAC_Time(other.get_year(), other.get_month(), other.get_day(), + ASN1_Tag(36)) + {} }; /** diff --git a/src/cert/cvc/info.txt b/src/cert/cvc/info.txt index 33a872053..3cf759188 100644 --- a/src/cert/cvc/info.txt +++ b/src/cert/cvc/info.txt @@ -1,5 +1,4 @@ define CARD_VERIFIABLE_CERTIFICATES - load_on request <header:public> diff --git a/src/cert/pkcs10/pkcs10.cpp b/src/cert/pkcs10/pkcs10.cpp index 784318d3d..870a4d3a1 100644 --- a/src/cert/pkcs10/pkcs10.cpp +++ b/src/cert/pkcs10/pkcs10.cpp @@ -45,7 +45,7 @@ void PKCS10_Request::force_decode() cert_req_info.decode(version); if(version != 0) throw Decoding_Error("Unknown version code in PKCS #10 request: " + - to_string(version)); + std::to_string(version)); X509_DN dn_subject; cert_req_info.decode(dn_subject); diff --git a/src/cert/x509ca/x509_ca.cpp b/src/cert/x509ca/x509_ca.cpp index 40f2e3b3a..37b4f44b4 100644 --- a/src/cert/x509ca/x509_ca.cpp +++ b/src/cert/x509ca/x509_ca.cpp @@ -13,10 +13,6 @@ #include <botan/parsing.h> #include <botan/lookup.h> #include <botan/oids.h> -#include <botan/time.h> -#include <algorithm> -#include <typeinfo> -#include <iterator> #include <memory> #include <set> @@ -56,7 +52,7 @@ X509_Certificate X509_CA::sign_request(const PKCS10_Request& req, constraints = Key_Constraints(KEY_CERT_SIGN | CRL_SIGN); else { - std::auto_ptr<Public_Key> key(req.subject_public_key()); + std::unique_ptr<Public_Key> key(req.subject_public_key()); constraints = X509::find_constraints(*key, req.constraints()); } @@ -172,7 +168,8 @@ X509_CRL X509_CA::make_crl(const std::vector<CRL_Entry>& revoked, next_update = timespec_to_u32bit("7d"); // Totally stupid: ties encoding logic to the return of std::time!! - const u64bit current_time = system_time(); + auto current_time = std::chrono::system_clock::now(); + auto expire_time = current_time + std::chrono::seconds(next_update); Extensions extensions; extensions.add( @@ -185,7 +182,7 @@ X509_CRL X509_CA::make_crl(const std::vector<CRL_Entry>& revoked, .encode(ca_sig_algo) .encode(cert.issuer_dn()) .encode(X509_Time(current_time)) - .encode(X509_Time(current_time + next_update)) + .encode(X509_Time(expire_time)) .encode_if(revoked.size() > 0, DER_Encoder() .start_cons(SEQUENCE) diff --git a/src/cert/x509ca/x509_ca.h b/src/cert/x509ca/x509_ca.h index 97be6a415..7aca26d03 100644 --- a/src/cert/x509ca/x509_ca.h +++ b/src/cert/x509ca/x509_ca.h @@ -99,11 +99,11 @@ class BOTAN_DLL X509_CA const Private_Key& key, const std::string& hash_fn); + X509_CA(const X509_CA&) = delete; + X509_CA& operator=(const X509_CA&) = delete; + ~X509_CA(); private: - X509_CA(const X509_CA&) {} - X509_CA& operator=(const X509_CA&) { return (*this); } - X509_CRL make_crl(const std::vector<CRL_Entry>& entries, u32bit crl_number, u32bit next_update, RandomNumberGenerator& rng) const; diff --git a/src/cert/x509cert/x509_obj.cpp b/src/cert/x509cert/x509_obj.cpp index 13193f09c..eff8e2543 100644 --- a/src/cert/x509cert/x509_obj.cpp +++ b/src/cert/x509cert/x509_obj.cpp @@ -168,7 +168,7 @@ std::string X509_Object::hash_used_for_signature() const */ bool X509_Object::check_signature(Public_Key* pub_key) const { - std::auto_ptr<Public_Key> key(pub_key); + std::unique_ptr<Public_Key> key(pub_key); return check_signature(*key); } diff --git a/src/cert/x509cert/x509cert.cpp b/src/cert/x509cert/x509cert.cpp index 7b57f6b1c..dccb7b7be 100644 --- a/src/cert/x509cert/x509cert.cpp +++ b/src/cert/x509cert/x509cert.cpp @@ -30,12 +30,8 @@ std::vector<std::string> lookup_oids(const std::vector<std::string>& in) { std::vector<std::string> out; - std::vector<std::string>::const_iterator i = in.begin(); - while(i != in.end()) - { + for(auto i = in.begin(); i != in.end(); ++i) out.push_back(OIDS::lookup(OID(*i))); - ++i; - } return out; } @@ -87,7 +83,7 @@ void X509_Certificate::force_decode() .decode(dn_subject); if(version > 2) - throw Decoding_Error("Unknown X.509 cert version " + Botan::to_string(version)); + throw Decoding_Error("Unknown X.509 cert version " + std::to_string(version)); if(sig_algo != sig_algo_inner) throw Decoding_Error("Algorithm identifier mismatch"); @@ -459,24 +455,15 @@ std::string X509_Certificate::to_string() const */ X509_DN create_dn(const Data_Store& info) { - class DN_Matcher : public Data_Store::Matcher + auto names = info.search_for( + [](const std::string& key, const std::string&) { - public: - bool operator()(const std::string& key, const std::string&) const - { - if(key.find("X520.") != std::string::npos) - return true; - return false; - } - }; - - std::multimap<std::string, std::string> names = - info.search_with(DN_Matcher()); + return (key.find("X520.") != std::string::npos); + }); X509_DN dn; - std::multimap<std::string, std::string>::iterator i; - for(i = names.begin(); i != names.end(); ++i) + for(auto i = names.begin(); i != names.end(); ++i) dn.add_attribute(i->first, i->second); return dn; @@ -487,32 +474,18 @@ X509_DN create_dn(const Data_Store& info) */ AlternativeName create_alt_name(const Data_Store& info) { - class AltName_Matcher : public Data_Store::Matcher + auto names = info.search_for( + [](const std::string& key, const std::string&) { - public: - bool operator()(const std::string& key, const std::string&) const - { - for(size_t i = 0; i != matches.size(); ++i) - if(key.compare(matches[i]) == 0) - return true; - return false; - } - - AltName_Matcher(const std::string& match_any_of) - { - matches = split_on(match_any_of, '/'); - } - private: - std::vector<std::string> matches; - }; - - std::multimap<std::string, std::string> names = - info.search_with(AltName_Matcher("RFC822/DNS/URI/IP")); + return (key == "RFC822" || + key == "DNS" || + key == "URI" || + key == "IP"); + }); AlternativeName alt_name; - std::multimap<std::string, std::string>::iterator i; - for(i = names.begin(); i != names.end(); ++i) + for(auto i = names.begin(); i != names.end(); ++i) alt_name.add_attribute(i->first, i->second); return alt_name; diff --git a/src/cert/x509crl/crl_ent.cpp b/src/cert/x509crl/crl_ent.cpp index d566637f6..a5663e6bb 100644 --- a/src/cert/x509crl/crl_ent.cpp +++ b/src/cert/x509crl/crl_ent.cpp @@ -11,7 +11,6 @@ #include <botan/ber_dec.h> #include <botan/bigint.h> #include <botan/oids.h> -#include <botan/time.h> namespace Botan { @@ -31,7 +30,7 @@ CRL_Entry::CRL_Entry(const X509_Certificate& cert, CRL_Code why) : throw_on_unknown_critical(false) { serial = cert.serial_number(); - time = X509_Time(system_time()); + time = X509_Time(std::chrono::system_clock::now()); reason = why; } diff --git a/src/cert/x509crl/x509_crl.cpp b/src/cert/x509crl/x509_crl.cpp index 01fce4c52..72da81fce 100644 --- a/src/cert/x509crl/x509_crl.cpp +++ b/src/cert/x509crl/x509_crl.cpp @@ -44,7 +44,7 @@ void X509_CRL::force_decode() if(version != 0 && version != 1) throw X509_CRL_Error("Unknown X.509 CRL version " + - to_string(version+1)); + std::to_string(version+1)); AlgorithmIdentifier sig_algo_inner; tbs_crl.decode(sig_algo_inner); diff --git a/src/cert/x509self/x509opt.cpp b/src/cert/x509self/x509opt.cpp index 345df1fe0..8a27fdbde 100644 --- a/src/cert/x509self/x509opt.cpp +++ b/src/cert/x509self/x509opt.cpp @@ -8,7 +8,7 @@ #include <botan/x509self.h> #include <botan/oids.h> #include <botan/parsing.h> -#include <botan/time.h> +#include <chrono> namespace Botan { @@ -78,16 +78,16 @@ void X509_Cert_Options::sanity_check() const * Initialize the certificate options */ X509_Cert_Options::X509_Cert_Options(const std::string& initial_opts, - u32bit expiration_time_in_seconds) + u32bit expiration_time) { is_CA = false; path_limit = 0; constraints = NO_CONSTRAINTS; - const u64bit now = system_time(); + auto now = std::chrono::system_clock::now(); start = X509_Time(now); - end = X509_Time(now + expiration_time_in_seconds); + end = X509_Time(now + std::chrono::seconds(expiration_time)); if(initial_opts == "") return; diff --git a/src/cert/x509self/x509self.cpp b/src/cert/x509self/x509self.cpp index a2f89159f..c100ee825 100644 --- a/src/cert/x509self/x509self.cpp +++ b/src/cert/x509self/x509self.cpp @@ -54,7 +54,7 @@ X509_Certificate create_self_signed_cert(const X509_Cert_Options& opts, opts.sanity_check(); MemoryVector<byte> pub_key = X509::BER_encode(key); - std::auto_ptr<PK_Signer> signer(choose_sig_format(key, hash_fn, sig_algo)); + std::unique_ptr<PK_Signer> signer(choose_sig_format(key, hash_fn, sig_algo)); load_info(opts, subject_dn, subject_alt); Key_Constraints constraints; @@ -100,7 +100,7 @@ PKCS10_Request create_cert_req(const X509_Cert_Options& opts, opts.sanity_check(); MemoryVector<byte> pub_key = X509::BER_encode(key); - std::auto_ptr<PK_Signer> signer(choose_sig_format(key, hash_fn, sig_algo)); + std::unique_ptr<PK_Signer> signer(choose_sig_format(key, hash_fn, sig_algo)); load_info(opts, subject_dn, subject_alt); const size_t PKCS10_VERSION = 0; diff --git a/src/cert/x509store/x509stor.cpp b/src/cert/x509store/x509stor.cpp index 3fe1adf62..a635b3930 100644 --- a/src/cert/x509store/x509stor.cpp +++ b/src/cert/x509store/x509stor.cpp @@ -9,8 +9,8 @@ #include <botan/parsing.h> #include <botan/pubkey.h> #include <botan/oids.h> -#include <botan/time.h> #include <algorithm> +#include <chrono> #include <memory> namespace Botan { @@ -21,13 +21,14 @@ namespace { * Do a validity check */ s32bit validity_check(const X509_Time& start, const X509_Time& end, - u64bit current_time, u32bit slack) + const std::chrono::system_clock::time_point& now, + std::chrono::seconds slack) { const s32bit NOT_YET_VALID = -1, VALID_TIME = 0, EXPIRED = 1; - if(start.cmp(current_time + slack) > 0) + if(start.cmp(now + slack) > 0) return NOT_YET_VALID; - if(end.cmp(current_time - slack) < 0) + if(end.cmp(now - slack) < 0) return EXPIRED; return VALID_TIME; } @@ -168,7 +169,8 @@ bool X509_Store::CRL_Data::operator<(const X509_Store::CRL_Data& other) const /* * X509_Store Constructor */ -X509_Store::X509_Store(u32bit slack, u32bit cache_timeout) +X509_Store::X509_Store(std::chrono::seconds slack, + std::chrono::seconds cache_timeout) { revoked_info_valid = true; @@ -211,10 +213,11 @@ X509_Code X509_Store::validate_cert(const X509_Certificate& cert, if(chaining_result != VERIFIED) return chaining_result; - const u64bit current_time = system_time(); + auto current_time = std::chrono::system_clock::now(); s32bit time_check = validity_check(cert.start_time(), cert.end_time(), current_time, time_slack); + if(time_check < 0) return CERT_NOT_YET_VALID; else if(time_check > 0) return CERT_HAS_EXPIRED; @@ -373,7 +376,7 @@ X509_Code X509_Store::check_sig(const Cert_Info& cert_info, */ X509_Code X509_Store::check_sig(const X509_Object& object, Public_Key* key) { - std::auto_ptr<Public_Key> pub_key(key); + std::unique_ptr<Public_Key> pub_key(key); try { std::vector<std::string> sig_info = @@ -528,8 +531,10 @@ void X509_Store::add_trusted_certs(DataSource& source) */ X509_Code X509_Store::add_crl(const X509_CRL& crl) { + auto current_time = std::chrono::system_clock::now(); + s32bit time_check = validity_check(crl.this_update(), crl.next_update(), - system_time(), time_slack); + current_time, time_slack); if(time_check < 0) return CRL_NOT_YET_VALID; else if(time_check > 0) return CRL_HAS_EXPIRED; @@ -568,8 +573,7 @@ X509_Code X509_Store::add_crl(const X509_CRL& crl) revoked_info.serial = revoked_certs[j].serial_number(); revoked_info.auth_key_id = crl.authority_key_id(); - std::vector<CRL_Data>::iterator p = - std::find(revoked.begin(), revoked.end(), revoked_info); + auto p = std::find(revoked.begin(), revoked.end(), revoked_info); if(revoked_certs[j].reason_code() == REMOVE_FROM_CRL) { @@ -607,8 +611,8 @@ X509_Store::Cert_Info::Cert_Info(const X509_Certificate& c, bool t) : cert(c), trusted(t) { checked = false; + last_checked = std::chrono::system_clock::time_point::min(); result = UNKNOWN_X509_ERROR; - last_checked = 0; } /* @@ -626,9 +630,9 @@ X509_Code X509_Store::Cert_Info::verify_result() const */ void X509_Store::Cert_Info::set_result(X509_Code code) const { - result = code; - last_checked = system_time(); checked = true; + last_checked = std::chrono::system_clock::now(); + result = code; } /* @@ -642,16 +646,16 @@ bool X509_Store::Cert_Info::is_trusted() const /* * Check if this certificate has been verified */ -bool X509_Store::Cert_Info::is_verified(u32bit timeout) const +bool X509_Store::Cert_Info::is_verified(std::chrono::seconds timeout) const { if(!checked) return false; if(result != VERIFIED && result != CERT_NOT_YET_VALID) return true; - const u64bit current_time = system_time(); + auto now = std::chrono::system_clock::now(); - if(current_time > last_checked + timeout) + if(now > last_checked + timeout) checked = false; return checked; diff --git a/src/cert/x509store/x509stor.h b/src/cert/x509store/x509stor.h index b4b50022c..532db6190 100644 --- a/src/cert/x509store/x509stor.h +++ b/src/cert/x509store/x509stor.h @@ -11,6 +11,7 @@ #include <botan/x509cert.h> #include <botan/x509_crl.h> #include <botan/certstor.h> +#include <functional> namespace Botan { @@ -70,14 +71,18 @@ class BOTAN_DLL X509_Store void add_new_certstore(Certificate_Store*); - X509_Store(u32bit time_slack = 24*60*60, - u32bit cache_results = 30*60); + X509_Store& operator=(const X509_Store&) = delete; + + /** + * @param slack the slack in checking validity times against current clock + * @param cache how long to cache validation results before rechecking + */ + X509_Store(std::chrono::seconds slack = std::chrono::seconds(24*60*60), + std::chrono::seconds cache = std::chrono::seconds(30*60)); X509_Store(const X509_Store&); ~X509_Store(); private: - X509_Store& operator=(const X509_Store&) { return (*this); } - class BOTAN_DLL CRL_Data { public: @@ -91,7 +96,7 @@ class BOTAN_DLL X509_Store class BOTAN_DLL Cert_Info { public: - bool is_verified(u32bit timeout) const; + bool is_verified(std::chrono::seconds cache_timeout) const; bool is_trusted() const; X509_Code verify_result() const; void set_result(X509_Code) const; @@ -102,7 +107,7 @@ class BOTAN_DLL X509_Store private: mutable bool checked; mutable X509_Code result; - mutable u64bit last_checked; + mutable std::chrono::system_clock::time_point last_checked; }; static X509_Code check_sig(const X509_Object&, Public_Key*); @@ -122,7 +127,8 @@ class BOTAN_DLL X509_Store std::vector<Cert_Info> certs; std::vector<CRL_Data> revoked; std::vector<Certificate_Store*> stores; - u32bit time_slack, validation_cache_timeout; + + std::chrono::seconds time_slack, validation_cache_timeout; mutable bool revoked_info_valid; }; diff --git a/src/cms/cms_dalg.cpp b/src/cms/cms_dalg.cpp index 2935f3070..9fb5a29f2 100644 --- a/src/cms/cms_dalg.cpp +++ b/src/cms/cms_dalg.cpp @@ -28,7 +28,7 @@ SecureVector<byte> hash_of(const SecureVector<byte>& content, Algorithm_Factory& af = global_state().algorithm_factory(); - std::auto_ptr<HashFunction> hash_fn(af.make_hash_function(hash_name)); + std::unique_ptr<HashFunction> hash_fn(af.make_hash_function(hash_name)); return hash_fn->process(content); } @@ -51,10 +51,11 @@ std::vector<X509_Certificate> get_cert(BER_Decoder& signer_info, iands.decode(issuer); iands.decode(serial); - found = store.get_certs(IandS_Match(issuer, BigInt::encode(serial))); + found = store.get_certs( + X509_Store_Search::by_issuer_and_serial(issuer, serial)); } else if(id.type_tag == 0 && id.class_tag == CONSTRUCTED) - found = store.get_certs(SKID_Match(id.value)); + found = store.get_certs(X509_Store_Search::by_skid(id.value)); else throw Decoding_Error("CMS: Unknown tag for cert identifier"); #endif diff --git a/src/cms/cms_ealg.cpp b/src/cms/cms_ealg.cpp index 4aee8afd8..2acffa5f7 100644 --- a/src/cms/cms_ealg.cpp +++ b/src/cms/cms_ealg.cpp @@ -57,7 +57,7 @@ SecureVector<byte> hash_of(const SecureVector<byte>& content, const std::string& hash_name) { Algorithm_Factory& af = global_state().algorithm_factory(); - std::auto_ptr<HashFunction> hash_fn(af.make_hash_function(hash_name)); + std::unique_ptr<HashFunction> hash_fn(af.make_hash_function(hash_name)); return hash_fn->process(content); } @@ -96,7 +96,7 @@ void CMS_Encoder::encrypt(RandomNumberGenerator& rng, { const std::string cipher = choose_algo(user_cipher, "TripleDES"); - std::auto_ptr<Public_Key> key(to.subject_public_key()); + std::unique_ptr<Public_Key> key(to.subject_public_key()); const std::string algo = key->algo_name(); Key_Constraints constraints = to.constraints(); diff --git a/src/constructs/rfc3394/rfc3394.cpp b/src/constructs/rfc3394/rfc3394.cpp index b000873fd..db6420ff3 100644 --- a/src/constructs/rfc3394/rfc3394.cpp +++ b/src/constructs/rfc3394/rfc3394.cpp @@ -39,7 +39,7 @@ SecureVector<byte> rfc3394_keywrap(const MemoryRegion<byte>& key, if(key.size() % 8 != 0) throw std::invalid_argument("Bad input key size for NIST key wrap"); - std::auto_ptr<BlockCipher> aes(make_aes(kek.length(), af)); + std::unique_ptr<BlockCipher> aes(make_aes(kek.length(), af)); aes->set_key(kek); const size_t n = key.size() / 8; @@ -81,7 +81,7 @@ SecureVector<byte> rfc3394_keyunwrap(const MemoryRegion<byte>& key, if(key.size() < 16 || key.size() % 8 != 0) throw std::invalid_argument("Bad input key size for NIST key unwrap"); - std::auto_ptr<BlockCipher> aes(make_aes(kek.length(), af)); + std::unique_ptr<BlockCipher> aes(make_aes(kek.length(), af)); aes->set_key(kek); const size_t n = (key.size() - 8) / 8; diff --git a/src/constructs/srp6/srp6.cpp b/src/constructs/srp6/srp6.cpp index 287f0bdfb..b2785e7f6 100644 --- a/src/constructs/srp6/srp6.cpp +++ b/src/constructs/srp6/srp6.cpp @@ -20,7 +20,7 @@ BigInt hash_seq(const std::string& hash_id, const BigInt& in1, const BigInt& in2) { - std::auto_ptr<HashFunction> hash_fn( + std::unique_ptr<HashFunction> hash_fn( global_state().algorithm_factory().make_hash_function(hash_id)); hash_fn->update(BigInt::encode_1363(in1, pad_to)); @@ -35,7 +35,7 @@ BigInt hash_seq(const std::string& hash_id, const BigInt& in2, const BigInt& in3) { - std::auto_ptr<HashFunction> hash_fn( + std::unique_ptr<HashFunction> hash_fn( global_state().algorithm_factory().make_hash_function(hash_id)); hash_fn->update(BigInt::encode_1363(in1, pad_to)); @@ -50,7 +50,7 @@ BigInt compute_x(const std::string& hash_id, const std::string& password, const MemoryRegion<byte>& salt) { - std::auto_ptr<HashFunction> hash_fn( + std::unique_ptr<HashFunction> hash_fn( global_state().algorithm_factory().make_hash_function(hash_id)); hash_fn->update(identifier); diff --git a/src/constructs/tss/tss.cpp b/src/constructs/tss/tss.cpp index d0a18f534..cc34216f3 100644 --- a/src/constructs/tss/tss.cpp +++ b/src/constructs/tss/tss.cpp @@ -205,7 +205,7 @@ RTSS_Share::reconstruct(const std::vector<RTSS_Share>& shares) byte hash_id = shares[0].contents[16]; - std::auto_ptr<HashFunction> hash(get_rtss_hash_by_id(hash_id)); + std::unique_ptr<HashFunction> hash(get_rtss_hash_by_id(hash_id)); if(shares[0].size() != secret_len + hash->output_length() + RTSS_HEADER_SIZE + 1) throw Decoding_Error("Bad RTSS length field in header"); diff --git a/src/engine/dyn_engine/dyn_engine.cpp b/src/engine/dyn_engine/dyn_engine.cpp index b76544d0f..2d8dbae3b 100644 --- a/src/engine/dyn_engine/dyn_engine.cpp +++ b/src/engine/dyn_engine/dyn_engine.cpp @@ -35,7 +35,7 @@ Dynamically_Loaded_Engine::Dynamically_Loaded_Engine( if(mod_version != 20101003) throw std::runtime_error("Incompatible version in " + library_path + " of " + - to_string(mod_version)); + std::to_string(mod_version)); creator_func creator = lib->resolve<creator_func>("create_engine"); diff --git a/src/engine/openssl/ossl_arc4.cpp b/src/engine/openssl/ossl_arc4.cpp index 0b1f7f1f3..799206ce1 100644 --- a/src/engine/openssl/ossl_arc4.cpp +++ b/src/engine/openssl/ossl_arc4.cpp @@ -46,7 +46,7 @@ std::string ARC4_OpenSSL::name() const { if(SKIP == 0) return "ARC4"; if(SKIP == 256) return "MARK-4"; - else return "RC4_skip(" + to_string(SKIP) + ")"; + else return "RC4_skip(" + std::to_string(SKIP) + ")"; } /* diff --git a/src/entropy/cryptoapi_rng/es_capi.cpp b/src/entropy/cryptoapi_rng/es_capi.cpp index d3d076641..c9069ce65 100644 --- a/src/entropy/cryptoapi_rng/es_capi.cpp +++ b/src/entropy/cryptoapi_rng/es_capi.cpp @@ -65,7 +65,7 @@ void Win32_CAPI_EntropySource::poll(Entropy_Accumulator& accum) if(got) { - accum.add(&io_buffer[0], io_buffer.size(), 8); + accum.add(&io_buffer[0], io_buffer.size(), 6); break; } } diff --git a/src/entropy/dev_random/dev_random.cpp b/src/entropy/dev_random/dev_random.cpp index d14ae43ae..9e4f0b373 100644 --- a/src/entropy/dev_random/dev_random.cpp +++ b/src/entropy/dev_random/dev_random.cpp @@ -105,9 +105,12 @@ Device_EntropySource::~Device_EntropySource() */ void Device_EntropySource::poll(Entropy_Accumulator& accum) { - size_t go_get = std::min<size_t>(accum.desired_remaining_bits() / 8, 48); + const size_t ENTROPY_BITS_PER_BYTE = 7; - size_t read_wait_ms = std::max<size_t>(go_get, 1000); + const size_t go_get = std::min<size_t>( + accum.desired_remaining_bits() / ENTROPY_BITS_PER_BYTE, 32); + + const size_t read_wait_ms = std::max<size_t>(go_get, 100); MemoryRegion<byte>& io_buffer = accum.get_io_buffer(go_get); for(size_t i = 0; i != devices.size(); ++i) @@ -117,7 +120,7 @@ void Device_EntropySource::poll(Entropy_Accumulator& accum) if(got) { - accum.add(&io_buffer[0], got, 8); + accum.add(&io_buffer[0], got, ENTROPY_BITS_PER_BYTE); break; } } diff --git a/src/entropy/egd/es_egd.cpp b/src/entropy/egd/es_egd.cpp index b2b629930..e0ebf9509 100644 --- a/src/entropy/egd/es_egd.cpp +++ b/src/entropy/egd/es_egd.cpp @@ -147,7 +147,7 @@ void EGD_EntropySource::poll(Entropy_Accumulator& accum) if(got) { - accum.add(&io_buffer[0], got, 8); + accum.add(&io_buffer[0], got, 6); break; } } diff --git a/src/entropy/hres_timer/hres_timer.cpp b/src/entropy/hres_timer/hres_timer.cpp index dd1fc6f7c..c6b31d996 100644 --- a/src/entropy/hres_timer/hres_timer.cpp +++ b/src/entropy/hres_timer/hres_timer.cpp @@ -7,9 +7,8 @@ #include <botan/internal/hres_timer.h> #include <botan/cpuid.h> -#include <botan/time.h> -#if defined(BOTAN_TARGET_OS_IS_WINDOWS) +#if defined(BOTAN_TARGET_OS_HAS_QUERY_PERF_COUNTER) #include <windows.h> #endif @@ -20,8 +19,7 @@ namespace Botan { */ void High_Resolution_Timestamp::poll(Entropy_Accumulator& accum) { - // If Windows, grab the Performance Counter (usually TSC or PIT) -#if defined(BOTAN_TARGET_OS_IS_WINDOWS) +#if defined(BOTAN_TARGET_OS_HAS_QUERY_PERF_COUNTER) { LARGE_INTEGER tv; ::QueryPerformanceCounter(&tv); diff --git a/src/entropy/proc_walk/es_ftw.cpp b/src/entropy/proc_walk/es_ftw.cpp index 5d58f9869..407034891 100644 --- a/src/entropy/proc_walk/es_ftw.cpp +++ b/src/entropy/proc_walk/es_ftw.cpp @@ -1,6 +1,6 @@ /* * FTW EntropySource -* (C) 1999-2008 Jack Lloyd +* (C) 1999-2008,2012 Jack Lloyd * * Distributed under the terms of the Botan license */ @@ -41,60 +41,79 @@ namespace { class Directory_Walker : public File_Descriptor_Source { public: - Directory_Walker(const std::string& root) { add_directory(root); } - ~Directory_Walker(); + Directory_Walker(const std::string& root) : + m_cur_dir(std::make_pair<DIR*, std::string>(0, "")) + { + if(DIR* root_dir = ::opendir(root.c_str())) + m_cur_dir = std::make_pair(root_dir, root); + } + + ~Directory_Walker() + { + if(m_cur_dir.first) + ::closedir(m_cur_dir.first); + } int next_fd(); private: - void add_directory(const std::string&); + void add_directory(const std::string& dirname) + { + m_dirlist.push_back(dirname); + } - std::deque<std::pair<DIR*, std::string> > dirs; - }; + std::pair<struct dirent*, std::string> get_next_dirent(); -void Directory_Walker::add_directory(const std::string& dirname) - { - DIR* dir = ::opendir(dirname.c_str()); - if(dir) - dirs.push_back(std::make_pair(dir, dirname)); - } + std::pair<DIR*, std::string> m_cur_dir; + std::deque<std::string> m_dirlist; + }; -Directory_Walker::~Directory_Walker() +std::pair<struct dirent*, std::string> Directory_Walker::get_next_dirent() { - while(dirs.size()) + while(m_cur_dir.first) { - ::closedir(dirs[0].first); - dirs.pop_front(); + if(struct dirent* dir = ::readdir(m_cur_dir.first)) + return std::make_pair(dir, m_cur_dir.second); + + ::closedir(m_cur_dir.first); + m_cur_dir = std::make_pair<DIR*, std::string>(0, ""); + + while(!m_dirlist.empty() && m_cur_dir.first == 0) + { + const std::string next_dir_name = m_dirlist[0]; + m_dirlist.pop_front(); + + if(DIR* next_dir = ::opendir(next_dir_name.c_str())) + m_cur_dir = std::make_pair(next_dir, next_dir_name); + } } + + return std::make_pair<struct dirent*, std::string>(0, ""); // nothing left } int Directory_Walker::next_fd() { - while(dirs.size()) + while(true) { - std::pair<DIR*, std::string> dirinfo = dirs[0]; + std::pair<struct dirent*, std::string> entry = get_next_dirent(); - struct dirent* entry = ::readdir(dirinfo.first); + if(!entry.first) + break; // no more dirs - if(!entry) - { - ::closedir(dirinfo.first); - dirs.pop_front(); - continue; - } - - const std::string filename = entry->d_name; + const std::string filename = entry.first->d_name; if(filename == "." || filename == "..") continue; - const std::string full_path = dirinfo.second + '/' + filename; + const std::string full_path = entry.second + '/' + filename; struct stat stat_buf; if(::lstat(full_path.c_str(), &stat_buf) == -1) continue; if(S_ISDIR(stat_buf.st_mode)) + { add_directory(full_path); + } else if(S_ISREG(stat_buf.st_mode) && (stat_buf.st_mode & S_IROTH)) { int fd = ::open(full_path.c_str(), O_RDONLY | O_NOCTTY); @@ -127,12 +146,12 @@ FTW_EntropySource::~FTW_EntropySource() void FTW_EntropySource::poll(Entropy_Accumulator& accum) { - const size_t MAX_FILES_READ_PER_POLL = 1024; + const size_t MAX_FILES_READ_PER_POLL = 2048; if(!dir) dir = new Directory_Walker(path); - MemoryRegion<byte>& io_buffer = accum.get_io_buffer(128); + MemoryRegion<byte>& io_buffer = accum.get_io_buffer(4096); for(size_t i = 0; i != MAX_FILES_READ_PER_POLL; ++i) { @@ -150,7 +169,7 @@ void FTW_EntropySource::poll(Entropy_Accumulator& accum) ::close(fd); if(got > 0) - accum.add(&io_buffer[0], got, .01); + accum.add(&io_buffer[0], got, .001); if(accum.polling_goal_achieved()) break; diff --git a/src/filters/bzip2/bzip2.cpp b/src/filters/bzip2/bzip2.cpp index a291c1173..18a53558c 100644 --- a/src/filters/bzip2/bzip2.cpp +++ b/src/filters/bzip2/bzip2.cpp @@ -48,7 +48,7 @@ void* bzip_malloc(void* info_ptr, int n, int size) void bzip_free(void* info_ptr, void* ptr) { Bzip_Alloc_Info* info = static_cast<Bzip_Alloc_Info*>(info_ptr); - std::map<void*, size_t>::const_iterator i = info->current_allocs.find(ptr); + auto i = info->current_allocs.find(ptr); if(i == info->current_allocs.end()) throw Invalid_Argument("bzip_free: Got pointer not allocated by us"); info->alloc->deallocate(ptr, i->second); diff --git a/src/filters/data_snk.h b/src/filters/data_snk.h index e31cb9d28..6b9da0b4d 100644 --- a/src/filters/data_snk.h +++ b/src/filters/data_snk.h @@ -22,9 +22,9 @@ class BOTAN_DLL DataSink : public Filter bool attachable() { return false; } DataSink() {} virtual ~DataSink() {} - private: - DataSink& operator=(const DataSink&) { return (*this); } - DataSink(const DataSink&); + + DataSink& operator=(const DataSink&) = delete; + DataSink(const DataSink&) = delete; }; /** diff --git a/src/filters/data_src.h b/src/filters/data_src.h index a274de8e2..d2d51fe23 100644 --- a/src/filters/data_src.h +++ b/src/filters/data_src.h @@ -81,9 +81,8 @@ class BOTAN_DLL DataSource DataSource() {} virtual ~DataSource() {} - private: - DataSource& operator=(const DataSource&) { return (*this); } - DataSource(const DataSource&); + DataSource& operator=(const DataSource&) = delete; + DataSource(const DataSource&) = delete; }; /** diff --git a/src/filters/filter.h b/src/filters/filter.h index 962b2816e..b62846075 100644 --- a/src/filters/filter.h +++ b/src/filters/filter.h @@ -78,9 +78,6 @@ class BOTAN_DLL Filter Filter(); private: - Filter(const Filter&) {} - Filter& operator=(const Filter&) { return (*this); } - /** * Start a new message in *this and all following filters. Only for * internal use, not intended for use in client applications. @@ -96,6 +93,9 @@ class BOTAN_DLL Filter friend class Pipe; friend class Fanout_Filter; + Filter(const Filter&) = delete; + Filter& operator=(const Filter&) = delete; + size_t total_ports() const; size_t current_port() const { return port_num; } diff --git a/src/filters/modes/cfb/cfb.cpp b/src/filters/modes/cfb/cfb.cpp index 8f7471c98..22d4a9c2e 100644 --- a/src/filters/modes/cfb/cfb.cpp +++ b/src/filters/modes/cfb/cfb.cpp @@ -26,7 +26,7 @@ CFB_Encryption::CFB_Encryption(BlockCipher* ciph, size_t fback_bits) if(feedback == 0 || fback_bits % 8 != 0 || feedback > cipher->block_size()) throw Invalid_Argument("CFB_Encryption: Invalid feedback size " + - to_string(fback_bits)); + std::to_string(fback_bits)); } /* @@ -46,7 +46,7 @@ CFB_Encryption::CFB_Encryption(BlockCipher* ciph, if(feedback == 0 || fback_bits % 8 != 0 || feedback > cipher->block_size()) throw Invalid_Argument("CFB_Encryption: Invalid feedback size " + - to_string(fback_bits)); + std::to_string(fback_bits)); set_key(key); set_iv(iv); @@ -103,7 +103,7 @@ CFB_Decryption::CFB_Decryption(BlockCipher* ciph, size_t fback_bits) if(feedback == 0 || fback_bits % 8 != 0 || feedback > cipher->block_size()) throw Invalid_Argument("CFB_Decryption: Invalid feedback size " + - to_string(fback_bits)); + std::to_string(fback_bits)); } /* @@ -123,7 +123,7 @@ CFB_Decryption::CFB_Decryption(BlockCipher* ciph, if(feedback == 0 || fback_bits % 8 != 0 || feedback > cipher->block_size()) throw Invalid_Argument("CFB_Decryption: Invalid feedback size " + - to_string(fback_bits)); + std::to_string(fback_bits)); set_key(key); set_iv(iv); diff --git a/src/filters/modes/eax/eax.cpp b/src/filters/modes/eax/eax.cpp index 6d6d9ec18..791286cc6 100644 --- a/src/filters/modes/eax/eax.cpp +++ b/src/filters/modes/eax/eax.cpp @@ -45,7 +45,7 @@ EAX_Base::EAX_Base(BlockCipher* cipher, size_t tag_size) : ctr = new CTR_BE(cipher); // takes ownership if(tag_size % 8 != 0 || TAG_SIZE == 0 || TAG_SIZE > cmac->output_length()) - throw Invalid_Argument(name() + ": Bad tag size " + to_string(tag_size)); + throw Invalid_Argument(name() + ": Bad tag size " + std::to_string(tag_size)); } /* diff --git a/src/filters/pipe.cpp b/src/filters/pipe.cpp index 3c3b5e6a4..53bab3e94 100644 --- a/src/filters/pipe.cpp +++ b/src/filters/pipe.cpp @@ -43,11 +43,12 @@ Pipe::Pipe(Filter* f1, Filter* f2, Filter* f3, Filter* f4) /* * Pipe Constructor */ -Pipe::Pipe(Filter* filter_array[], size_t count) +Pipe::Pipe(std::initializer_list<Filter*> args) { init(); - for(size_t j = 0; j != count; ++j) - append(filter_array[j]); + + for(auto i = args.begin(); i != args.end(); ++i) + append(*i); } /* diff --git a/src/filters/pipe.h b/src/filters/pipe.h index e5cb5f445..6df518d3e 100644 --- a/src/filters/pipe.h +++ b/src/filters/pipe.h @@ -11,6 +11,7 @@ #include <botan/data_src.h> #include <botan/filter.h> #include <botan/exceptn.h> +#include <initializer_list> #include <iosfwd> namespace Botan { @@ -42,7 +43,7 @@ class BOTAN_DLL Pipe : public DataSource */ Invalid_Message_Number(const std::string& where, message_id msg) : Invalid_Argument("Pipe::" + where + ": Invalid message number " + - to_string(msg)) + std::to_string(msg)) {} }; @@ -264,15 +265,16 @@ class BOTAN_DLL Pipe : public DataSource Pipe(Filter* = 0, Filter* = 0, Filter* = 0, Filter* = 0); /** - * Construct a Pipe from range of filters passed as an array + * Construct a Pipe from a list of filters * @param filters the set of filters to use - * @param count the number of elements in filters */ - Pipe(Filter* filters[], size_t count); + Pipe(std::initializer_list<Filter*> filters); + + Pipe(const Pipe&) = delete; + Pipe& operator=(const Pipe&) = delete; + ~Pipe(); private: - Pipe(const Pipe&) : DataSource() {} - Pipe& operator=(const Pipe&) { return (*this); } void init(); void destruct(Filter*); void find_endpoints(Filter*); diff --git a/src/filters/zlib/zlib.cpp b/src/filters/zlib/zlib.cpp index 517660e3b..169146826 100644 --- a/src/filters/zlib/zlib.cpp +++ b/src/filters/zlib/zlib.cpp @@ -47,7 +47,7 @@ void* zlib_malloc(void* info_ptr, unsigned int n, unsigned int size) void zlib_free(void* info_ptr, void* ptr) { Zlib_Alloc_Info* info = static_cast<Zlib_Alloc_Info*>(info_ptr); - std::map<void*, size_t>::const_iterator i = info->current_allocs.find(ptr); + auto i = info->current_allocs.find(ptr); if(i == info->current_allocs.end()) throw Invalid_Argument("zlib_free: Got pointer not allocated by us"); info->alloc->deallocate(ptr, i->second); diff --git a/src/hash/keccak/keccak.cpp b/src/hash/keccak/keccak.cpp index 922167b61..107055509 100644 --- a/src/hash/keccak/keccak.cpp +++ b/src/hash/keccak/keccak.cpp @@ -112,12 +112,12 @@ Keccak_1600::Keccak_1600(size_t output_bits) : if(output_bits != 224 && output_bits != 256 && output_bits != 384 && output_bits != 512) throw Invalid_Argument("Keccak_1600: Invalid output length " + - to_string(output_bits)); + std::to_string(output_bits)); } std::string Keccak_1600::name() const { - return "Keccak-1600(" + to_string(output_bits) + ")"; + return "Keccak-1600(" + std::to_string(output_bits) + ")"; } HashFunction* Keccak_1600::clone() const diff --git a/src/hash/par_hash/par_hash.cpp b/src/hash/par_hash/par_hash.cpp index 328be6a11..df47780ef 100644 --- a/src/hash/par_hash/par_hash.cpp +++ b/src/hash/par_hash/par_hash.cpp @@ -1,11 +1,12 @@ /* * Parallel -* (C) 1999-2007 Jack Lloyd +* (C) 1999-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/par_hash.h> +#include <botan/parsing.h> namespace Botan { @@ -14,20 +15,21 @@ namespace Botan { */ void Parallel::add_data(const byte input[], size_t length) { - for(size_t i = 0; i != hashes.size(); ++i) - hashes[i]->update(input, length); + for(auto hash : hashes) + hash->update(input, length); } /* * Finalize the hash */ -void Parallel::final_result(byte hash[]) +void Parallel::final_result(byte out[]) { - size_t offset = 0; - for(size_t i = 0; i != hashes.size(); ++i) + u32bit offset = 0; + + for(auto hash : hashes) { - hashes[i]->final(hash + offset); - offset += hashes[i]->output_length(); + hash->final(out + offset); + offset += hash->output_length(); } } @@ -37,8 +39,9 @@ void Parallel::final_result(byte hash[]) size_t Parallel::output_length() const { size_t sum = 0; - for(size_t i = 0; i != hashes.size(); ++i) - sum += hashes[i]->output_length(); + + for(auto hash : hashes) + sum += hash->output_length(); return sum; } @@ -47,14 +50,12 @@ size_t Parallel::output_length() const */ std::string Parallel::name() const { - std::string hash_names; - for(size_t i = 0; i != hashes.size(); ++i) - { - if(i) - hash_names += ','; - hash_names += hashes[i]->name(); - } - return "Parallel(" + hash_names + ")"; + std::vector<std::string> names; + + for(auto hash : hashes) + names.push_back(hash->name()); + + return "Parallel(" + string_join(names, ',') + ")"; } /* @@ -63,8 +64,10 @@ std::string Parallel::name() const HashFunction* Parallel::clone() const { std::vector<HashFunction*> hash_copies; - for(size_t i = 0; i != hashes.size(); ++i) - hash_copies.push_back(hashes[i]->clone()); + + for(auto hash : hashes) + hash_copies.push_back(hash->clone()); + return new Parallel(hash_copies); } @@ -73,8 +76,8 @@ HashFunction* Parallel::clone() const */ void Parallel::clear() { - for(size_t i = 0; i != hashes.size(); ++i) - hashes[i]->clear(); + for(auto hash : hashes) + hash->clear(); } /* @@ -90,8 +93,8 @@ Parallel::Parallel(const std::vector<HashFunction*>& hash_in) : */ Parallel::~Parallel() { - for(size_t i = 0; i != hashes.size(); ++i) - delete hashes[i]; + for(auto hash : hashes) + delete hash; } } diff --git a/src/hash/skein/skein_512.cpp b/src/hash/skein/skein_512.cpp index 571bf9c0b..47bee5274 100644 --- a/src/hash/skein/skein_512.cpp +++ b/src/hash/skein/skein_512.cpp @@ -185,8 +185,9 @@ Skein_512::Skein_512(size_t arg_output_bits, std::string Skein_512::name() const { if(personalization != "") - return "Skein-512(" + to_string(output_bits) + "," + personalization + ")"; - return "Skein-512(" + to_string(output_bits) + ")"; + return "Skein-512(" + std::to_string(output_bits) + "," + + personalization + ")"; + return "Skein-512(" + std::to_string(output_bits) + ")"; } HashFunction* Skein_512::clone() const diff --git a/src/hash/tiger/tiger.cpp b/src/hash/tiger/tiger.cpp index 6f40f84c8..daa0939b9 100644 --- a/src/hash/tiger/tiger.cpp +++ b/src/hash/tiger/tiger.cpp @@ -160,7 +160,8 @@ void Tiger::clear() */ std::string Tiger::name() const { - return "Tiger(" + to_string(output_length()) + "," + to_string(passes) + ")"; + return "Tiger(" + std::to_string(output_length()) + "," + + std::to_string(passes) + ")"; } /* @@ -175,11 +176,11 @@ Tiger::Tiger(size_t hash_len, size_t passes) : { if(output_length() != 16 && output_length() != 20 && output_length() != 24) throw Invalid_Argument("Tiger: Illegal hash output size: " + - to_string(output_length())); + std::to_string(output_length())); if(passes < 3) throw Invalid_Argument("Tiger: Invalid number of passes: " - + to_string(passes)); + + std::to_string(passes)); clear(); } diff --git a/src/kdf/prf_tls/prf_tls.cpp b/src/kdf/prf_tls/prf_tls.cpp index 3790650b0..1236e13c7 100644 --- a/src/kdf/prf_tls/prf_tls.cpp +++ b/src/kdf/prf_tls/prf_tls.cpp @@ -29,7 +29,8 @@ void P_hash(MemoryRegion<byte>& output, } catch(Invalid_Key_Length) { - throw Internal_Error("The premaster secret of " + to_string(secret_len) + + throw Internal_Error("The premaster secret of " + + std::to_string(secret_len) + " bytes is too long for the PRF"); } diff --git a/src/libstate/global_rng.cpp b/src/libstate/global_rng.cpp index a73924213..066d033a1 100644 --- a/src/libstate/global_rng.cpp +++ b/src/libstate/global_rng.cpp @@ -6,7 +6,6 @@ */ #include <botan/libstate.h> -#include <botan/internal/mutex.h> #if defined(BOTAN_HAS_RANDPOOL) #include <botan/randpool.h> @@ -68,7 +67,7 @@ void add_entropy_sources(RandomNumberGenerator* rng) #if defined(BOTAN_HAS_ENTROPY_SRC_DEV_RANDOM) rng->add_entropy_source( new Device_EntropySource( - split_on("/dev/urandom:/dev/random:/dev/srandom", ':') + split_on("/dev/random:/dev/srandom:/dev/urandom", ':') ) ); #endif @@ -107,60 +106,60 @@ class Serialized_PRNG : public RandomNumberGenerator public: void randomize(byte out[], size_t len) { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); rng->randomize(out, len); } bool is_seeded() const { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); return rng->is_seeded(); } void clear() { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); rng->clear(); } std::string name() const { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); return rng->name(); } void reseed(size_t poll_bits) { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); rng->reseed(poll_bits); } void add_entropy_source(EntropySource* es) { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); rng->add_entropy_source(es); } void add_entropy(const byte in[], size_t len) { - Mutex_Holder lock(mutex); + std::lock_guard<std::mutex> lock(mutex); rng->add_entropy(in, len); } // We do not own the mutex; Library_State does - Serialized_PRNG(RandomNumberGenerator* r, Mutex* m) : + Serialized_PRNG(RandomNumberGenerator* r, std::mutex& m) : mutex(m), rng(r) {} ~Serialized_PRNG() { delete rng; } private: - Mutex* mutex; + std::mutex& mutex; RandomNumberGenerator* rng; }; } RandomNumberGenerator* Library_State::make_global_rng(Algorithm_Factory& af, - Mutex* mutex) + std::mutex& mutex) { RandomNumberGenerator* rng = 0; diff --git a/src/libstate/global_state.cpp b/src/libstate/global_state.cpp index 43c935ca3..34bcd03fc 100644 --- a/src/libstate/global_state.cpp +++ b/src/libstate/global_state.cpp @@ -37,7 +37,7 @@ Library_State& global_state() if(!global_lib_state) { global_lib_state = new Library_State; - global_lib_state->initialize(true); + global_lib_state->initialize(); } return (*global_lib_state); diff --git a/src/libstate/info.txt b/src/libstate/info.txt index d48ad70d5..ef0c9a47e 100644 --- a/src/libstate/info.txt +++ b/src/libstate/info.txt @@ -38,8 +38,6 @@ hmac_rng kdf mac mode_pad -mutex -noop_mutex pbkdf pk_pad pubkey diff --git a/src/libstate/init.cpp b/src/libstate/init.cpp index 7cdc615bd..5fd476994 100644 --- a/src/libstate/init.cpp +++ b/src/libstate/init.cpp @@ -1,12 +1,11 @@ /* * Default Initialization Function -* (C) 1999-2007 Jack Lloyd +* (C) 1999-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/init.h> -#include <botan/parsing.h> #include <botan/libstate.h> #include <botan/global_state.h> @@ -15,36 +14,8 @@ namespace Botan { /* * Library Initialization */ -void LibraryInitializer::initialize(const std::string& arg_string) +void LibraryInitializer::initialize(const std::string&) { - bool thread_safe = false; - - const std::vector<std::string> arg_list = split_on(arg_string, ' '); - for(size_t i = 0; i != arg_list.size(); ++i) - { - if(arg_list[i].size() == 0) - continue; - - std::string name, value; - - if(arg_list[i].find('=') == std::string::npos) - { - name = arg_list[i]; - value = "true"; - } - else - { - std::vector<std::string> name_and_value = split_on(arg_list[i], '='); - name = name_and_value[0]; - value = name_and_value[1]; - } - - bool is_on = - (value == "1" || value == "true" || value == "yes" || value == "on"); - - if(name == "thread_safe") - thread_safe = is_on; - } try { @@ -56,7 +27,7 @@ void LibraryInitializer::initialize(const std::string& arg_string) */ Global_State_Management::set_global_state(new Library_State); - global_state().initialize(thread_safe); + global_state().initialize(); } catch(...) { diff --git a/src/libstate/libstate.cpp b/src/libstate/libstate.cpp index 076b55fcf..588c5db1b 100644 --- a/src/libstate/libstate.cpp +++ b/src/libstate/libstate.cpp @@ -11,8 +11,6 @@ #include <botan/cpuid.h> #include <botan/internal/defalloc.h> #include <botan/internal/core_engine.h> -#include <botan/internal/mutex.h> -#include <botan/internal/mux_noop.h> #include <botan/internal/stl_util.h> #include <botan/internal/mlock.h> #include <algorithm> @@ -21,14 +19,6 @@ #include <botan/selftest.h> #endif -#if defined(BOTAN_HAS_MUTEX_PTHREAD) - #include <botan/internal/mux_pthr.h> -#elif defined(BOTAN_HAS_MUTEX_WIN32) - #include <botan/internal/mux_win32.h> -#elif defined(BOTAN_HAS_MUTEX_QT) - #include <botan/internal/mux_qt.h> -#endif - #if defined(BOTAN_HAS_ALLOC_MMAP) #include <botan/internal/mmap_mem.h> #endif @@ -56,19 +46,11 @@ namespace Botan { /* -* Get a new mutex object -*/ -Mutex* Library_State::get_mutex() const - { - return mutex_factory->make(); - } - -/* * Get an allocator by its name */ -Allocator* Library_State::get_allocator(const std::string& type) const +Allocator* Library_State::get_allocator(const std::string& type) { - Mutex_Holder lock(allocator_lock); + std::lock_guard<std::mutex> lock(allocator_lock); if(type != "") return search_map<std::string, Allocator*>(alloc_factory, type, 0); @@ -88,7 +70,7 @@ Allocator* Library_State::get_allocator(const std::string& type) const */ void Library_State::add_allocator(Allocator* allocator) { - Mutex_Holder lock(allocator_lock); + std::lock_guard<std::mutex> lock(allocator_lock); allocator->init(); @@ -101,11 +83,11 @@ void Library_State::add_allocator(Allocator* allocator) */ void Library_State::set_default_allocator(const std::string& type) { - Mutex_Holder lock(allocator_lock); - if(type == "") return; + std::lock_guard<std::mutex> lock(allocator_lock); + default_allocator_name = type; cached_default_allocator = 0; } @@ -114,9 +96,9 @@ void Library_State::set_default_allocator(const std::string& type) * Get a configuration value */ std::string Library_State::get(const std::string& section, - const std::string& key) const + const std::string& key) { - Mutex_Holder lock(config_lock); + std::lock_guard<std::mutex> lock(config_lock); return search_map<std::string, std::string>(config, section + "/" + key, ""); @@ -126,9 +108,9 @@ std::string Library_State::get(const std::string& section, * See if a particular option has been set */ bool Library_State::is_set(const std::string& section, - const std::string& key) const + const std::string& key) { - Mutex_Holder lock(config_lock); + std::lock_guard<std::mutex> lock(config_lock); return config.count(section + "/" + key) != 0; } @@ -139,12 +121,11 @@ bool Library_State::is_set(const std::string& section, void Library_State::set(const std::string& section, const std::string& key, const std::string& value, bool overwrite) { - Mutex_Holder lock(config_lock); + std::lock_guard<std::mutex> lock(config_lock); std::string full_key = section + "/" + key; - std::map<std::string, std::string>::const_iterator i = - config.find(full_key); + auto i = config.find(full_key); if(overwrite || i == config.end() || i->second == "") config[full_key] = value; @@ -161,7 +142,7 @@ void Library_State::add_alias(const std::string& key, const std::string& value) /* * Dereference an alias to a fixed name */ -std::string Library_State::deref_alias(const std::string& key) const +std::string Library_State::deref_alias(const std::string& key) { std::string result = key; while(is_set("alias", result)) @@ -184,7 +165,7 @@ Algorithm_Factory& Library_State::algorithm_factory() const */ RandomNumberGenerator& Library_State::global_rng() { - Mutex_Holder lock(global_rng_lock); + std::lock_guard<std::mutex> lock(global_rng_lock); if(!global_rng_ptr) global_rng_ptr = make_global_rng(algorithm_factory(), @@ -196,46 +177,26 @@ RandomNumberGenerator& Library_State::global_rng() /* * Load a set of modules */ -void Library_State::initialize(bool thread_safe) +void Library_State::initialize() { CPUID::initialize(); - if(mutex_factory) + if(m_algorithm_factory) throw Invalid_State("Library_State has already been initialized"); - if(!thread_safe) - { - mutex_factory = new Noop_Mutex_Factory; - } - else - { -#if defined(BOTAN_HAS_MUTEX_PTHREAD) - mutex_factory = new Pthread_Mutex_Factory; -#elif defined(BOTAN_HAS_MUTEX_WIN32) - mutex_factory = new Win32_Mutex_Factory; -#elif defined(BOTAN_HAS_MUTEX_QT) - mutex_factory Qt_Mutex_Factory; -#else - throw Invalid_State("Could not find a thread-safe mutex object to use"); -#endif - } - - allocator_lock = get_mutex(); - config_lock = get_mutex(); - global_rng_lock = get_mutex(); - + cached_default_allocator = 0; default_allocator_name = has_mlock() ? "locking" : "malloc"; add_allocator(new Malloc_Allocator); - add_allocator(new Locking_Allocator(get_mutex())); + add_allocator(new Locking_Allocator); #if defined(BOTAN_HAS_ALLOC_MMAP) - add_allocator(new MemoryMapping_Allocator(get_mutex())); + add_allocator(new MemoryMapping_Allocator); #endif load_default_config(); - m_algorithm_factory = new Algorithm_Factory(*mutex_factory); + m_algorithm_factory = new Algorithm_Factory(); #if defined(BOTAN_HAS_ENGINE_GNU_MP) algorithm_factory().add_engine(new GMP_Engine); @@ -269,12 +230,9 @@ void Library_State::initialize(bool thread_safe) */ Library_State::Library_State() { - mutex_factory = 0; - allocator_lock = config_lock = 0; cached_default_allocator = 0; m_algorithm_factory = 0; - global_rng_lock = 0; global_rng_ptr = 0; } @@ -284,7 +242,11 @@ Library_State::Library_State() Library_State::~Library_State() { delete m_algorithm_factory; + m_algorithm_factory = 0; + delete global_rng_ptr; + global_rng_ptr = 0; + cached_default_allocator = 0; @@ -293,11 +255,6 @@ Library_State::~Library_State() allocators[i]->destroy(); delete allocators[i]; } - - delete global_rng_lock; - delete allocator_lock; - delete mutex_factory; - delete config_lock; } } diff --git a/src/libstate/libstate.h b/src/libstate/libstate.h index aa957c8c9..49908a1e3 100644 --- a/src/libstate/libstate.h +++ b/src/libstate/libstate.h @@ -13,16 +13,15 @@ #include <botan/algo_factory.h> #include <botan/rng.h> +#include <mutex> #include <string> #include <vector> #include <map> namespace Botan { -class Mutex; - -/** -* Global state container aka the buritto at the center of it all +/* +* Global State Container Base */ class BOTAN_DLL Library_State { @@ -30,10 +29,10 @@ class BOTAN_DLL Library_State Library_State(); ~Library_State(); - /** - * @param thread_safe should a mutex be used for serialization - */ - void initialize(bool thread_safe); + Library_State(const Library_State&) = delete; + Library_State& operator=(const Library_State&) = delete; + + void initialize(); /** * @return global Algorithm_Factory @@ -49,7 +48,7 @@ class BOTAN_DLL Library_State * @param name the name of the allocator * @return allocator matching this name, or NULL */ - Allocator* get_allocator(const std::string& name = "") const; + Allocator* get_allocator(const std::string& name = ""); /** * Add a new allocator to the list of available ones @@ -70,7 +69,7 @@ class BOTAN_DLL Library_State * @result the value of the parameter */ std::string get(const std::string& section, - const std::string& key) const; + const std::string& key); /** * Check whether a certain parameter is set or not. @@ -80,7 +79,7 @@ class BOTAN_DLL Library_State * false otherwise */ bool is_set(const std::string& section, - const std::string& key) const; + const std::string& key); /** * Set a configuration parameter. @@ -109,30 +108,20 @@ class BOTAN_DLL Library_State * @param alias the alias to resolve. * @return what the alias stands for */ - std::string deref_alias(const std::string& alias) const; - - /** - * @return newly created Mutex (free with delete) - */ - Mutex* get_mutex() const; + std::string deref_alias(const std::string&); private: static RandomNumberGenerator* make_global_rng(Algorithm_Factory& af, - Mutex* mutex); + std::mutex& mutex); void load_default_config(); - Library_State(const Library_State&) {} - Library_State& operator=(const Library_State&) { return (*this); } - - class Mutex_Factory* mutex_factory; - - Mutex* global_rng_lock; + std::mutex global_rng_lock; RandomNumberGenerator* global_rng_ptr; - Mutex* config_lock; + std::mutex config_lock; std::map<std::string, std::string> config; - Mutex* allocator_lock; + std::mutex allocator_lock; std::string default_allocator_name; std::map<std::string, Allocator*> alloc_factory; mutable Allocator* cached_default_allocator; diff --git a/src/math/bigint/big_code.cpp b/src/math/bigint/big_code.cpp index 75a310a7c..28614c9f1 100644 --- a/src/math/bigint/big_code.cpp +++ b/src/math/bigint/big_code.cpp @@ -111,7 +111,9 @@ BigInt BigInt::decode(const byte buf[], size_t length, Base base) if(length % 2) { // Handle lack of leading 0 - const char buf0_with_leading_0[2] = { '0', buf[0] }; + const char buf0_with_leading_0[2] = + { '0', static_cast<char>(buf[0]) }; + binary = hex_decode(buf0_with_leading_0, 2); binary += hex_decode(reinterpret_cast<const char*>(&buf[1]), diff --git a/src/math/bigint/bigint.cpp b/src/math/bigint/bigint.cpp index e2e062f2d..e2bbe7f5a 100644 --- a/src/math/bigint/bigint.cpp +++ b/src/math/bigint/bigint.cpp @@ -40,7 +40,7 @@ BigInt::BigInt(Sign s, size_t size) } /* -* Construct a BigInt from a "raw" BigInt +* Copy constructor */ BigInt::BigInt(const BigInt& b) { @@ -101,15 +101,6 @@ BigInt::BigInt(RandomNumberGenerator& rng, size_t bits) } /* -* Swap this BigInt with another -*/ -void BigInt::swap(BigInt& other) - { - reg.swap(other.reg); - std::swap(signedness, other.signedness); - } - -/* * Grow the internal storage */ void BigInt::grow_reg(size_t n) diff --git a/src/math/bigint/bigint.h b/src/math/bigint/bigint.h index 87c7cb766..57aa84528 100644 --- a/src/math/bigint/bigint.h +++ b/src/math/bigint/bigint.h @@ -438,7 +438,11 @@ class BOTAN_DLL BigInt * Swap this value with another * @param other BigInt to swap values with */ - void swap(BigInt& other); + void swap(BigInt& other) + { + reg.swap(other.reg); + std::swap(signedness, other.signedness); + } /** * Create empty BigInt @@ -500,6 +504,29 @@ class BOTAN_DLL BigInt */ BigInt(NumberType type, size_t n); + /** + * Move constructor + */ + BigInt(BigInt&& other) + { + this->swap(other); + } + + /** + * Move assignment + */ + BigInt& operator=(BigInt&& other) + { + if(this != &other) + this->swap(other); + + return (*this); + } + + /** + * Copy assignment + */ + BigInt& operator=(const BigInt&) = default; private: SecureVector<word> reg; Sign signedness; diff --git a/src/math/ec_gfp/point_gfp.h b/src/math/ec_gfp/point_gfp.h index b2b6fe2f0..546a8dd6f 100644 --- a/src/math/ec_gfp/point_gfp.h +++ b/src/math/ec_gfp/point_gfp.h @@ -59,6 +59,34 @@ class BOTAN_DLL PointGFp PointGFp(const CurveGFp& curve); /** + * Copy constructor + */ + PointGFp(const PointGFp&) = default; + + /** + * Move Constructor + */ + PointGFp(PointGFp&& other) + { + this->swap(other); + } + + /** + * Standard Assignment + */ + PointGFp& operator=(const PointGFp&) = default; + + /** + * Move Assignment + */ + PointGFp& operator=(PointGFp&& other) + { + if(this != &other) + this->swap(other); + return (*this); + } + + /** * Construct a point from its affine coordinates * @param curve the base curve * @param x affine x coordinate @@ -66,9 +94,6 @@ class BOTAN_DLL PointGFp */ PointGFp(const CurveGFp& curve, const BigInt& x, const BigInt& y); - //PointGFp(const PointGFp& other) = default; - //PointGFp& operator=(const PointGFp& other) = default; - /** * += Operator * @param rhs the PointGFp to add to the local value diff --git a/src/math/numbertheory/dsa_gen.cpp b/src/math/numbertheory/dsa_gen.cpp index 670f103da..612370804 100644 --- a/src/math/numbertheory/dsa_gen.cpp +++ b/src/math/numbertheory/dsa_gen.cpp @@ -47,15 +47,15 @@ bool generate_dsa_primes(RandomNumberGenerator& rng, if(!fips186_3_valid_size(pbits, qbits)) throw Invalid_Argument( "FIPS 186-3 does not allow DSA domain parameters of " + - to_string(pbits) + "/" + to_string(qbits) + " bits long"); + std::to_string(pbits) + "/" + std::to_string(qbits) + " bits long"); if(seed_c.size() * 8 < qbits) throw Invalid_Argument( - "Generating a DSA parameter set with a " + to_string(qbits) + + "Generating a DSA parameter set with a " + std::to_string(qbits) + "long q requires a seed at least as many bits long"); - std::auto_ptr<HashFunction> hash( - af.make_hash_function("SHA-" + to_string(qbits))); + std::unique_ptr<HashFunction> hash( + af.make_hash_function("SHA-" + std::to_string(qbits))); const size_t HASH_SIZE = hash->output_length(); diff --git a/src/math/numbertheory/make_prm.cpp b/src/math/numbertheory/make_prm.cpp index 4fb3f908c..1e8d11000 100644 --- a/src/math/numbertheory/make_prm.cpp +++ b/src/math/numbertheory/make_prm.cpp @@ -20,7 +20,7 @@ BigInt random_prime(RandomNumberGenerator& rng, { if(bits <= 1) throw Invalid_Argument("random_prime: Can't make a prime of " + - to_string(bits) + " bits"); + std::to_string(bits) + " bits"); else if(bits == 2) return ((rng.next_byte() % 2) ? 2 : 3); else if(bits == 3) @@ -88,7 +88,7 @@ BigInt random_safe_prime(RandomNumberGenerator& rng, size_t bits) { if(bits <= 64) throw Invalid_Argument("random_safe_prime: Can't make a prime of " + - to_string(bits) + " bits"); + std::to_string(bits) + " bits"); BigInt p; do diff --git a/src/math/numbertheory/numthry.cpp b/src/math/numbertheory/numthry.cpp index 16fa8ca0c..18f6ce429 100644 --- a/src/math/numbertheory/numthry.cpp +++ b/src/math/numbertheory/numthry.cpp @@ -10,8 +10,6 @@ #include <botan/internal/bit_ops.h> #include <algorithm> -#include <stdio.h> - namespace Botan { namespace { @@ -85,7 +83,7 @@ size_t miller_rabin_test_iterations(size_t bits, size_t level) { struct mapping { size_t bits; size_t verify_iter; size_t check_iter; }; - static const mapping tests[] = { + const mapping tests[] = { { 50, 55, 25 }, { 100, 38, 22 }, { 160, 32, 18 }, diff --git a/src/mutex/info.txt b/src/mutex/info.txt deleted file mode 100644 index af4cf9bb3..000000000 --- a/src/mutex/info.txt +++ /dev/null @@ -1,5 +0,0 @@ -define MUTEX_WRAPPERS - -<header:internal> -mutex.h -</header:internal> diff --git a/src/mutex/mutex.h b/src/mutex/mutex.h deleted file mode 100644 index f209466d5..000000000 --- a/src/mutex/mutex.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -* Mutex -* (C) 1999-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#ifndef BOTAN_MUTEX_H__ -#define BOTAN_MUTEX_H__ - -#include <botan/exceptn.h> - -namespace Botan { - -/** -* Mutex Base Class -*/ -class Mutex - { - public: - /** - * Lock the mutex - */ - virtual void lock() = 0; - - /** - * Unlock the mutex - */ - virtual void unlock() = 0; - virtual ~Mutex() {} - }; - -/** -* Mutex Factory -*/ -class Mutex_Factory - { - public: - /** - * @return newly allocated mutex - */ - virtual Mutex* make() = 0; - - virtual ~Mutex_Factory() {} - }; - -/** -* Mutex Holding Class for RAII -*/ -class Mutex_Holder - { - public: - /** - * Hold onto a mutex until we leave scope - * @param m the mutex to lock - */ - Mutex_Holder(Mutex* m) : mux(m) - { - if(!mux) - throw Invalid_Argument("Mutex_Holder: Argument was NULL"); - mux->lock(); - } - - ~Mutex_Holder() { mux->unlock(); } - private: - Mutex* mux; - }; - -} - -#endif diff --git a/src/mutex/noop_mutex/info.txt b/src/mutex/noop_mutex/info.txt deleted file mode 100644 index 16670b1dd..000000000 --- a/src/mutex/noop_mutex/info.txt +++ /dev/null @@ -1,9 +0,0 @@ -define MUTEX_NOOP - -<source> -mux_noop.cpp -</source> - -<header:internal> -mux_noop.h -</header:internal> diff --git a/src/mutex/noop_mutex/mux_noop.cpp b/src/mutex/noop_mutex/mux_noop.cpp deleted file mode 100644 index 18151274a..000000000 --- a/src/mutex/noop_mutex/mux_noop.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* -* No-Op Mutex Factory -* (C) 1999-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#include <botan/internal/mux_noop.h> - -namespace Botan { - -/* -* No-Op Mutex Factory -*/ -Mutex* Noop_Mutex_Factory::make() - { - class Noop_Mutex : public Mutex - { - public: - class Mutex_State_Error : public Internal_Error - { - public: - Mutex_State_Error(const std::string& where) : - Internal_Error("Noop_Mutex::" + where + ": " + - "Mutex is already " + where + "ed") {} - }; - - void lock() - { - if(locked) - throw Mutex_State_Error("lock"); - locked = true; - } - - void unlock() - { - if(!locked) - throw Mutex_State_Error("unlock"); - locked = false; - } - - Noop_Mutex() { locked = false; } - private: - bool locked; - }; - - return new Noop_Mutex; - } - -} diff --git a/src/mutex/noop_mutex/mux_noop.h b/src/mutex/noop_mutex/mux_noop.h deleted file mode 100644 index 20989a635..000000000 --- a/src/mutex/noop_mutex/mux_noop.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -* No-Op Mutex Factory -* (C) 1999-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#ifndef BOTAN_NOOP_MUTEX_FACTORY_H__ -#define BOTAN_NOOP_MUTEX_FACTORY_H__ - -#include <botan/internal/mutex.h> - -namespace Botan { - -/** -* No-Op Mutex Factory -*/ -class Noop_Mutex_Factory : public Mutex_Factory - { - public: - Mutex* make(); - }; - -} - -#endif diff --git a/src/mutex/pthreads/info.txt b/src/mutex/pthreads/info.txt deleted file mode 100644 index 1d826b61c..000000000 --- a/src/mutex/pthreads/info.txt +++ /dev/null @@ -1,29 +0,0 @@ -define MUTEX_PTHREAD - -<source> -mux_pthr.cpp -</source> - -<header:internal> -mux_pthr.h -</header:internal> - -<libs> -all!qnx,freebsd,dragonfly,openbsd,netbsd -> pthread -</libs> - -<os> -aix -cygwin -darwin -freebsd -dragonfly -hpux -irix -linux -netbsd -openbsd -qnx -solaris -tru64 -</os> diff --git a/src/mutex/pthreads/mux_pthr.cpp b/src/mutex/pthreads/mux_pthr.cpp deleted file mode 100644 index 165132239..000000000 --- a/src/mutex/pthreads/mux_pthr.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* -* Pthread Mutex -* (C) 1999-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#include <botan/internal/mux_pthr.h> -#include <botan/exceptn.h> - -#ifndef _POSIX_C_SOURCE - #define _POSIX_C_SOURCE 199506 -#endif - -#include <pthread.h> - -namespace Botan { - -/* -* Pthread Mutex Factory -*/ -Mutex* Pthread_Mutex_Factory::make() - { - - class Pthread_Mutex : public Mutex - { - public: - void lock() - { - if(pthread_mutex_lock(&mutex) != 0) - throw Invalid_State("Pthread_Mutex::lock: Error occured"); - } - - void unlock() - { - if(pthread_mutex_unlock(&mutex) != 0) - throw Invalid_State("Pthread_Mutex::unlock: Error occured"); - } - - Pthread_Mutex() - { - if(pthread_mutex_init(&mutex, 0) != 0) - throw Invalid_State("Pthread_Mutex: initialization failed"); - } - - ~Pthread_Mutex() - { - if(pthread_mutex_destroy(&mutex) != 0) - throw Invalid_State("~Pthread_Mutex: mutex is still locked"); - } - private: - pthread_mutex_t mutex; - }; - - return new Pthread_Mutex(); - } - -} diff --git a/src/mutex/pthreads/mux_pthr.h b/src/mutex/pthreads/mux_pthr.h deleted file mode 100644 index 5cecd09ad..000000000 --- a/src/mutex/pthreads/mux_pthr.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -* Pthread Mutex -* (C) 1999-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#ifndef BOTAN_MUTEX_PTHREAD_H__ -#define BOTAN_MUTEX_PTHREAD_H__ - -#include <botan/internal/mutex.h> - -namespace Botan { - -/** -* Pthread Mutex Factory -*/ -class Pthread_Mutex_Factory : public Mutex_Factory - { - public: - Mutex* make(); - }; - -} - -#endif diff --git a/src/mutex/qt_mutex/info.txt b/src/mutex/qt_mutex/info.txt deleted file mode 100644 index 7b014f886..000000000 --- a/src/mutex/qt_mutex/info.txt +++ /dev/null @@ -1,17 +0,0 @@ -define MUTEX_QT - -load_on request - -<source> -mux_qt.cpp -</source> - -<header:internal> -mux_qt.h -</header:internal> - -# I think we want to always use qt-mt, not qt -- not much point in supporting -# mutexes in a single threaded application, after all. -<libs> -all -> qt-mt -</libs> diff --git a/src/mutex/qt_mutex/mux_qt.cpp b/src/mutex/qt_mutex/mux_qt.cpp deleted file mode 100644 index da4e5ce5c..000000000 --- a/src/mutex/qt_mutex/mux_qt.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* -* Qt Thread Mutex -* (C) 2004-2007 Justin Karneges -* 2004-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#include <botan/internal/mux_qt.h> -#include <qmutex.h> - -#if !defined(QT_THREAD_SUPPORT) - #error Your version of Qt does not support threads or mutexes -#endif - -namespace Botan { - -/* -* Qt Mutex Factory -*/ -Mutex* Qt_Mutex_Factory::make() - { - class Qt_Mutex : public Mutex - { - public: - void lock() { mutex.lock(); } - void unlock() { mutex.unlock(); } - private: - QMutex mutex; - }; - - return new Qt_Mutex(); - } - -} diff --git a/src/mutex/qt_mutex/mux_qt.h b/src/mutex/qt_mutex/mux_qt.h deleted file mode 100644 index 3805acc3b..000000000 --- a/src/mutex/qt_mutex/mux_qt.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -* Qt Mutex -* (C) 2004-2007 Justin Karneges -* 2004-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#ifndef BOTAN_MUTEX_QT_H__ -#define BOTAN_MUTEX_QT_H__ - -#include <botan/internal/mutex.h> - -namespace Botan { - -/** -* Qt Mutex -*/ -class Qt_Mutex_Factory : public Mutex_Factory - { - public: - Mutex* make(); - }; - -} - -#endif diff --git a/src/mutex/win32_crit_section/info.txt b/src/mutex/win32_crit_section/info.txt deleted file mode 100644 index d90b8b64b..000000000 --- a/src/mutex/win32_crit_section/info.txt +++ /dev/null @@ -1,15 +0,0 @@ -define MUTEX_WIN32 - -<source> -mux_win32.cpp -</source> - -<header:internal> -mux_win32.h -</header:internal> - -<os> -cygwin -windows -mingw -</os> diff --git a/src/mutex/win32_crit_section/mux_win32.cpp b/src/mutex/win32_crit_section/mux_win32.cpp deleted file mode 100644 index fa6051798..000000000 --- a/src/mutex/win32_crit_section/mux_win32.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* -* Win32 Mutex -* (C) 2006 Luca Piccarreta -* 2006-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#include <botan/internal/mux_win32.h> -#include <windows.h> - -namespace Botan { - -/* -* Win32 Mutex Factory -*/ -Mutex* Win32_Mutex_Factory::make() - { - class Win32_Mutex : public Mutex - { - public: - void lock() { EnterCriticalSection(&mutex); } - void unlock() { LeaveCriticalSection(&mutex); } - - Win32_Mutex() { InitializeCriticalSection(&mutex); } - ~Win32_Mutex() { DeleteCriticalSection(&mutex); } - private: - CRITICAL_SECTION mutex; - }; - - return new Win32_Mutex(); - } - -} diff --git a/src/mutex/win32_crit_section/mux_win32.h b/src/mutex/win32_crit_section/mux_win32.h deleted file mode 100644 index 2aa51e18b..000000000 --- a/src/mutex/win32_crit_section/mux_win32.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -* Win32 Mutex -* (C) 2006 Luca Piccarreta -* 2006-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#ifndef BOTAN_MUTEX_WIN32_H__ -#define BOTAN_MUTEX_WIN32_H__ - -#include <botan/internal/mutex.h> - -namespace Botan { - -/** -* Win32 Mutex Factory -*/ -class Win32_Mutex_Factory : public Mutex_Factory - { - public: - Mutex* make(); - }; -} - -#endif diff --git a/src/passhash/bcrypt/bcrypt.cpp b/src/passhash/bcrypt/bcrypt.cpp index bb2e9095a..b0d654717 100644 --- a/src/passhash/bcrypt/bcrypt.cpp +++ b/src/passhash/bcrypt/bcrypt.cpp @@ -112,8 +112,13 @@ std::string make_bcrypt(const std::string& pass, std::string salt_b64 = bcrypt_base64_encode(&salt[0], salt.size()); - return "$2a$" + to_string(work_factor, 2) + "$" + salt_b64.substr(0, 22) + - bcrypt_base64_encode(&ctext[0], ctext.size() - 1); + std::string work_factor_str = std::to_string(work_factor); + if(work_factor_str.length() == 1) + work_factor_str = "0" + work_factor_str; + + return "$2a$" + work_factor_str + + "$" + salt_b64.substr(0, 22) + + bcrypt_base64_encode(&ctext[0], ctext.size() - 1); } } diff --git a/src/passhash/passhash9/passhash9.cpp b/src/passhash/passhash9/passhash9.cpp index e1e37da1e..43bfdd36e 100644 --- a/src/passhash/passhash9/passhash9.cpp +++ b/src/passhash/passhash9/passhash9.cpp @@ -53,7 +53,8 @@ std::string generate_passhash9(const std::string& pass, MessageAuthenticationCode* prf = get_pbkdf_prf(alg_id); if(!prf) - throw Invalid_Argument("Passhash9: Algorithm id " + to_string(alg_id) + + throw Invalid_Argument("Passhash9: Algorithm id " + + std::to_string(alg_id) + " is not defined"); PKCS5_PBKDF2 kdf(prf); // takes ownership of pointer diff --git a/src/pbkdf/pbkdf2/pbkdf2.cpp b/src/pbkdf/pbkdf2/pbkdf2.cpp index 7e4d1cd8a..39d53d417 100644 --- a/src/pbkdf/pbkdf2/pbkdf2.cpp +++ b/src/pbkdf/pbkdf2/pbkdf2.cpp @@ -30,7 +30,7 @@ OctetString PKCS5_PBKDF2::derive_key(size_t key_len, catch(Invalid_Key_Length) { throw Exception(name() + " cannot accept passphrases of length " + - to_string(passphrase.length())); + std::to_string(passphrase.length())); } SecureVector<byte> key(key_len); diff --git a/src/pubkey/dl_group/dl_group.cpp b/src/pubkey/dl_group/dl_group.cpp index 7f0160b6b..3904841ba 100644 --- a/src/pubkey/dl_group/dl_group.cpp +++ b/src/pubkey/dl_group/dl_group.cpp @@ -47,7 +47,7 @@ DL_Group::DL_Group(RandomNumberGenerator& rng, PrimeType type, size_t pbits, size_t qbits) { if(pbits < 512) - throw Invalid_Argument("DL_Group: prime size " + to_string(pbits) + + throw Invalid_Argument("DL_Group: prime size " + std::to_string(pbits) + " is too small"); if(type == Strong) @@ -239,7 +239,7 @@ SecureVector<byte> DL_Group::DER_encode(Format format) const .get_contents(); } - throw Invalid_Argument("Unknown DL_Group encoding " + to_string(format)); + throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); } /* @@ -255,7 +255,7 @@ std::string DL_Group::PEM_encode(Format format) const else if(format == ANSI_X9_42) return PEM_Code::encode(encoding, "X942 DH PARAMETERS"); else - throw Invalid_Argument("Unknown DL_Group encoding " + to_string(format)); + throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); } /* @@ -289,7 +289,7 @@ void DL_Group::BER_decode(DataSource& source, Format format) .discard_remaining(); } else - throw Invalid_Argument("Unknown DL_Group encoding " + to_string(format)); + throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); initialize(new_p, new_q, new_g); } diff --git a/src/pubkey/dsa/dsa.cpp b/src/pubkey/dsa/dsa.cpp index 5e511840f..c3b4f260b 100644 --- a/src/pubkey/dsa/dsa.cpp +++ b/src/pubkey/dsa/dsa.cpp @@ -8,7 +8,7 @@ #include <botan/dsa.h> #include <botan/numthry.h> #include <botan/keypair.h> - +#include <future> namespace Botan { /* @@ -89,8 +89,12 @@ DSA_Signature_Operation::sign(const byte msg[], size_t msg_len, k.randomize(rng, q.bits()); while(k >= q); - r = mod_q.reduce(powermod_g_p(k)); - s = mod_q.multiply(inverse_mod(k, q), mul_add(x, r, i)); + auto future_r = std::async(std::launch::async, + [&]() { return mod_q.reduce(powermod_g_p(k)); }); + + s = inverse_mod(k, q); + r = future_r.get(); + s = mod_q.multiply(s, mul_add(x, r, i)); } SecureVector<byte> output(2*q.bytes()); @@ -124,8 +128,14 @@ bool DSA_Verification_Operation::verify(const byte msg[], size_t msg_len, return false; s = inverse_mod(s, q); - s = mod_p.multiply(powermod_g_p(mod_q.multiply(s, i)), - powermod_y_p(mod_q.multiply(s, r))); + + auto future_s_i = std::async(std::launch::async, + [&]() { return powermod_g_p(mod_q.multiply(s, i)); }); + + BigInt s_r = powermod_y_p(mod_q.multiply(s, r)); + BigInt s_i = future_s_i.get(); + + s = mod_p.multiply(s_i, s_r); return (mod_q.reduce(s) == r); } diff --git a/src/pubkey/ecdh/ecdh.h b/src/pubkey/ecdh/ecdh.h index 2edbfe86d..6fe0697bf 100644 --- a/src/pubkey/ecdh/ecdh.h +++ b/src/pubkey/ecdh/ecdh.h @@ -22,7 +22,6 @@ class BOTAN_DLL ECDH_PublicKey : public virtual EC_PublicKey { public: - ECDH_PublicKey(const AlgorithmIdentifier& alg_id, const MemoryRegion<byte>& key_bits) : EC_PublicKey(alg_id, key_bits) {} diff --git a/src/pubkey/nr/nr.cpp b/src/pubkey/nr/nr.cpp index 61cf7eb3f..e1c5e51da 100644 --- a/src/pubkey/nr/nr.cpp +++ b/src/pubkey/nr/nr.cpp @@ -8,6 +8,7 @@ #include <botan/nr.h> #include <botan/numthry.h> #include <botan/keypair.h> +#include <future> namespace Botan { @@ -132,7 +133,10 @@ NR_Verification_Operation::verify_mr(const byte msg[], size_t msg_len) if(c.is_zero() || c >= q || d >= q) throw Invalid_Argument("NR verification: Invalid signature"); - BigInt i = mod_p.multiply(powermod_g_p(d), powermod_y_p(c)); + auto future_y_c = std::async(std::launch::async, powermod_y_p, c); + BigInt g_d = powermod_g_p(d); + + BigInt i = mod_p.multiply(g_d, future_y_c.get()); return BigInt::encode(mod_q.reduce(c - i)); } diff --git a/src/pubkey/pk_algs.cpp b/src/pubkey/pk_algs.cpp index e500cfc2e..9b3218ac4 100644 --- a/src/pubkey/pk_algs.cpp +++ b/src/pubkey/pk_algs.cpp @@ -40,6 +40,10 @@ #include <botan/elgamal.h> #endif +#if defined(BOTAN_HAS_ECDH) + #include <botan/ecdh.h> +#endif + namespace Botan { Public_Key* make_public_key(const AlgorithmIdentifier& alg_id, @@ -89,6 +93,11 @@ Public_Key* make_public_key(const AlgorithmIdentifier& alg_id, return new GOST_3410_PublicKey(alg_id, key_bits); #endif +#if defined(BOTAN_HAS_ECDH) + if(alg_name == "ECDH") + return new ECDH_PublicKey(alg_id, key_bits); +#endif + return 0; } @@ -140,6 +149,11 @@ Private_Key* make_private_key(const AlgorithmIdentifier& alg_id, return new GOST_3410_PrivateKey(alg_id, key_bits); #endif +#if defined(BOTAN_HAS_ECDH) + if(alg_name == "ECDH") + return new ECDH_PrivateKey(alg_id, key_bits); +#endif + return 0; } diff --git a/src/pubkey/pkcs8.cpp b/src/pubkey/pkcs8.cpp index 16440b648..57bb5c1e2 100644 --- a/src/pubkey/pkcs8.cpp +++ b/src/pubkey/pkcs8.cpp @@ -41,8 +41,10 @@ SecureVector<byte> PKCS8_extract(DataSource& source, /* * PEM decode and/or decrypt a private key */ -SecureVector<byte> PKCS8_decode(DataSource& source, const User_Interface& ui, - AlgorithmIdentifier& pk_alg_id) +SecureVector<byte> PKCS8_decode( + DataSource& source, + std::function<std::pair<bool,std::string> ()> get_passphrase, + AlgorithmIdentifier& pk_alg_id) { AlgorithmIdentifier pbe_alg_id; SecureVector<byte> key_data, key; @@ -89,16 +91,14 @@ SecureVector<byte> PKCS8_decode(DataSource& source, const User_Interface& ui, if(is_encrypted) { DataSource_Memory params(pbe_alg_id.parameters); - std::auto_ptr<PBE> pbe(get_pbe(pbe_alg_id.oid, params)); + std::unique_ptr<PBE> pbe(get_pbe(pbe_alg_id.oid, params)); - User_Interface::UI_Result result = User_Interface::OK; - const std::string passphrase = - ui.get_passphrase("PKCS #8 private key", source.id(), result); + std::pair<bool, std::string> pass = get_passphrase(); - if(result == User_Interface::CANCEL_ACTION) + if(pass.first == false) break; - pbe->set_key(passphrase); + pbe->set_key(pass.second); Pipe decryptor(pbe.release()); decryptor.process_msg(key_data); @@ -162,7 +162,7 @@ SecureVector<byte> BER_encode(const Private_Key& key, { const std::string DEFAULT_PBE = "PBE-PKCS5v20(SHA-1,AES-256/CBC)"; - std::auto_ptr<PBE> pbe(get_pbe(((pbe_algo != "") ? pbe_algo : DEFAULT_PBE))); + std::unique_ptr<PBE> pbe(get_pbe(((pbe_algo != "") ? pbe_algo : DEFAULT_PBE))); pbe->new_params(rng); pbe->set_key(pass); @@ -200,10 +200,10 @@ std::string PEM_encode(const Private_Key& key, */ Private_Key* load_key(DataSource& source, RandomNumberGenerator& rng, - const User_Interface& ui) + std::function<std::pair<bool, std::string> ()> get_pass) { AlgorithmIdentifier alg_id; - SecureVector<byte> pkcs8_key = PKCS8_decode(source, ui, alg_id); + SecureVector<byte> pkcs8_key = PKCS8_decode(source, get_pass, alg_id); const std::string alg_name = OIDS::lookup(alg_id.oid); if(alg_name == "" || alg_name == alg_id.oid.as_string()) @@ -218,12 +218,38 @@ Private_Key* load_key(DataSource& source, */ Private_Key* load_key(const std::string& fsname, RandomNumberGenerator& rng, - const User_Interface& ui) + std::function<std::pair<bool, std::string> ()> get_pass) { DataSource_Stream source(fsname, true); - return PKCS8::load_key(source, rng, ui); + return PKCS8::load_key(source, rng, get_pass); } +namespace { + +class Single_Shot_Passphrase + { + public: + Single_Shot_Passphrase(const std::string& pass) : + passphrase(pass), first(true) {} + + std::pair<bool, std::string> operator()() + { + if(first) + { + first = false; + return std::make_pair(true, passphrase); + } + else + return std::make_pair(false, ""); + } + + private: + std::string passphrase; + bool first; + }; + +} + /* * Extract a private key and return it */ @@ -231,7 +257,7 @@ Private_Key* load_key(DataSource& source, RandomNumberGenerator& rng, const std::string& pass) { - return PKCS8::load_key(source, rng, User_Interface(pass)); + return PKCS8::load_key(source, rng, Single_Shot_Passphrase(pass)); } /* @@ -241,7 +267,7 @@ Private_Key* load_key(const std::string& fsname, RandomNumberGenerator& rng, const std::string& pass) { - return PKCS8::load_key(fsname, rng, User_Interface(pass)); + return PKCS8::load_key(fsname, rng, Single_Shot_Passphrase(pass)); } /* diff --git a/src/pubkey/pkcs8.h b/src/pubkey/pkcs8.h index 00607b329..d573fb460 100644 --- a/src/pubkey/pkcs8.h +++ b/src/pubkey/pkcs8.h @@ -9,7 +9,7 @@ #define BOTAN_PKCS8_H__ #include <botan/x509_key.h> -#include <botan/ui.h> +#include <functional> namespace Botan { @@ -123,18 +123,19 @@ inline void encrypt_key(const Private_Key& key, * Load a key from a data source. * @param source the data source providing the encoded key * @param rng the rng to use -* @param ui the user interface to be used for passphrase dialog +* @param get_passphrase a function that returns passphrases * @return loaded private key object */ -BOTAN_DLL Private_Key* load_key(DataSource& source, - RandomNumberGenerator& rng, - const User_Interface& ui); +BOTAN_DLL Private_Key* load_key( + DataSource& source, + RandomNumberGenerator& rng, + std::function<std::pair<bool, std::string> ()> get_passphrase); /** Load a key from a data source. * @param source the data source providing the encoded key * @param rng the rng to use * @param pass the passphrase to decrypt the key. Provide an empty -* string if the key is not encoded. +* string if the key is not encrypted * @return loaded private key object */ BOTAN_DLL Private_Key* load_key(DataSource& source, @@ -145,18 +146,19 @@ BOTAN_DLL Private_Key* load_key(DataSource& source, * Load a key from a file. * @param filename the path to the file containing the encoded key * @param rng the rng to use -* @param ui the user interface to be used for passphrase dialog +* @param get_passphrase a function that returns passphrases * @return loaded private key object */ -BOTAN_DLL Private_Key* load_key(const std::string& filename, - RandomNumberGenerator& rng, - const User_Interface& ui); +BOTAN_DLL Private_Key* load_key( + const std::string& filename, + RandomNumberGenerator& rng, + std::function<std::pair<bool, std::string> ()> get_passphrase); /** Load a key from a file. * @param filename the path to the file containing the encoded key * @param rng the rng to use * @param pass the passphrase to decrypt the key. Provide an empty -* string if the key is not encoded. +* string if the key is not encrypted * @return loaded private key object */ BOTAN_DLL Private_Key* load_key(const std::string& filename, diff --git a/src/pubkey/pubkey.cpp b/src/pubkey/pubkey.cpp index 6e63f9fc9..d0b74071c 100644 --- a/src/pubkey/pubkey.cpp +++ b/src/pubkey/pubkey.cpp @@ -238,7 +238,7 @@ SecureVector<byte> PK_Signer::signature(RandomNumberGenerator& rng) } else throw Encoding_Error("PK_Signer: Unknown signature format " + - to_string(sig_format)); + std::to_string(sig_format)); } /* @@ -324,7 +324,7 @@ bool PK_Verifier::check_signature(const byte sig[], size_t length) } else throw Decoding_Error("PK_Verifier: Unknown signature format " + - to_string(sig_format)); + std::to_string(sig_format)); } catch(Invalid_Argument) { return false; } } diff --git a/src/pubkey/rsa/rsa.cpp b/src/pubkey/rsa/rsa.cpp index 40c3968af..2da366699 100644 --- a/src/pubkey/rsa/rsa.cpp +++ b/src/pubkey/rsa/rsa.cpp @@ -11,6 +11,7 @@ #include <botan/numthry.h> #include <botan/keypair.h> #include <botan/internal/assert.h> +#include <future> namespace Botan { @@ -22,7 +23,7 @@ RSA_PrivateKey::RSA_PrivateKey(RandomNumberGenerator& rng, { if(bits < 512) throw Invalid_Argument(algo_name() + ": Can't make a key that is only " + - to_string(bits) + " bits long"); + std::to_string(bits) + " bits long"); if(exp < 3 || exp % 2 == 0) throw Invalid_Argument(algo_name() + ": Invalid encryption exponent"); @@ -78,8 +79,9 @@ BigInt RSA_Private_Operation::private_op(const BigInt& m) const if(m >= n) throw Invalid_Argument("RSA private op - input is too large"); - BigInt j1 = powermod_d1_p(m); + auto future_j1 = std::async(std::launch::async, powermod_d1_p, m); BigInt j2 = powermod_d2_q(m); + BigInt j1 = future_j1.get(); j1 = mod_p.reduce(sub_mul(j1, j2, c)); diff --git a/src/pubkey/rw/rw.cpp b/src/pubkey/rw/rw.cpp index 5f58d8e88..dab84b59f 100644 --- a/src/pubkey/rw/rw.cpp +++ b/src/pubkey/rw/rw.cpp @@ -21,7 +21,7 @@ RW_PrivateKey::RW_PrivateKey(RandomNumberGenerator& rng, { if(bits < 512) throw Invalid_Argument(algo_name() + ": Can't make a key that is only " + - to_string(bits) + " bits long"); + std::to_string(bits) + " bits long"); if(exp < 2 || exp % 2 == 1) throw Invalid_Argument(algo_name() + ": Invalid encryption exponent"); diff --git a/src/rng/hmac_rng/hmac_rng.cpp b/src/rng/hmac_rng/hmac_rng.cpp index 7912e58af..44a9e9cba 100644 --- a/src/rng/hmac_rng/hmac_rng.cpp +++ b/src/rng/hmac_rng/hmac_rng.cpp @@ -8,7 +8,6 @@ #include <botan/hmac_rng.h> #include <botan/get_byte.h> #include <botan/internal/xor_buf.h> -#include <botan/internal/stl_util.h> #include <algorithm> namespace Botan { @@ -75,7 +74,8 @@ void HMAC_RNG::reseed(size_t poll_bits) while(!accum.polling_goal_achieved() && poll_attempt < poll_bits) { - entropy_sources[poll_attempt % entropy_sources.size()]->poll(accum); + const size_t src_idx = poll_attempt % entropy_sources.size(); + entropy_sources[src_idx]->poll(accum); ++poll_attempt; } } @@ -110,7 +110,11 @@ void HMAC_RNG::reseed(size_t poll_bits) counter = 0; user_input_len = 0; - if(accum.bits_collected() >= 128) + /* + Consider ourselves seeded once we've collected an estimated 128 bits of + entropy in a single poll. + */ + if(seeded == false && accum.bits_collected() >= 128) seeded = true; } @@ -119,15 +123,18 @@ void HMAC_RNG::reseed(size_t poll_bits) */ void HMAC_RNG::add_entropy(const byte input[], size_t length) { + const size_t USER_ENTROPY_WATERSHED = 20; + extractor->update(input, length); user_input_len += length; /* - * After we've accumulated >= 1024 bytes of user input, reseed. - * This input will automatically have been included if reseed was - * called already, as it's just included in the extractor input. + * After we've accumulated at least USER_ENTROPY_WATERSHED bytes of + * user input, reseed. This input will automatically have been + * included if reseed was called already, as it's just included in + * the extractor input. */ - if(user_input_len >= 1024) + if(user_input_len >= USER_ENTROPY_WATERSHED) reseed(128); } @@ -216,8 +223,8 @@ HMAC_RNG::~HMAC_RNG() delete extractor; delete prf; - std::for_each(entropy_sources.begin(), entropy_sources.end(), - del_fun<EntropySource>()); + for(auto src : entropy_sources) + delete src; counter = 0; } diff --git a/src/rng/randpool/randpool.cpp b/src/rng/randpool/randpool.cpp index 92f225a9c..51354db12 100644 --- a/src/rng/randpool/randpool.cpp +++ b/src/rng/randpool/randpool.cpp @@ -8,8 +8,8 @@ #include <botan/randpool.h> #include <botan/get_byte.h> #include <botan/internal/xor_buf.h> -#include <botan/internal/stl_util.h> #include <algorithm> +#include <chrono> namespace Botan { @@ -202,8 +202,8 @@ Randpool::~Randpool() delete cipher; delete mac; - std::for_each(entropy_sources.begin(), entropy_sources.end(), - del_fun<EntropySource>()); + for(auto i = entropy_sources.begin(); i != entropy_sources.end(); ++i) + delete *i; } } diff --git a/src/selftest/selftest.cpp b/src/selftest/selftest.cpp index 7b87bcb61..8f4dc70d8 100644 --- a/src/selftest/selftest.cpp +++ b/src/selftest/selftest.cpp @@ -10,8 +10,6 @@ #include <botan/internal/core_engine.h> #include <botan/internal/stl_util.h> -#include <stdio.h> - namespace Botan { namespace { @@ -28,8 +26,6 @@ bool test_filter_kat(Filter* filter, const std::string output = pipe.read_all_as_string(); - //printf("%s %s\n", output.c_str(), expected_output.c_str()); - return (output == expected_output); } @@ -129,8 +125,7 @@ namespace { void verify_results(const std::string& algo, const std::map<std::string, bool>& results) { - for(std::map<std::string, bool>::const_iterator i = results.begin(); - i != results.end(); ++i) + for(auto i = results.begin(); i != results.end(); ++i) { if(!i->second) throw Self_Test_Failure(algo + " self-test failed, provider "+ diff --git a/src/stream/arc4/arc4.cpp b/src/stream/arc4/arc4.cpp index 6eea7bb45..a25b68185 100644 --- a/src/stream/arc4/arc4.cpp +++ b/src/stream/arc4/arc4.cpp @@ -85,7 +85,7 @@ std::string ARC4::name() const { if(SKIP == 0) return "ARC4"; if(SKIP == 256) return "MARK-4"; - else return "RC4_skip(" + to_string(SKIP) + ")"; + else return "RC4_skip(" + std::to_string(SKIP) + ")"; } /* diff --git a/src/tls/c_hello.cpp b/src/tls/c_hello.cpp index 3428225d0..b08e1abe2 100644 --- a/src/tls/c_hello.cpp +++ b/src/tls/c_hello.cpp @@ -11,7 +11,7 @@ #include <botan/internal/tls_extensions.h> #include <botan/tls_record.h> #include <botan/internal/stl_util.h> -#include <botan/time.h> +#include <chrono> namespace Botan { @@ -20,7 +20,10 @@ namespace TLS { MemoryVector<byte> make_hello_random(RandomNumberGenerator& rng) { MemoryVector<byte> buf(32); - const u32bit time32 = system_time(); + + const u32bit time32 = static_cast<u32bit>( + std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); + store_be(time32, buf); rng.randomize(&buf[4], buf.size() - 4); return buf; diff --git a/src/tls/c_kex.cpp b/src/tls/c_kex.cpp index ed571852c..0e7eba23a 100644 --- a/src/tls/c_kex.cpp +++ b/src/tls/c_kex.cpp @@ -147,7 +147,8 @@ Client_Key_Exchange::Client_Key_Exchange(Record_Writer& writer, const std::string name = Supported_Elliptic_Curves::curve_id_to_name(curve_id); if(name == "") - throw Decoding_Error("Server sent unknown named curve " + to_string(curve_id)); + throw Decoding_Error("Server sent unknown named curve " + + std::to_string(curve_id)); EC_Group group(name); @@ -187,7 +188,7 @@ Client_Key_Exchange::Client_Key_Exchange(Record_Writer& writer, if(peer_certs.empty()) throw Internal_Error("No certificate and no server key exchange"); - std::auto_ptr<Public_Key> pub_key(peer_certs[0].subject_public_key()); + std::unique_ptr<Public_Key> pub_key(peer_certs[0].subject_public_key()); if(const RSA_PublicKey* rsa_pub = dynamic_cast<const RSA_PublicKey*>(pub_key.get())) { diff --git a/src/tls/cert_ver.cpp b/src/tls/cert_ver.cpp index 73acf3de1..0a377b35f 100644 --- a/src/tls/cert_ver.cpp +++ b/src/tls/cert_ver.cpp @@ -93,7 +93,7 @@ MemoryVector<byte> Certificate_Verify::serialize() const bool Certificate_Verify::verify(const X509_Certificate& cert, Handshake_State* state) { - std::auto_ptr<Public_Key> key(cert.subject_public_key()); + std::unique_ptr<Public_Key> key(cert.subject_public_key()); std::pair<std::string, Signature_Format> format = state->understand_sig_format(key.get(), hash_algo, sig_algo, true); diff --git a/src/tls/finished.cpp b/src/tls/finished.cpp index a494bf932..bb6e8d20e 100644 --- a/src/tls/finished.cpp +++ b/src/tls/finished.cpp @@ -47,7 +47,7 @@ MemoryVector<byte> finished_compute_verify(Handshake_State* state, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x66, 0x69, 0x6E, 0x69, 0x73, 0x68, 0x65, 0x64 }; - std::auto_ptr<KDF> prf(state->protocol_specific_prf()); + std::unique_ptr<KDF> prf(state->protocol_specific_prf()); MemoryVector<byte> input; if(side == CLIENT) diff --git a/src/tls/info.txt b/src/tls/info.txt index ff84c3448..b19eedb20 100644 --- a/src/tls/info.txt +++ b/src/tls/info.txt @@ -5,8 +5,6 @@ The TLS code is complex, new, and not yet reviewed, there may be serious bugs or security issues. </comment> -uses_tr1 yes - <header:public> tls_alert.h tls_channel.h diff --git a/src/tls/rec_read.cpp b/src/tls/rec_read.cpp index d1fab4692..bd6ae5af9 100644 --- a/src/tls/rec_read.cpp +++ b/src/tls/rec_read.cpp @@ -219,7 +219,7 @@ size_t Record_Reader::add_input(const byte input_array[], size_t input_sz, m_readbuf[0] != APPLICATION_DATA) { throw Unexpected_Message( - "Unknown record type " + to_string(m_readbuf[0]) + " from counterparty"); + "Unknown record type " + std::to_string(m_readbuf[0]) + " from counterparty"); } const size_t record_len = make_u16bit(m_readbuf[3], m_readbuf[4]); diff --git a/src/tls/rec_wri.cpp b/src/tls/rec_wri.cpp index 85f178ffe..3a54d7931 100644 --- a/src/tls/rec_wri.cpp +++ b/src/tls/rec_wri.cpp @@ -22,7 +22,7 @@ namespace TLS { /* * Record_Writer Constructor */ -Record_Writer::Record_Writer(std::tr1::function<void (const byte[], size_t)> out) : +Record_Writer::Record_Writer(std::function<void (const byte[], size_t)> out) : m_output_fn(out), m_writebuf(TLS_HEADER_SIZE + MAX_CIPHERTEXT_SIZE), m_mac(0) @@ -306,8 +306,8 @@ void Record_Writer::send_record(byte type, const byte input[], size_t length) */ void Record_Writer::send_alert(const Alert& alert) { - const byte alert_bits[2] = { alert.is_fatal() ? 2 : 1, - alert.type() }; + const byte alert_bits[2] = { static_cast<byte>(alert.is_fatal() ? 2 : 1), + static_cast<byte>(alert.type()) }; send(ALERT, alert_bits, sizeof(alert_bits)); } diff --git a/src/tls/s_kex.cpp b/src/tls/s_kex.cpp index 6707d2611..0890cac49 100644 --- a/src/tls/s_kex.cpp +++ b/src/tls/s_kex.cpp @@ -47,7 +47,7 @@ Server_Key_Exchange::Server_Key_Exchange(Record_Writer& writer, if(kex_algo == "DH" || kex_algo == "DHE_PSK") { - std::auto_ptr<DH_PrivateKey> dh(new DH_PrivateKey(rng, policy.dh_group())); + std::unique_ptr<DH_PrivateKey> dh(new DH_PrivateKey(rng, policy.dh_group())); append_tls_length_value(m_params, BigInt::encode(dh->get_domain().get_p()), 2); append_tls_length_value(m_params, BigInt::encode(dh->get_domain().get_g()), 2); @@ -70,7 +70,7 @@ Server_Key_Exchange::Server_Key_Exchange(Record_Writer& writer, EC_Group ec_group(curve_name); - std::auto_ptr<ECDH_PrivateKey> ecdh(new ECDH_PrivateKey(rng, ec_group)); + std::unique_ptr<ECDH_PrivateKey> ecdh(new ECDH_PrivateKey(rng, ec_group)); const std::string ecdh_domain_oid = ecdh->domain().get_oid(); const std::string domain = OIDS::lookup(OID(ecdh_domain_oid)); @@ -160,7 +160,7 @@ Server_Key_Exchange::Server_Key_Exchange(const MemoryRegion<byte>& buf, if(name == "") throw Decoding_Error("Server_Key_Exchange: Server sent unknown named curve " + - to_string(curve_id)); + std::to_string(curve_id)); m_params.push_back(curve_type); m_params.push_back(get_byte(0, curve_id)); @@ -211,7 +211,7 @@ MemoryVector<byte> Server_Key_Exchange::serialize() const bool Server_Key_Exchange::verify(const X509_Certificate& cert, Handshake_State* state) const { - std::auto_ptr<Public_Key> key(cert.subject_public_key()); + std::unique_ptr<Public_Key> key(cert.subject_public_key()); std::pair<std::string, Signature_Format> format = state->understand_sig_format(key.get(), m_hash_algo, m_sig_algo, false); diff --git a/src/tls/tls_alert.cpp b/src/tls/tls_alert.cpp index b526eeac3..30c51d4c8 100644 --- a/src/tls/tls_alert.cpp +++ b/src/tls/tls_alert.cpp @@ -15,7 +15,7 @@ namespace TLS { Alert::Alert(const MemoryRegion<byte>& buf) { if(buf.size() != 2) - throw Decoding_Error("Alert: Bad size " + to_string(buf.size()) + + throw Decoding_Error("Alert: Bad size " + std::to_string(buf.size()) + " for alert message"); if(buf[0] == 1) fatal = false; @@ -106,7 +106,7 @@ std::string Alert::type_string() const * compiler can warn us that it is not included in the switch * statement. */ - return "unrecognized_alert_" + to_string(type()); + return "unrecognized_alert_" + std::to_string(type()); } diff --git a/src/tls/tls_channel.cpp b/src/tls/tls_channel.cpp index f45ce4bda..736b37654 100644 --- a/src/tls/tls_channel.cpp +++ b/src/tls/tls_channel.cpp @@ -15,9 +15,9 @@ namespace Botan { namespace TLS { -Channel::Channel(std::tr1::function<void (const byte[], size_t)> socket_output_fn, - std::tr1::function<void (const byte[], size_t, Alert)> proc_fn, - std::tr1::function<bool (const Session&)> handshake_complete) : +Channel::Channel(std::function<void (const byte[], size_t)> socket_output_fn, + std::function<void (const byte[], size_t, Alert)> proc_fn, + std::function<bool (const Session&)> handshake_complete) : proc_fn(proc_fn), handshake_fn(handshake_complete), writer(socket_output_fn), @@ -106,7 +106,7 @@ size_t Channel::received_data(const byte buf[], size_t buf_size) } else throw Unexpected_Message("Unknown TLS message type " + - to_string(rec_type) + " received"); + std::to_string(rec_type) + " received"); } return 0; // on a record boundary diff --git a/src/tls/tls_channel.h b/src/tls/tls_channel.h index 53af0bdfc..9ab89e5f7 100644 --- a/src/tls/tls_channel.h +++ b/src/tls/tls_channel.h @@ -62,9 +62,9 @@ class BOTAN_DLL Channel */ std::vector<X509_Certificate> peer_cert_chain() const { return peer_certs; } - Channel(std::tr1::function<void (const byte[], size_t)> socket_output_fn, - std::tr1::function<void (const byte[], size_t, Alert)> proc_fn, - std::tr1::function<bool (const Session&)> handshake_complete); + Channel(std::function<void (const byte[], size_t)> socket_output_fn, + std::function<void (const byte[], size_t, Alert)> proc_fn, + std::function<bool (const Session&)> handshake_complete); virtual ~Channel(); protected: @@ -85,8 +85,8 @@ class BOTAN_DLL Channel virtual void alert_notify(const Alert& alert) = 0; - std::tr1::function<void (const byte[], size_t, Alert)> proc_fn; - std::tr1::function<bool (const Session&)> handshake_fn; + std::function<void (const byte[], size_t, Alert)> proc_fn; + std::function<bool (const Session&)> handshake_fn; Record_Writer writer; Record_Reader reader; diff --git a/src/tls/tls_ciphersuite.cpp b/src/tls/tls_ciphersuite.cpp index 247948464..89daaf679 100644 --- a/src/tls/tls_ciphersuite.cpp +++ b/src/tls/tls_ciphersuite.cpp @@ -310,7 +310,7 @@ std::string Ciphersuite::to_string() const if(cipher_algo() == "3DES") out << "3DES_EDE"; else if(cipher_algo() == "Camellia") - out << "CAMELLIA_" << Botan::to_string(8*cipher_keylen()); + out << "CAMELLIA_" << std::to_string(8*cipher_keylen()); else out << replace_char(cipher_algo(), '-', '_'); diff --git a/src/tls/tls_client.cpp b/src/tls/tls_client.cpp index ba9ec8082..77e87e9bc 100644 --- a/src/tls/tls_client.cpp +++ b/src/tls/tls_client.cpp @@ -18,15 +18,15 @@ namespace TLS { /* * TLS Client Constructor */ -Client::Client(std::tr1::function<void (const byte[], size_t)> output_fn, - std::tr1::function<void (const byte[], size_t, Alert)> proc_fn, - std::tr1::function<bool (const Session&)> handshake_fn, +Client::Client(std::function<void (const byte[], size_t)> output_fn, + std::function<void (const byte[], size_t, Alert)> proc_fn, + std::function<bool (const Session&)> handshake_fn, Session_Manager& session_manager, Credentials_Manager& creds, const Policy& policy, RandomNumberGenerator& rng, const std::string& hostname, - std::tr1::function<std::string (std::vector<std::string>)> next_protocol) : + std::function<std::string (std::vector<std::string>)> next_protocol) : Channel(output_fn, proc_fn, handshake_fn), policy(policy), rng(rng), @@ -288,7 +288,7 @@ void Client::process_handshake_msg(Handshake_Type type, throw TLS_Exception(Alert::BAD_CERTIFICATE, e.what()); } - std::auto_ptr<Public_Key> peer_key(peer_certs[0].subject_public_key()); + std::unique_ptr<Public_Key> peer_key(peer_certs[0].subject_public_key()); if(peer_key->algo_name() != state->suite.sig_algo()) throw TLS_Exception(Alert::ILLEGAL_PARAMETER, diff --git a/src/tls/tls_client.h b/src/tls/tls_client.h index 5c2692cd6..cd972fa28 100644 --- a/src/tls/tls_client.h +++ b/src/tls/tls_client.h @@ -42,16 +42,16 @@ class BOTAN_DLL Client : public Channel * called with the list of protocols the server advertised; * the client should return the protocol it would like to use. */ - Client(std::tr1::function<void (const byte[], size_t)> socket_output_fn, - std::tr1::function<void (const byte[], size_t, Alert)> proc_fn, - std::tr1::function<bool (const Session&)> handshake_complete, + Client(std::function<void (const byte[], size_t)> socket_output_fn, + std::function<void (const byte[], size_t, Alert)> proc_fn, + std::function<bool (const Session&)> handshake_complete, Session_Manager& session_manager, Credentials_Manager& creds, const Policy& policy, RandomNumberGenerator& rng, const std::string& servername = "", - std::tr1::function<std::string (std::vector<std::string>)> next_protocol = - std::tr1::function<std::string (std::vector<std::string>)>()); + std::function<std::string (std::vector<std::string>)> next_protocol = + std::function<std::string (std::vector<std::string>)>()); void renegotiate(); private: diff --git a/src/tls/tls_extensions.cpp b/src/tls/tls_extensions.cpp index 1ca4e3eb4..c0de24bfe 100644 --- a/src/tls/tls_extensions.cpp +++ b/src/tls/tls_extensions.cpp @@ -242,7 +242,7 @@ Maximum_Fragment_Length::Maximum_Fragment_Length(size_t max_fragment) else if(max_fragment == 4096) val = 4; else - throw std::invalid_argument("Bad setting " + to_string(max_fragment) + + throw std::invalid_argument("Bad setting " + std::to_string(max_fragment) + " for maximum fragment size"); } diff --git a/src/tls/tls_handshake_hash.cpp b/src/tls/tls_handshake_hash.cpp index 61295a95c..a9bd8dccf 100644 --- a/src/tls/tls_handshake_hash.cpp +++ b/src/tls/tls_handshake_hash.cpp @@ -35,7 +35,7 @@ SecureVector<byte> Handshake_Hash::final(Protocol_Version version, { Algorithm_Factory& af = global_state().algorithm_factory(); - std::auto_ptr<HashFunction> hash; + std::unique_ptr<HashFunction> hash; if(version == Protocol_Version::TLS_V10 || version == Protocol_Version::TLS_V11) { @@ -65,8 +65,8 @@ SecureVector<byte> Handshake_Hash::final_ssl3(const MemoryRegion<byte>& secret) Algorithm_Factory& af = global_state().algorithm_factory(); - std::auto_ptr<HashFunction> md5(af.make_hash_function("MD5")); - std::auto_ptr<HashFunction> sha1(af.make_hash_function("SHA-1")); + std::unique_ptr<HashFunction> md5(af.make_hash_function("MD5")); + std::unique_ptr<HashFunction> sha1(af.make_hash_function("SHA-1")); md5->update(data); sha1->update(data); diff --git a/src/tls/tls_handshake_state.cpp b/src/tls/tls_handshake_state.cpp index 6ddd8d346..b34d8616d 100644 --- a/src/tls/tls_handshake_state.cpp +++ b/src/tls/tls_handshake_state.cpp @@ -68,7 +68,7 @@ u32bit bitmask_for_handshake_type(Handshake_Type type) return 0; default: - throw Internal_Error("Unknown handshake type " + to_string(type)); + throw Internal_Error("Unknown handshake type " + std::to_string(type)); } return 0; @@ -121,8 +121,8 @@ void Handshake_State::confirm_transition_to(Handshake_Type handshake_msg) if(!ok) throw Unexpected_Message("Unexpected state transition in handshake, got " + - to_string(handshake_msg) + " mask is " + - to_string(hand_expecting_mask)); + std::to_string(handshake_msg) + " mask is " + + std::to_string(hand_expecting_mask)); /* We don't know what to expect next, so force a call to set_expected_next; if it doesn't happen, the next transition diff --git a/src/tls/tls_handshake_state.h b/src/tls/tls_handshake_state.h index 2a78d1d1e..d2f64c43b 100644 --- a/src/tls/tls_handshake_state.h +++ b/src/tls/tls_handshake_state.h @@ -15,20 +15,7 @@ #include <botan/pubkey.h> #include <utility> - -#if defined(BOTAN_USE_STD_TR1) - -#if defined(BOTAN_BUILD_COMPILER_IS_MSVC) - #include <functional> -#else - #include <tr1/functional> -#endif - -#elif defined(BOTAN_USE_BOOST_TR1) - #include <boost/tr1/functional.hpp> -#else - #error "No TR1 library defined for use" -#endif +#include <functional> namespace Botan { @@ -102,7 +89,7 @@ class Handshake_State /** * Used by client using NPN */ - std::tr1::function<std::string (std::vector<std::string>)> client_npn_cb; + std::function<std::string (std::vector<std::string>)> client_npn_cb; Handshake_Reader* handshake_reader() { return m_handshake_reader; } private: diff --git a/src/tls/tls_reader.h b/src/tls/tls_reader.h index f6b0d4088..bf8098bed 100644 --- a/src/tls/tls_reader.h +++ b/src/tls/tls_reader.h @@ -163,8 +163,8 @@ class TLS_Data_Reader { if(buf.size() - offset < n) { - throw Decoding_Error("TLS_Data_Reader: Expected " + to_string(n) + - " bytes remaining, only " + to_string(buf.size()-offset) + + throw Decoding_Error("TLS_Data_Reader: Expected " + std::to_string(n) + + " bytes remaining, only " + std::to_string(buf.size()-offset) + " left"); } } diff --git a/src/tls/tls_record.h b/src/tls/tls_record.h index fb27db5e2..b966e3c72 100644 --- a/src/tls/tls_record.h +++ b/src/tls/tls_record.h @@ -16,20 +16,7 @@ #include <botan/mac.h> #include <botan/secqueue.h> #include <vector> - -#if defined(BOTAN_USE_STD_TR1) - -#if defined(BOTAN_BUILD_COMPILER_IS_MSVC) - #include <functional> -#else - #include <tr1/functional> -#endif - -#elif defined(BOTAN_USE_BOOST_TR1) - #include <boost/tr1/functional.hpp> -#else - #error "No TR1 library defined for use" -#endif +#include <functional> namespace Botan { @@ -61,7 +48,7 @@ class BOTAN_DLL Record_Writer void set_maximum_fragment_size(size_t max_fragment); - Record_Writer(std::tr1::function<void (const byte[], size_t)> output_fn); + Record_Writer(std::function<void (const byte[], size_t)> output_fn); ~Record_Writer() { delete m_mac; } private: @@ -70,7 +57,7 @@ class BOTAN_DLL Record_Writer void send_record(byte type, const byte input[], size_t length); - std::tr1::function<void (const byte[], size_t)> m_output_fn; + std::function<void (const byte[], size_t)> m_output_fn; MemoryVector<byte> m_writebuf; diff --git a/src/tls/tls_server.cpp b/src/tls/tls_server.cpp index 1f69d153e..3b4a526cc 100644 --- a/src/tls/tls_server.cpp +++ b/src/tls/tls_server.cpp @@ -106,9 +106,9 @@ get_server_certs(const std::string& hostname, /* * TLS Server Constructor */ -Server::Server(std::tr1::function<void (const byte[], size_t)> output_fn, - std::tr1::function<void (const byte[], size_t, Alert)> proc_fn, - std::tr1::function<bool (const Session&)> handshake_fn, +Server::Server(std::function<void (const byte[], size_t)> output_fn, + std::function<void (const byte[], size_t, Alert)> proc_fn, + std::function<bool (const Session&)> handshake_fn, Session_Manager& session_manager, Credentials_Manager& creds, const Policy& policy, diff --git a/src/tls/tls_server.h b/src/tls/tls_server.h index 025bbf3ec..a90982066 100644 --- a/src/tls/tls_server.h +++ b/src/tls/tls_server.h @@ -26,9 +26,9 @@ class BOTAN_DLL Server : public Channel /** * Server initialization */ - Server(std::tr1::function<void (const byte[], size_t)> socket_output_fn, - std::tr1::function<void (const byte[], size_t, Alert)> proc_fn, - std::tr1::function<bool (const Session&)> handshake_complete, + Server(std::function<void (const byte[], size_t)> socket_output_fn, + std::function<void (const byte[], size_t, Alert)> proc_fn, + std::function<bool (const Session&)> handshake_complete, Session_Manager& session_manager, Credentials_Manager& creds, const Policy& policy, diff --git a/src/tls/tls_session.cpp b/src/tls/tls_session.cpp index 2a532196d..44689b510 100644 --- a/src/tls/tls_session.cpp +++ b/src/tls/tls_session.cpp @@ -10,7 +10,6 @@ #include <botan/ber_dec.h> #include <botan/asn1_str.h> #include <botan/pem.h> -#include <botan/time.h> #include <botan/lookup.h> #include <botan/loadstor.h> #include <memory> @@ -20,18 +19,17 @@ namespace Botan { namespace TLS { Session::Session(const MemoryRegion<byte>& session_identifier, - const MemoryRegion<byte>& master_secret, - Protocol_Version version, - u16bit ciphersuite, - byte compression_method, - Connection_Side side, - bool secure_renegotiation_supported, - size_t fragment_size, - const std::vector<X509_Certificate>& certs, - const MemoryRegion<byte>& ticket, - const std::string& sni_hostname, - const std::string& srp_identifier) : - m_start_time(system_time()), + const MemoryRegion<byte>& master_secret, + Protocol_Version version, + u16bit ciphersuite, + byte compression_method, + Connection_Side side, + bool secure_renegotiation_supported, + size_t fragment_size, + const std::vector<X509_Certificate>& certs, + const std::string& sni_hostname, + const std::string& srp_identifier) : + m_start_time(std::chrono::system_clock::now()), m_identifier(session_identifier), m_session_ticket(ticket), m_master_secret(master_secret), @@ -64,6 +62,8 @@ Session::Session(const byte ber[], size_t ber_len) MemoryVector<byte> peer_cert_bits; + size_t start_time = 0; + BER_Decoder(ber, ber_len) .start_cons(SEQUENCE) .decode_and_check(static_cast<size_t>(TLS_SESSION_PARAM_STRUCT_VERSION), @@ -86,6 +86,7 @@ Session::Session(const byte ber[], size_t ber_len) .verify_end(); m_version = Protocol_Version(major_version, minor_version); + m_start_time = std::chrono::system_clock::from_time_t(start_time); m_sni_hostname = sni_hostname_str.value(); m_srp_identifier = srp_identifier_str.value(); m_connection_side = static_cast<Connection_Side>(side_code); @@ -108,7 +109,7 @@ SecureVector<byte> Session::DER_encode() const return DER_Encoder() .start_cons(SEQUENCE) .encode(static_cast<size_t>(TLS_SESSION_PARAM_STRUCT_VERSION)) - .encode(static_cast<size_t>(m_start_time)) + .encode(static_cast<size_t>(std::chrono::system_clock::to_time_t(m_start_time))) .encode(static_cast<size_t>(m_version.major_version())) .encode(static_cast<size_t>(m_version.minor_version())) .encode(m_identifier, OCTET_STRING) diff --git a/src/tls/tls_session.h b/src/tls/tls_session.h index 0c57201a4..8fc048c75 100644 --- a/src/tls/tls_session.h +++ b/src/tls/tls_session.h @@ -14,6 +14,7 @@ #include <botan/tls_magic.h> #include <botan/secmem.h> #include <botan/symkey.h> +#include <chrono> namespace Botan { @@ -30,7 +31,7 @@ class BOTAN_DLL Session * Uninitialized session */ Session() : - m_start_time(0), + m_start_time(std::chrono::system_clock::time_point::min()), m_version(), m_ciphersuite(0), m_compression_method(0), @@ -174,7 +175,8 @@ class BOTAN_DLL Session /** * Get the time this session began (seconds since Epoch) */ - u64bit start_time() const { return m_start_time; } + std::chrono::system_clock::time_point start_time() const + { return m_start_time; } /** * Return the session ticket the server gave us @@ -184,7 +186,7 @@ class BOTAN_DLL Session private: enum { TLS_SESSION_PARAM_STRUCT_VERSION = 0x2994e300 }; - u64bit m_start_time; + std::chrono::system_clock::time_point m_start_time; MemoryVector<byte> m_identifier; MemoryVector<byte> m_session_ticket; // only used by client side diff --git a/src/tls/tls_session_key.cpp b/src/tls/tls_session_key.cpp index edd0617bc..4d7603ce1 100644 --- a/src/tls/tls_session_key.cpp +++ b/src/tls/tls_session_key.cpp @@ -37,7 +37,7 @@ Session_Keys::Session_Keys(Handshake_State* state, const byte KEY_GEN_MAGIC[] = { 0x6B, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6E, 0x73, 0x69, 0x6F, 0x6E }; - std::auto_ptr<KDF> prf(state->protocol_specific_prf()); + std::unique_ptr<KDF> prf(state->protocol_specific_prf()); if(resuming) { diff --git a/src/tls/tls_session_manager.cpp b/src/tls/tls_session_manager.cpp index 59fc75b9f..4c6bc1a47 100644 --- a/src/tls/tls_session_manager.cpp +++ b/src/tls/tls_session_manager.cpp @@ -7,7 +7,7 @@ #include <botan/tls_session_manager.h> #include <botan/hex.h> -#include <botan/time.h> +#include <chrono> namespace Botan { @@ -16,13 +16,16 @@ namespace TLS { bool Session_Manager_In_Memory::load_from_session_str( const std::string& session_str, Session& session) { - std::map<std::string, Session>::iterator i = sessions.find(session_str); + // assert(lock is held) + + auto i = sessions.find(session_str); if(i == sessions.end()) return false; - // session has expired, remove it - const u64bit now = system_time(); + // if session has expired, remove it + const auto now = std::chrono::system_clock::now(); + if(i->second.start_time() + session_lifetime < now) { sessions.erase(i); @@ -36,16 +39,20 @@ bool Session_Manager_In_Memory::load_from_session_str( bool Session_Manager_In_Memory::load_from_session_id( const MemoryRegion<byte>& session_id, Session& session) { + std::lock_guard<std::mutex> lock(mutex); + return load_from_session_str(hex_encode(session_id), session); } bool Session_Manager_In_Memory::load_from_host_info( const std::string& hostname, u16bit port, Session& session) { + std::lock_guard<std::mutex> lock(mutex); + std::map<std::string, std::string>::iterator i; if(port > 0) - i = host_sessions.find(hostname + ":" + to_string(port)); + i = host_sessions.find(hostname + ":" + std::to_string(port)); else i = host_sessions.find(hostname); @@ -64,8 +71,9 @@ bool Session_Manager_In_Memory::load_from_host_info( void Session_Manager_In_Memory::remove_entry( const MemoryRegion<byte>& session_id) { - std::map<std::string, Session>::iterator i = - sessions.find(hex_encode(session_id)); + std::lock_guard<std::mutex> lock(mutex); + + auto i = sessions.find(hex_encode(session_id)); if(i != sessions.end()) sessions.erase(i); @@ -73,6 +81,8 @@ void Session_Manager_In_Memory::remove_entry( void Session_Manager_In_Memory::save(const Session& session) { + std::lock_guard<std::mutex> lock(mutex); + if(max_sessions != 0) { /* diff --git a/src/tls/tls_session_manager.h b/src/tls/tls_session_manager.h index c0a9996e3..4152f2392 100644 --- a/src/tls/tls_session_manager.h +++ b/src/tls/tls_session_manager.h @@ -9,6 +9,8 @@ #define TLS_SESSION_MANAGER_H__ #include <botan/tls_session.h> +#include <mutex> +#include <chrono> #include <map> namespace Botan { @@ -69,8 +71,6 @@ class BOTAN_DLL Session_Manager /** * A simple implementation of Session_Manager that just saves * values in memory, with no persistance abilities -* -* @todo add locking */ class BOTAN_DLL Session_Manager_In_Memory : public Session_Manager { @@ -82,7 +82,7 @@ class BOTAN_DLL Session_Manager_In_Memory : public Session_Manager * seconds have elapsed from initial handshake. */ Session_Manager_In_Memory(size_t max_sessions = 1000, - size_t session_lifetime = 7200) : + std::chrono::seconds session_lifetime = std::chrono::seconds(7200)) : max_sessions(max_sessions), session_lifetime(session_lifetime) {} @@ -101,7 +101,10 @@ class BOTAN_DLL Session_Manager_In_Memory : public Session_Manager bool load_from_session_str(const std::string& session_str, Session& session); - size_t max_sessions, session_lifetime; + std::mutex mutex; + + size_t max_sessions; + std::chrono::seconds session_lifetime; std::map<std::string, Session> sessions; // hex(session_id) -> session std::map<std::string, std::string> host_sessions; diff --git a/src/tls/tls_version.cpp b/src/tls/tls_version.cpp index 4445998eb..82dce0be9 100644 --- a/src/tls/tls_version.cpp +++ b/src/tls/tls_version.cpp @@ -19,13 +19,13 @@ std::string Protocol_Version::to_string() const // Some very new or very old protocol? if(maj != 3) - return "Protocol " + Botan::to_string(maj) + "." + Botan::to_string(min); + return "Protocol " + std::to_string(maj) + "." + std::to_string(min); if(maj == 3 && min == 0) return "SSL v3"; // The TLS v1.[0123...] case - return "TLS v1." + Botan::to_string(min-1); + return "TLS v1." + std::to_string(min-1); } } diff --git a/src/utils/calendar.cpp b/src/utils/calendar.cpp new file mode 100644 index 000000000..14f0113f2 --- /dev/null +++ b/src/utils/calendar.cpp @@ -0,0 +1,52 @@ +/* +* Calendar Functions +* (C) 1999-2010 Jack Lloyd +* +* Distributed under the terms of the Botan license +*/ + +#include <botan/calendar.h> +#include <botan/exceptn.h> +#include <ctime> + +namespace Botan { + +namespace { + +std::tm do_gmtime(std::time_t time_val) + { + std::tm tm; + +#if defined(BOTAN_TARGET_OS_HAS_GMTIME_S) + gmtime_s(&tm, &time_val); // Windows +#elif defined(BOTAN_TARGET_OS_HAS_GMTIME_R) + gmtime_r(&time_val, &tm); // Unix/SUSv2 +#else + std::tm* tm_p = std::gmtime(&time_val); + if (tm_p == 0) + throw Encoding_Error("time_t_to_tm could not convert"); + tm = *tm_p; +#endif + + return tm; + } + +} + +/* +* Convert a time_point to a calendar_point +*/ +calendar_point calendar_value( + const std::chrono::system_clock::time_point& time_point) + { + std::tm tm = do_gmtime(std::chrono::system_clock::to_time_t(time_point)); + + return calendar_point(tm.tm_year + 1900, + tm.tm_mon + 1, + tm.tm_mday, + tm.tm_hour, + tm.tm_min, + tm.tm_sec); + } + +} diff --git a/src/utils/time.h b/src/utils/calendar.h index fcc956df2..d617cc9a0 100644 --- a/src/utils/time.h +++ b/src/utils/calendar.h @@ -1,14 +1,15 @@ /* -* Time Functions +* Calendar Functions * (C) 1999-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ -#ifndef BOTAN_TIME_H__ -#define BOTAN_TIME_H__ +#ifndef BOTAN_CALENDAR_H__ +#define BOTAN_CALENDAR_H__ #include <botan/types.h> +#include <chrono> namespace Botan { @@ -50,21 +51,12 @@ struct BOTAN_DLL calendar_point year(y), month(mon), day(d), hour(h), minutes(min), seconds(sec) {} }; -/** +/* * @param time_point a time point from the system clock * @return calendar_point object representing this time point */ -BOTAN_DLL calendar_point calendar_value(u64bit time_point); - -/** -* @return seconds resolution timestamp, unknown epoch -*/ -BOTAN_DLL u64bit system_time(); - -/** -* @return nanoseconds resolution timestamp, unknown epoch -*/ -BOTAN_DLL u64bit get_nanoseconds_clock(); +BOTAN_DLL calendar_point calendar_value( + const std::chrono::system_clock::time_point& time_point); } diff --git a/src/utils/charset.cpp b/src/utils/charset.cpp index 8e20e6492..7ee637f80 100644 --- a/src/utils/charset.cpp +++ b/src/utils/charset.cpp @@ -119,7 +119,7 @@ std::string transcode(const std::string& str, return ucs2_to_latin1(str); throw Invalid_Argument("Unknown transcoding operation from " + - to_string(from) + " to " + to_string(to)); + std::to_string(from) + " to " + std::to_string(to)); } /* diff --git a/src/utils/datastor/datastor.cpp b/src/utils/datastor/datastor.cpp index 49e7b2dda..363136c69 100644 --- a/src/utils/datastor/datastor.cpp +++ b/src/utils/datastor/datastor.cpp @@ -14,16 +14,6 @@ namespace Botan { /* -* Default Matcher transform operation (identity) -*/ -std::pair<std::string, std::string> -Data_Store::Matcher::transform(const std::string& key, - const std::string& value) const - { - return std::make_pair(key, value); - } - -/* * Data_Store Equality Comparison */ bool Data_Store::operator==(const Data_Store& other) const @@ -42,26 +32,14 @@ bool Data_Store::has_value(const std::string& key) const /* * Search based on an arbitrary predicate */ -std::multimap<std::string, std::string> -Data_Store::search_with(const Matcher& matcher) const +std::multimap<std::string, std::string> Data_Store::search_for( + std::function<bool (std::string, std::string)> predicate) const { std::multimap<std::string, std::string> out; - std::multimap<std::string, std::string>::const_iterator i = - contents.begin(); - - while(i != contents.end()) - { - if(matcher(i->first, i->second)) - { - std::pair<std::string, std::string> p( - matcher.transform(i->first, i->second)); - - multimap_insert(out, p.first, p.second); - } - - ++i; - } + for(auto i = contents.begin(); i != contents.end(); ++i) + if(predicate(i->first, i->second)) + out.insert(std::make_pair(i->first, i->second)); return out; } @@ -71,12 +49,9 @@ Data_Store::search_with(const Matcher& matcher) const */ std::vector<std::string> Data_Store::get(const std::string& looking_for) const { - typedef std::multimap<std::string, std::string>::const_iterator iter; - - std::pair<iter, iter> range = contents.equal_range(looking_for); - std::vector<std::string> out; - for(iter i = range.first; i != range.second; ++i) + auto range = contents.equal_range(looking_for); + for(auto i = range.first; i != range.second; ++i) out.push_back(i->second); return out; } @@ -144,7 +119,7 @@ void Data_Store::add(const std::string& key, const std::string& val) */ void Data_Store::add(const std::string& key, u32bit val) { - add(key, to_string(val)); + add(key, std::to_string(val)); } /* diff --git a/src/utils/datastor/datastor.h b/src/utils/datastor/datastor.h index 8d41b07a8..26a0d418c 100644 --- a/src/utils/datastor/datastor.h +++ b/src/utils/datastor/datastor.h @@ -9,6 +9,7 @@ #define BOTAN_DATA_STORE_H__ #include <botan/secmem.h> +#include <functional> #include <utility> #include <string> #include <vector> @@ -25,22 +26,10 @@ class BOTAN_DLL Data_Store /** * A search function */ - class BOTAN_DLL Matcher - { - public: - virtual bool operator()(const std::string&, - const std::string&) const = 0; - - virtual std::pair<std::string, std::string> - transform(const std::string&, const std::string&) const; - - virtual ~Matcher() {} - }; - bool operator==(const Data_Store&) const; - std::multimap<std::string, std::string> - search_with(const Matcher&) const; + std::multimap<std::string, std::string> search_for( + std::function<bool (std::string, std::string)> predicate) const; std::vector<std::string> get(const std::string&) const; diff --git a/src/utils/exceptn.h b/src/utils/exceptn.h index 3797a5478..02fb16a66 100644 --- a/src/utils/exceptn.h +++ b/src/utils/exceptn.h @@ -56,7 +56,7 @@ struct BOTAN_DLL Invalid_Key_Length : public Invalid_Argument { Invalid_Key_Length(const std::string& name, size_t length) : Invalid_Argument(name + " cannot accept a key of length " + - to_string(length)) + std::to_string(length)) {} }; @@ -78,7 +78,7 @@ struct BOTAN_DLL Invalid_Block_Size : public Invalid_Argument struct BOTAN_DLL Invalid_IV_Length : public Invalid_Argument { Invalid_IV_Length(const std::string& mode, size_t bad_len) : - Invalid_Argument("IV length " + to_string(bad_len) + + Invalid_Argument("IV length " + std::to_string(bad_len) + " is invalid for " + mode) {} }; diff --git a/src/utils/info.txt b/src/utils/info.txt index fcf16bd5a..e2ffd2714 100644 --- a/src/utils/info.txt +++ b/src/utils/info.txt @@ -4,12 +4,11 @@ load_on always <source> assert.cpp +calendar.cpp charset.cpp cpuid.cpp mlock.cpp parsing.cpp -time.cpp -ui.cpp version.cpp </source> @@ -25,6 +24,7 @@ xor_buf.h <header:public> bswap.h +calendar.h charset.h cpuid.h exceptn.h @@ -32,9 +32,7 @@ loadstor.h mem_ops.h parsing.h rotate.h -time.h types.h -ui.h version.h get_byte.h </header:public> diff --git a/src/utils/parsing.cpp b/src/utils/parsing.cpp index 25f021c8c..c3d7f00f7 100644 --- a/src/utils/parsing.cpp +++ b/src/utils/parsing.cpp @@ -13,53 +13,6 @@ namespace Botan { /* -* Convert a string into an integer -*/ -u32bit to_u32bit(const std::string& number) - { - u32bit n = 0; - - for(std::string::const_iterator i = number.begin(); i != number.end(); ++i) - { - const u32bit OVERFLOW_MARK = 0xFFFFFFFF / 10; - - if(*i == ' ') - continue; - - byte digit = Charset::char2digit(*i); - - if((n > OVERFLOW_MARK) || (n == OVERFLOW_MARK && digit > 5)) - throw Decoding_Error("to_u32bit: Integer overflow"); - n *= 10; - n += digit; - } - return n; - } - -/* -* Convert an integer into a string -*/ -std::string to_string(u64bit n, size_t min_len) - { - std::string lenstr; - if(n) - { - while(n > 0) - { - lenstr = Charset::digit2char(n % 10) + lenstr; - n /= 10; - } - } - else - lenstr = "0"; - - while(lenstr.size() < min_len) - lenstr = "0" + lenstr; - - return lenstr; - } - -/* * Convert a string into a time duration */ u32bit timespec_to_u32bit(const std::string& timespec) @@ -106,7 +59,7 @@ std::vector<std::string> parse_algorithm_name(const std::string& namex) elems.push_back(name.substr(0, name.find('('))); name = name.substr(name.find('(')); - for(std::string::const_iterator i = name.begin(); i != name.end(); ++i) + for(auto i = name.begin(); i != name.end(); ++i) { char c = *i; @@ -155,7 +108,7 @@ std::vector<std::string> split_on(const std::string& str, char delim) if(str == "") return elems; std::string substr; - for(std::string::const_iterator i = str.begin(); i != str.end(); ++i) + for(auto i = str.begin(); i != str.end(); ++i) { if(*i == delim) { @@ -175,6 +128,23 @@ std::vector<std::string> split_on(const std::string& str, char delim) } /* +* Join a string +*/ +std::string string_join(const std::vector<std::string>& strs, char delim) + { + std::string out = ""; + + for(size_t i = 0; i != strs.size(); ++i) + { + if(i != 0) + out += delim; + out += strs[i]; + } + + return out; + } + +/* * Parse an ASN.1 OID string */ std::vector<u32bit> parse_asn1_oid(const std::string& oid) @@ -182,7 +152,7 @@ std::vector<u32bit> parse_asn1_oid(const std::string& oid) std::string substring; std::vector<u32bit> oid_elems; - for(std::string::const_iterator i = oid.begin(); i != oid.end(); ++i) + for(auto i = oid.begin(); i != oid.end(); ++i) { char c = *i; @@ -212,8 +182,8 @@ std::vector<u32bit> parse_asn1_oid(const std::string& oid) */ bool x500_name_cmp(const std::string& name1, const std::string& name2) { - std::string::const_iterator p1 = name1.begin(); - std::string::const_iterator p2 = name2.begin(); + auto p1 = name1.begin(); + auto p2 = name2.begin(); while((p1 != name1.end()) && Charset::is_space(*p1)) ++p1; while((p2 != name2.end()) && Charset::is_space(*p2)) ++p2; @@ -258,9 +228,9 @@ u32bit string_to_ipv4(const std::string& str) u32bit ip = 0; - for(size_t i = 0; i != parts.size(); ++i) + for(auto part = parts.begin(); part != parts.end(); ++part) { - u32bit octet = to_u32bit(parts[i]); + u32bit octet = to_u32bit(*part); if(octet > 255) throw Decoding_Error("Invalid IP string " + str); @@ -282,7 +252,7 @@ std::string ipv4_to_string(u32bit ip) { if(i) str += "."; - str += to_string(get_byte(i, ip)); + str += std::to_string(get_byte(i, ip)); } return str; diff --git a/src/utils/parsing.h b/src/utils/parsing.h index 668272309..12a31a7dd 100644 --- a/src/utils/parsing.h +++ b/src/utils/parsing.h @@ -42,6 +42,15 @@ BOTAN_DLL std::string replace_char(const std::string& str, char to_char); /** +* Join a string +* @param strs strings to join +* @param delim the delimitor +* @return string joined by delim +*/ +BOTAN_DLL std::string string_join(const std::vector<std::string>& strs, + char delim); + +/** * Parse an ASN.1 OID * @param oid the OID in string form * @return OID components @@ -58,19 +67,12 @@ BOTAN_DLL bool x500_name_cmp(const std::string& name1, const std::string& name2); /** -* Convert a number to a string -* @param n the integer to convert to a string -* @param min_len the min length of the output string -* @return n convert to a string -*/ -BOTAN_DLL std::string to_string(u64bit n, size_t min_len = 0); - -/** * Convert a string to a number * @param str the string to convert * @return number value of the string */ -BOTAN_DLL u32bit to_u32bit(const std::string& str); +inline u32bit to_u32bit(const std::string& str) + { return std::stoul(str); } /** * Convert a time specification to a number diff --git a/src/utils/stl_util.h b/src/utils/stl_util.h index 9ae5c5f7a..1a62e8fe7 100644 --- a/src/utils/stl_util.h +++ b/src/utils/stl_util.h @@ -8,31 +8,12 @@ #ifndef BOTAN_STL_UTIL_H__ #define BOTAN_STL_UTIL_H__ +#include <vector> #include <map> namespace Botan { -/** -* Copy-on-Predicate Algorithm -* @param current the first iterator value -* @param end the final iterator value -* @param dest an output iterator -* @param copy_p the predicate -*/ -template<typename InputIterator, typename OutputIterator, typename Predicate> -OutputIterator copy_if(InputIterator current, InputIterator end, - OutputIterator dest, Predicate copy_p) - { - while(current != end) - { - if(copy_p(*current)) - *dest++ = *current; - ++current; - } - return dest; - } - -/** +/* * Searching through a std::map * @param mapping the map to search * @param key is what to look for @@ -44,32 +25,23 @@ inline V search_map(const std::map<K, V>& mapping, const K& key, const V& null_result = V()) { - typename std::map<K, V>::const_iterator i = mapping.find(key); + auto i = mapping.find(key); if(i == mapping.end()) return null_result; return i->second; } -/** -* Function adaptor for delete operation -*/ -template<class T> -class del_fun : public std::unary_function<T, void> +template<typename K, typename V, typename R> +inline R search_map(const std::map<K, V>& mapping, const K& key, + const R& null_result, const R& found_result) { - public: - void operator()(T* ptr) { delete ptr; } - }; - -/** -* Delete the second half of a pair of objects -*/ -template<typename Pair> -void delete2nd(Pair& pair) - { - delete pair.second; + auto i = mapping.find(key); + if(i == mapping.end()) + return null_result; + return found_result; } -/** +/* * Insert a key/value pair into a multimap */ template<typename K, typename V> diff --git a/src/utils/time.cpp b/src/utils/time.cpp deleted file mode 100644 index 65e808c04..000000000 --- a/src/utils/time.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* -* Time Functions -* (C) 1999-2010 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#include <botan/time.h> -#include <botan/exceptn.h> -#include <ctime> - -#if defined(BOTAN_TARGET_OS_HAS_WIN32_GET_SYSTEMTIME) - #include <windows.h> -#endif - -#if defined(BOTAN_TARGET_OS_HAS_GETTIMEOFDAY) - #include <sys/time.h> -#endif - -#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME) - - #ifndef _POSIX_C_SOURCE - #define _POSIX_C_SOURCE 199309 - #endif - - #include <time.h> - - #ifndef CLOCK_REALTIME - #define CLOCK_REALTIME 0 - #endif - -#endif - -namespace Botan { - -namespace { - -/* -* Combine a two time values into a single one -*/ -u64bit combine_timers(u32bit seconds, u32bit parts, u32bit parts_hz) - { - static const u64bit NANOSECONDS_UNITS = 1000000000; - - u64bit res = seconds * NANOSECONDS_UNITS; - res += parts * (NANOSECONDS_UNITS / parts_hz); - return res; - } - -std::tm do_gmtime(time_t time_val) - { - std::tm tm; - -#if defined(BOTAN_TARGET_OS_HAS_GMTIME_S) - gmtime_s(&tm, &time_val); // Windows -#elif defined(BOTAN_TARGET_OS_HAS_GMTIME_R) - gmtime_r(&time_val, &tm); // Unix/SUSv2 -#else - std::tm* tm_p = std::gmtime(&time_val); - if (tm_p == 0) - throw Encoding_Error("time_t_to_tm could not convert"); - tm = *tm_p; -#endif - - return tm; - } - -} - -/* -* Get the system clock -*/ -u64bit system_time() - { - return static_cast<u64bit>(std::time(0)); - } - -/* -* Convert a time_point to a calendar_point -*/ -calendar_point calendar_value(u64bit a_time_t) - { - std::tm tm = do_gmtime(static_cast<std::time_t>(a_time_t)); - - return calendar_point(tm.tm_year + 1900, - tm.tm_mon + 1, - tm.tm_mday, - tm.tm_hour, - tm.tm_min, - tm.tm_sec); - } - -u64bit get_nanoseconds_clock() - { -#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME) - - struct ::timespec tv; - ::clock_gettime(CLOCK_REALTIME, &tv); - return combine_timers(tv.tv_sec, tv.tv_nsec, 1000000000); - -#elif defined(BOTAN_TARGET_OS_HAS_GETTIMEOFDAY) - - struct ::timeval tv; - ::gettimeofday(&tv, 0); - return combine_timers(tv.tv_sec, tv.tv_usec, 1000000); - -#elif defined(BOTAN_TARGET_OS_HAS_WIN32_GET_SYSTEMTIME) - - // Returns time since January 1, 1601 in 100-ns increments - ::FILETIME tv; - ::GetSystemTimeAsFileTime(&tv); - u64bit tstamp = (static_cast<u64bit>(tv.dwHighDateTime) << 32) | - tv.dwLowDateTime; - - return (tstamp * 100); // Scale to 1 nanosecond units - -#else - - return combine_timers(static_cast<u32bit>(std::time(0)), - std::clock(), CLOCKS_PER_SEC); - -#endif - } - -} diff --git a/src/utils/types.h b/src/utils/types.h index 61a55368c..255311580 100644 --- a/src/utils/types.h +++ b/src/utils/types.h @@ -39,15 +39,7 @@ typedef signed int s32bit; /** * Typedef representing an unsigned 64-bit quantity */ -#if defined(_MSC_VER) || defined(__BORLANDC__) - typedef unsigned __int64 u64bit; -#elif defined(__KCC) - typedef unsigned __long_long u64bit; -#elif defined(__GNUG__) - __extension__ typedef unsigned long long u64bit; -#else - typedef unsigned long long u64bit; -#endif +typedef unsigned long long u64bit; /** * A default buffer size; typically a memory page diff --git a/src/utils/ui.cpp b/src/utils/ui.cpp deleted file mode 100644 index e6c3430ff..000000000 --- a/src/utils/ui.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* -* User Interface -* (C) 1999-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#include <botan/ui.h> - -namespace Botan { - -/* -* Get a passphrase from the user -*/ -std::string User_Interface::get_passphrase(const std::string&, - const std::string&, - UI_Result& action) const - { - action = OK; - - if(!first_try) - action = CANCEL_ACTION; - - return preset_passphrase; - } - -/* -* User_Interface Constructor -*/ -User_Interface::User_Interface(const std::string& preset) : - preset_passphrase(preset) - { - first_try = true; - } - -} diff --git a/src/utils/ui.h b/src/utils/ui.h deleted file mode 100644 index f69bb2c6d..000000000 --- a/src/utils/ui.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -* User Interface -* (C) 1999-2007 Jack Lloyd -* -* Distributed under the terms of the Botan license -*/ - -#ifndef BOTAN_UI_H__ -#define BOTAN_UI_H__ - -#include <botan/build.h> -#include <string> - -namespace Botan { - -/** -* User Interface -* Only really used for callbacks for PKCS #8 decryption -*/ -class BOTAN_DLL User_Interface - { - public: - enum UI_Result { OK, CANCEL_ACTION }; - - virtual std::string get_passphrase(const std::string&, - const std::string&, - UI_Result&) const; - User_Interface(const std::string& = ""); - virtual ~User_Interface() {} - protected: - std::string preset_passphrase; - mutable bool first_try; - }; - -} - -#endif diff --git a/src/wrap/python/core.cpp b/src/wrap/python/core.cpp index 7dac7be7f..6dcceee74 100644 --- a/src/wrap/python/core.cpp +++ b/src/wrap/python/core.cpp @@ -178,7 +178,7 @@ std::string python_kdf2(const std::string& param, const std::string& masterkey, u32bit outputlength) { - std::auto_ptr<KDF> kdf(get_kdf("KDF2(SHA-1)")); + std::unique_ptr<KDF> kdf(get_kdf("KDF2(SHA-1)")); return make_string( kdf->derive_key(outputlength, diff --git a/src/wrap/python/filter.cpp b/src/wrap/python/filter.cpp index 437c5239f..eef8b202c 100644 --- a/src/wrap/python/filter.cpp +++ b/src/wrap/python/filter.cpp @@ -26,7 +26,6 @@ class Py_Filter : public Filter void send_str(const std::string& str) { - printf("Py_Filter::send_str\n"); send((const byte*)str.data(), str.length()); } }; @@ -36,14 +35,12 @@ class FilterWrapper : public Py_Filter, public wrapper<Py_Filter> public: void start_msg() { - printf("wrapper start_msg\n"); if(override start_msg = this->get_override("start_msg")) start_msg(); } void end_msg() { - printf("wrapper end_msg\n"); if(override end_msg = this->get_override("end_msg")) end_msg(); } @@ -53,7 +50,6 @@ class FilterWrapper : public Py_Filter, public wrapper<Py_Filter> virtual void write_str(const std::string& str) { - printf("wrapper write\n"); this->get_override("write")(str); } }; @@ -111,21 +107,20 @@ Filter* make_filter4(const std::string& name, name); } -void append_filter(Pipe& pipe, std::auto_ptr<Filter> filter) +void append_filter(Pipe& pipe, std::unique_ptr<Filter> filter) { pipe.append(filter.get()); filter.release(); } -void prepend_filter(Pipe& pipe, std::auto_ptr<Filter> filter) +void prepend_filter(Pipe& pipe, std::unique_ptr<Filter> filter) { pipe.prepend(filter.get()); filter.release(); } -void do_send(std::auto_ptr<FilterWrapper> filter, const std::string& data) +void do_send(std::unique_ptr<FilterWrapper> filter, const std::string& data) { - printf("Sending %s to %p\n", data.c_str(), filter.get()); filter->send_str(data); } @@ -133,7 +128,7 @@ BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(rallas_ovls, read_all_as_string, 0, 1) void export_filters() { - class_<Filter, std::auto_ptr<Filter>, boost::noncopyable> + class_<Filter, std::unique_ptr<Filter>, boost::noncopyable> ("__Internal_FilterObj", no_init); def("make_filter", make_filter1, @@ -147,7 +142,7 @@ void export_filters() // This might not work - Pipe will delete the filter, but Python // might have allocated the space with malloc() or who-knows-what -> bad - class_<FilterWrapper, std::auto_ptr<FilterWrapper>, + class_<FilterWrapper, std::unique_ptr<FilterWrapper>, bases<Filter>, boost::noncopyable> ("FilterObj") .def("write", pure_virtual(&Py_Filter::write_str)) @@ -155,8 +150,8 @@ void export_filters() .def("start_msg", &Filter::start_msg, &FilterWrapper::default_start_msg) .def("end_msg", &Filter::end_msg, &FilterWrapper::default_end_msg); - implicitly_convertible<std::auto_ptr<FilterWrapper>, - std::auto_ptr<Filter> >(); + implicitly_convertible<std::unique_ptr<FilterWrapper>, + std::unique_ptr<Filter> >(); void (Pipe::*pipe_write_str)(const std::string&) = &Pipe::write; void (Pipe::*pipe_process_str)(const std::string&) = &Pipe::process_msg; diff --git a/src/wrap/python/python_botan.h b/src/wrap/python/python_botan.h index a7a2e505e..ac0a17d7f 100644 --- a/src/wrap/python/python_botan.h +++ b/src/wrap/python/python_botan.h @@ -24,7 +24,8 @@ class Bad_Size : public Exception public: Bad_Size(u32bit got, u32bit expected) : Exception("Bad size detected in Python/C++ conversion layer: got " + - to_string(got) + " bytes, expected " + to_string(expected)) + std::to_string(got) + " bytes, expected " + + std::to_string(expected)) {} }; |