CRYPTOPP 5.6.3 RC6 checkin

pull/63/head
Jeffrey Walton 2015-11-05 01:59:46 -05:00
parent 025337a94a
commit 48809d4e85
295 changed files with 83356 additions and 76410 deletions

View File

@ -15,7 +15,9 @@ void ThreeWay_TestInstantiations()
static const word32 START_E = 0x0b0b; // round constant of first encryption round
static const word32 START_D = 0xb1b1; // round constant of first decryption round
// static const word32 RC_MODULUS = 0x11011;
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
static const word32 RC_MODULUS = 0x11011;
#endif
static inline word32 reverseBits(word32 a)
{

26
3way.h
View File

@ -1,23 +1,33 @@
// 3way.h - written and placed in the public domain by Wei Dai
//! \file
//! \headerfile 3way.h
//! \brief Class files for the 3way cipher
#ifndef CRYPTOPP_THREEWAY_H
#define CRYPTOPP_THREEWAY_H
/** \file
*/
#include "seckey.h"
#include "secblock.h"
NAMESPACE_BEGIN(CryptoPP)
//! _
//! \class ThreeWay_Info
//! \brief The cipher's key, iv, block size and name information.
struct ThreeWay_Info : public FixedBlockSize<12>, public FixedKeyLength<12>, public VariableRounds<11>
{
static const char *StaticAlgorithmName() {return "3-Way";}
};
/// <a href="http://www.weidai.com/scan-mirror/cs.html#3-Way">3-Way</a>
// <a href="http://www.weidai.com/scan-mirror/cs.html#3-Way">3-Way</a>
//! \class ThreeWay
//! \brief Provides 3-Way encryption and decryption
class ThreeWay : public ThreeWay_Info, public BlockCipherDocumentation
{
//! \class Base
//! \brief Class specific implementation and overrides used to operate the cipher.
//! \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<ThreeWay_Info>
{
public:
@ -28,12 +38,18 @@ class ThreeWay : public ThreeWay_Info, public BlockCipherDocumentation
FixedSizeSecBlock<word32, 3> m_k;
};
//! \class Enc
//! \brief Class specific methods used to operate the cipher in the forward direction.
//! \details Implementations and overrides in \p Enc apply to \p ENCRYPTION.
class CRYPTOPP_NO_VTABLE Enc : public Base
{
public:
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
};
//! \class Dec
//! \brief Class specific methods used to operate the cipher in the reverse direction.
//! \details Implementations and overrides in \p Dec apply to \p DECRYPTION.
class CRYPTOPP_NO_VTABLE Dec : public Base
{
public:

2433
Doxyfile

File diff suppressed because it is too large Load Diff

View File

@ -1,256 +1,109 @@
#################################################################
# Tool and flag setup
# Base CXXFLAGS used if the user did not specify them
CXXFLAGS ?= -DNDEBUG -g2 -O2
# -fPIC is supported, please report failures with steps to reproduce
# If PIC is required but results in a crash, then use -DCRYPTOPP_DISABLE_ASM
# CXXFLAGS += -fPIC
# Add the following options reduce code size, but breaks link
# or makes link very slow on some systems
# CXXFLAGS += -ffunction-sections -fdata-sections
# On OS X, you need to use "LDFLAGS += -Wl,-dead_strip"
# LDFLAGS += -Wl,--gc-sections
AS ?= as
AR ?= ar
ARFLAGS ?= -cr # ar needs the dash on OpenBSD
RANLIB ?= ranlib
STRIP ?= strip -s
CP ?= cp
CHMOD ?= chmod
MKDIR ?= mkdir
EGREP ?= egrep
UNAME ?= uname
# Default setting from environment. Disable verbose flag, add create flag
ifeq ($(findstring rv,$(ARFLAGS)),rv)
ARFLAGS = cr
endif
UNAME := $(shell uname)
IS_X86 := $(shell uname -m | $(EGREP) -i -c "i.86|x86|i86|amd64")
IS_X86_64 := $(shell uname -m | $(EGREP) -i -c "(_64|d64)")
#########################
# CXXFLAGS
# -fPIC is supported, and enabled by default for x86_64.
IS_SUN := $(shell uname | $(EGREP) -i -c "SunOS")
IS_LINUX := $(shell $(CXX) -dumpmachine 2>&1 | $(EGREP) -i -c "Linux")
IS_MINGW := $(shell $(CXX) -dumpmachine 2>&1 | $(EGREP) -i -c "MinGW")
IS_CYGWIN := $(shell $(CXX) -dumpmachine 2>&1 | $(EGREP) -i -c "Cygwin")
IS_DARWIN := $(shell $(CXX) -dumpmachine 2>&1 | $(EGREP) -i -c "Darwin")
# We can augment CXXFLAGS if the user exports them in the shell, or if the user
# omits them. However, if the user `make CXXFLAGS="-g1"`, then that's what
# the user gets. Make does not override them, and does not honor our '+='.
CXXFLAGS ?= -DNDEBUG -g2 -O3
# Add -DNDEBUG if nothing specified
ifeq ($(filter -DDEBUG -DNDEBUG,$(CXXFLAGS)),)
CXXFLAGS += -DNDEBUG
endif
# Add a symolize if nothing specified
ifeq ($(filter -g -g1 -g2 -g3,$(CXXFLAGS)),)
CXXFLAGS += -g2
endif
# Add an optimize if nothing specified
ifeq ($(filter -O -O0 -O1 -O2 -O3 -Og -Os -Oz -Ofast,$(CXXFLAGS)),)
CXXFLAGS += -O3
endif
# the following options reduce code size, but breaks link or makes link very slow on some systems
# CXXFLAGS += -ffunction-sections -fdata-sections
# LDFLAGS += -Wl,--gc-sections
#########################
# Compilers
# Cygwin change the version string to "g++ (GCC) 4.9.3"
GCC_COMPILER = $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "^(gcc|g\+\+) version")
CLANG_COMPILER = $(shell $(CXX) --version 2>&1 | $(EGREP) -i -c "clang")
INTEL_COMPILER = $(shell $(CXX) --version 2>&1 | $(EGREP) -i -c "\(ICC\)")
SUN_COMPILER = $(shell $(CXX) -V 2>&1 | $(EGREP) -i -c "CC: Sun")
ifneq ($(GCC_COMPILER),0)
IS_GCC_41 = $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "^gcc version 4\.1\.")
IS_GCC_42 = $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "^gcc version 4\.2\.")
IS_GCC_45 = $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "^gcc version 4\.5\.")
IS_GCC_49 = $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "^gcc version 4\.9\.")
endif
# Also see LLVM Bug 24200 (https://llvm.org/bugs/show_bug.cgi?id=24200)
# CLANG_ASSEMBLER ?= $(shell $(CXX) -xc -c /dev/null -Wa,-v -o/dev/null 2>&1 | $(EGREP) -i -c "^clang")
# TODO: Uncomment the line above when Clang's integrated assembler can parse and generate code that passes the self tests.
#################################################################
# Platform and architecture detection
MACHINE ?= $(shell $(UNAME) -m)
SYSTEM ?= $(shell $(UNAME) -s)
RELEASE ?= $(shell $(UNAME) -r)
IS_X86 = $(shell echo $(MACHINE)| $(EGREP) -c "i.86|x86|i86|i686|amd64")
IS_X86_64 = $(shell echo $(MACHINE) | $(EGREP) -c "_64|d64")
IS_DARWIN = $(shell echo $(SYSTEM) | $(EGREP) -i -c "darwin")
IS_LINUX = $(shell $(CXX) -dumpmachine 2>&1 | $(EGREP) -i -c "linux")
IS_MINGW = $(shell $(CXX) -dumpmachine 2>&1 | $(EGREP) -i -c "mingw")
IS_CYGWIN = $(shell $(CXX) -dumpmachine 2>&1 | $(EGREP) -i -c "cygwin")
IS_OPENBSD = $(shell $(CXX) -dumpmachine 2>&1 | $(EGREP) -i -c "openbsd")
IS_SUN = $(shell echo $SYSTEM | $(EGREP) -i -c "SunOS")
IS_FEDORA22_i686 = $(shell echo $RELEASE | $(EGREP) -i -c "fc22.i686")
#########################
# May (or may not) be used below
ifeq ($(findstring -m32 -m64,$(CXXFLAGS)),)
ifneq ($(IS_X86_64),0)
M32OR64 = -m64
endif
endif # -m32 or -m64
#################################################################
# User install preferences
# Pick up the user's choice (lower prefix is the standard name)
ifneq ($(prefix),)
PREFIX = $(prefix)
else
SUN_COMPILER := $(shell $(CXX) -V 2>&1 | $(EGREP) -i -c "CC: Sun")
GCC_COMPILER := $(shell $(CXX) --version 2>&1 | $(EGREP) -i -c "(gcc|g\+\+)")
CLANG_COMPILER := $(shell $(CXX) --version 2>&1 | $(EGREP) -i -c "clang")
INTEL_COMPILER := $(shell $(CXX) --version 2>&1 | $(EGREP) -c "\(ICC\)")
MACPORTS_COMPILER := $(shell $(CXX) --version 2>&1 | $(EGREP) -i -c "macports")
# Default prefix for make install
ifeq ($(PREFIX),)
PREFIX = /usr
endif
# Can't put C++ headers in system include
ifneq ($(IS_OPENBSD),0)
PREFIX = /usr/local
ifeq ($(CXX),gcc) # for some reason CXX is gcc on cygwin 1.1.4
CXX := g++
endif
endif # prefix
#################################################################
# Undefined behavior and Address sanitizer
# Clang 3.2 and GCC 4.8 and above, i386/i686/x86_64
ifneq ($(IS_X86),0)
# Undefined Behavior Sanitizer (UBsan)
ifeq ($(findstring ubsan,$(MAKECMDGOALS)),ubsan)
CXXFLAGS += -fsanitize=undefined
# CXXFLAGS += -fsanitize-undefined-trap-on-error
endif # UBsan
# Address Sanitizer (Asan)
ifeq ($(findstring asan,$(MAKECMDGOALS)),asan)
CXXFLAGS += -fsanitize=address
endif # Asan
# Test CXXFLAGS in case the user passed the flags directly through it
ifeq ($(findstring -fsanitize=address,$(CXXFLAGS)),-fsanitize=address)
ASAN = 1
endif
ifeq ($(findstring -fsanitize=undefined,$(CXXFLAGS)),-fsanitize=undefined)
UBSAN = 1
# We honor ARFLAGS, but the "v" often option used by default causes a noisy make
ifeq ($(ARFLAGS),rv)
ARFLAGS = r
endif
# Enforce Sanitizer business logic...
ifeq ($(ASAN)$(UBSAN),11)
$(error Asan and UBsan are mutually exclusive)
endif
ifeq ($(IS_X86),1)
endif # IS_X86
IS_GCC_29 := $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c gcc-9[0-9][0-9])
IS_GCC_41 := $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "gcc version 4\.1\.")
GCC42_OR_LATER := $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "gcc version (4\.[2-9]|[5-9])")
GCC46_OR_LATER := $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "gcc version (4\.[6-9]|[5-9])")
GCC48_OR_LATER := $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "gcc version (4\.[8-9]|[5-9])")
GCC49_OR_LATER := $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "gcc version (4\.9|[5-9])")
#################################################################
# Darwin tweaks
ICC111_OR_LATER := $(shell $(CXX) --version 2>&1 | $(EGREP) -c "\(ICC\) ([2-9][0-9]|1[2-9]|11\.[1-9])")
GAS210_OR_LATER := $(shell $(CXX) -xc -c /dev/null -Wa,-v -o/dev/null 2>&1 | $(EGREP) -c "GNU assembler version (2\.[1-9][0-9]|[3-9])")
GAS217_OR_LATER := $(shell $(CXX) -xc -c /dev/null -Wa,-v -o/dev/null 2>&1 | $(EGREP) -c "GNU assembler version (2\.1[7-9]|2\.[2-9]|[3-9])")
GAS219_OR_LATER := $(shell $(CXX) -xc -c /dev/null -Wa,-v -o/dev/null 2>&1 | $(EGREP) -c "GNU assembler version (2\.19|2\.[2-9]|[3-9])")
ifneq ($(IS_DARWIN),0)
CXX ?= c++
ifeq ($(AR),ar)
AR = libtool
ARFLAGS = -static -o
endif
#########################
# Build a boolean circuit that says "Darwin && (GCC 4.2 || Clang)"
# MULTIARCH ?= $(shell echo $$(($(IS_DARWIN) * ($(GCC42_OR_LATER) + $(CLANG_COMPILER)))))
MULTIARCH ?= 0
ifneq ($(MULTIARCH),0)
CXXFLAGS += -arch i386 -arch x86_64
endif # MULTIARCH
endif # IS_DARWIN
#################################################################
# i386, i686, x86_64 and friends
ifneq ($(IS_X86),0)
GCC42_OR_LATER = $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "^gcc version (4.[2-9]|[5-9])")
ICC111_OR_LATER = $(shell $(CXX) --version 2>&1 | $(EGREP) -c "\(ICC\) ([2-9][0-9]|1[2-9]|11\.[1-9])")
# Using system provided assembler. It may be GNU AS (GAS).
GAS210_OR_LATER ?= $(shell $(CXX) -xc -c /dev/null -Wa,-v -o/dev/null 2>&1 | $(EGREP) -c "GNU assembler version (2\.[1-9][0-9]|[3-9])")
GAS217_OR_LATER ?= $(shell $(CXX) -xc -c /dev/null -Wa,-v -o/dev/null 2>&1 | $(EGREP) -c "GNU assembler version (2\.1[7-9]|2\.[2-9]|[3-9])")
GAS219_OR_LATER ?= $(shell $(CXX) -xc -c /dev/null -Wa,-v -o/dev/null 2>&1 | $(EGREP) -c "GNU assembler version (2\.19|2\.[2-9]|[3-9])")
# For testing and development. If CXX=clang++, then it effectively
# enables ASM code paths and engages the integrated assembler.
FORCE_ASM ?= 0
ifneq ($(FORCE_ASM),0)
GAS210_OR_LATER = 1
GAS217_OR_LATER = 1
GAS219_OR_LATER = 1
endif
# Enable PIC for x86_64 targets
# Add -fPIC for x86_64, but not X32 or Cygwin
ifneq ($(IS_X86_64),0)
CXXFLAGS += -fPIC
endif # PIC for x86_64 targets
#########################
# Cygwin work arounds
ifneq ($(IS_CYGWIN),0)
# CXX is gcc on Cygwin 1.1.4
ifeq ($(CXX),gcc)
CXX = g++
endif # CXX
# -fPIC causes spurious output during compile. Remove it even if the user passed it in.
ifeq ($(findstring -fPIC,$(CXXFLAGS)),-fPIC)
CXXFLAGS := $(subst -fPIC,,$(CXXFLAGS))
endif # -fPIC
# -O3 fails to link with GCC 4.5.3
ifneq ($(IS_GCC_45),0)
ifeq ($(findstring -O3,$(CXXFLAGS)),-O3)
CXXFLAGS := $(subst -O3,-O2,$(CXXFLAGS))
endif # -O3
endif # GCC 4.5
# -O3 crash in MQV validation with GCC 4.9.3
ifneq ($(IS_GCC_49),0)
ifeq ($(findstring -O3,$(CXXFLAGS)),-O3)
CXXFLAGS := $(subst -O3,-O2,$(CXXFLAGS))
endif # -O3
endif # GCC 4.9
endif # Cygwin work arounds
#########################
# F22/i386 crash
ifneq ($(IS_FEDORA22_i686),0)
ifeq ($(findstring -O3,$(CXXFLAGS)),-O3)
CXXFLAGS := $(subst -O3,-O2,$(CXXFLAGS))
endif # -O2
endif # Fedora 22/i686
#########################
# Way back when, '-march=native' caused a compiler crash with GCC on Ubuntu 9 or 10
# Add -march=native if the user did not specify an architecture.
ifeq ($(findstring -m32 -m64,$(CXXFLAGS)),)
CXXFLAGS += -march=native
IS_X32 := $(shell $(CXX) -dM -E - < /dev/null 2>&1 | $(EGREP) -c "ILP32")
ifeq ($(IS_X32),0)
ifeq ($(IS_CYGWIN),0)
ifeq ($(findstring -fPIC,$(CXXFLAGS)),)
CXXFLAGS += -fPIC
endif
endif
endif
endif
#########################
# GCC 4.1 and "error: bad value (native) for -march= switch"
# Work around GCC 4.1 bug.
ifneq ($(IS_GCC_41),0)
ifneq ($(findstring -march=native,$(CXXFLAGS)),)
ifneq ($(IS_X86_64),0)
CXXFLAGS := $(subst -march=native,-m64,$(CXXFLAGS))
# GCC 4.1 compiler crash with -march=native.
# Experienced on CentOS 5, which is still active.
ifneq ($(IS_X86_64),0)
CXXFLAGS += -m64
else
CXXFLAGS += -m32
endif # X86/X32/X64
# Not GCC 4.1, use default
else
CXXFLAGS := $(subst -march=native,-m32,$(CXXFLAGS))
endif
endif
CXXFLAGS += -march=native
endif
#########################
# Intel work arounds.
# Should this be moved to outside of i386/i686/x86_64 block?
# Aligned access required at -O3 for GCC due to vectorization (circa 08/2008). Expect other compilers to do the same.
GCC46_OR_LATER ?= 0
UNALIGNED_ACCESS := $(shell $(EGREP) -c "^[[:space:]]*//[[:space:]]*\#[[:space:]]*define[[:space:]]*CRYPTOPP_NO_UNALIGNED_DATA_ACCESS" config.h)
ifeq ($(findstring -O3,$(CXXFLAGS)),-O3)
ifneq ($(UNALIGNED_ACCESS),0)
ifeq ($(GCC46_OR_LATER),1)
ifeq ($(findstring -DCRYPTOPP_NO_UNALIGNED_DATA_ACCESS,$(CXXFLAGS)),)
CXXFLAGS += -DCRYPTOPP_NO_UNALIGNED_DATA_ACCESS
endif # CRYPTOPP_NO_UNALIGNED_DATA_ACCESS
endif # GCC 4.6
endif # UNALIGNED_ACCESS
endif # Vectorization
ifneq ($(INTEL_COMPILER),0)
CXXFLAGS += -wd68 -wd186 -wd279 -wd327
CXXFLAGS += -wd68 -wd186 -wd279 -wd327 -wd161 -wd3180
ifeq ($(ICC111_OR_LATER),0)
# "internal error: backend signals" occurs on some x86 inline assembly with ICC 9 and some x64 inline assembly with ICC 11.0
# if you want to use Crypto++'s assembly code with ICC, try enabling it on individual files
@ -258,10 +111,7 @@ CXXFLAGS += -DCRYPTOPP_DISABLE_ASM
endif
endif
#########################
# GAS work arounds.
# Should this be moved to outside of i386/i686/x86_64 block?
ifeq ($(GAS210_OR_LATER),0)
ifeq ($(GAS210_OR_LATER),0) # .intel_syntax wasn't supported until GNU assembler 2.10
CXXFLAGS += -DCRYPTOPP_DISABLE_ASM
else
ifeq ($(GAS217_OR_LATER),0)
@ -269,203 +119,247 @@ CXXFLAGS += -DCRYPTOPP_DISABLE_SSSE3
else
ifeq ($(GAS219_OR_LATER),0)
CXXFLAGS += -DCRYPTOPP_DISABLE_AESNI
endif # GAS219_OR_LATER
endif # GAS217_OR_LATER
endif
endif
ifneq ($(IS_SUN),0)
CXXFLAGS += -Wa,--divide # allow use of "/" operator
endif # IS_SUN
endif # GAS210_OR_LATER
ifneq ($(IS_MINGW),0)
LDLIBS += -lws2_32
endif # IS_MINGW
endif
endif
endif # IS_X86
# Should most of this be moved to outside of i386/i686/x86_64 block?
ifeq ($(UNAME),) # for DJGPP, where uname doesn't exist
CXXFLAGS += -mbnu210
else ifneq ($(findstring -save-temps,$(CXXFLAGS)),-save-temps)
CXXFLAGS += -pipe
endif
ifneq ($(IS_MINGW),0)
LDLIBS += -lws2_32
endif
ifeq ($(IS_LINUX),1)
LDFLAGS += -pthread
ifeq ($(findstring -fopenmp,$(MAKECMDGOALS)),-fopenmp)
ifeq ($(findstring -fopenmp,$(CXXFLAGS)),-fopenmp)
ifeq ($(findstring -lgomp,$(LDLIBS)),)
LDLIBS += -lgomp
endif # -fopenmp
endif # LDLIBS
endif # OpenMP
ifneq ($(IS_X86_64),0)
M32OR64 = -m64
endif
endif # IS_LINUX
ifneq ($(IS_DARWIN),0)
AR = libtool
ARFLAGS = -static -o
CXX ?= c++
ifeq ($(IS_GCC_29),1)
CXXFLAGS += -fno-coalesce-templates -fno-coalesce-static-vtables
LDLIBS += -lstdc++
LDFLAGS += -flat_namespace -undefined suppress -m
endif
endif
ifneq ($(IS_SUN),0)
LDLIBS += -lnsl -lsocket
M32OR64 = -m$(shell isainfo -b)
endif
ifneq ($(SUN_COMPILER),0) # override flags for CC Sun C++ compiler
CXXFLAGS = -DNDEBUG -O -g0 -native -template=no%extdef $(M32OR64)
CXXFLAGS ?= -DNDEBUG -O -g0 -native -template=no%extdef $(M32OR64)
LDFLAGS =
AR = $(CXX)
ARFLAGS = -xar -o
RANLIB = true
LDFLAGS =
SUN_CC10_BUGGY = $(shell $(CXX) -V 2>&1 | $(EGREP) -c "CC: Sun .* 5\.10 .* (2009|2010/0[1-4])")
SUN_CC10_BUGGY := $(shell $(CXX) -V 2>&1 | $(EGREP) -c "CC: Sun .* 5\.10 .* (2009|2010/0[1-4])")
ifneq ($(SUN_CC10_BUGGY),0)
# -DCRYPTOPP_INCLUDE_VECTOR_CC is needed for Sun Studio 12u1 Sun C++ 5.10 SunOS_i386 128229-02 2009/09/21 and was fixed in May 2010
# remove it if you get "already had a body defined" errors in vector.cc
CXXFLAGS += -DCRYPTOPP_INCLUDE_VECTOR_CC
endif # SUN_CC10_BUGGY
endif # SUN_COMPILER
#################################################################
# Public service announcement
# Do not warn for some targets
NO_WARN = GNUmakefile.deps deps system dist zip install install-strip uninstall remove clean distclean
ifeq ($(findstring $(MAKECMDGOALS),$(NO_WARN)),)
UNALIGNED_ACCESS = $(shell $(EGREP) -c "^// \#define CRYPTOPP_NO_UNALIGNED_DATA_ACCESS" config.h)
ifneq ($(UNALIGNED_ACCESS),0)
$(info WARNING: CRYPTOPP_NO_UNALIGNED_DATA_ACCESS is not defined in config.h)
endif
endif
endif # NO_WARN
# Undefined Behavior Sanitizer (UBsan) testing. There's no sense in
# allowing unaligned data access. There will too many findings.
ifeq ($(findstring ubsan,$(MAKECMDGOALS)),ubsan)
ifeq ($(findstring -fsanitize=undefined,$(CXXFLAGS)),)
CXXFLAGS += -fsanitize=undefined
endif # CXXFLAGS
ifeq ($(findstring -DCRYPTOPP_NO_UNALIGNED_DATA_ACCESS,$(CXXFLAGS)),)
CXXFLAGS += -DCRYPTOPP_NO_UNALIGNED_DATA_ACCESS
endif # CXXFLAGS
endif # UBsan
#################################################################
# Compiler diagnostics and warnings
# Address Sanitizer (Asan) testing
ifeq ($(findstring asan,$(MAKECMDGOALS)),asan)
ifeq ($(findstring -fsanitize=address,$(CXXFLAGS)),)
CXXFLAGS += -fsanitize=address
endif # CXXFLAGS
endif # Asan
# -Wall, -Wextra and -Wno-type-limits for GCC 4.3 and above. It needs -Wno-unknown-pragmas due
# to bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431. We can't use -Wall
# unguarded because it lights up CentOS 5 (GCC 4.1) and OpenBSD (4.2.1)
GCC43_OR_LATER = $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "^gcc version (4\.[3-9]|[5-9])")
ifneq ($(GCC43_OR_LATER),0)
CXXFLAGS += -Wall -Wextra -Wno-type-limits -Wno-unknown-pragmas
# LD gold linker testing
ifeq ($(findstring ld.gold,$(LD)),ld.gold)
ifeq ($(findstring -Wl,-fuse-ld=gold,$(CXXFLAGS)),)
ELF_FORMAT := $(shell file `which ld.gold` 2>&1 | cut -d":" -f 2 | $(EGREP) -i -c "elf")
ifneq ($(ELF_FORMAT),0)
GOLD_OPTION = -Wl,-fuse-ld=gold
endif # ELF/ELF64
endif # CXXFLAGS
endif # Gold
# Aligned access testing
ifneq ($(filter align aligned,$(MAKECMDGOALS)),)
ifeq ($(findstring -DCRYPTOPP_NO_UNALIGNED_DATA_ACCESS,$(CXXFLAGS)),)
CXXFLAGS += -DCRYPTOPP_NO_UNALIGNED_DATA_ACCESS
endif # # CXXFLAGS
endif # Aligned access
# Debug testing on GNU systems
ifneq ($(filter -DDEBUG -DDEBUG=1,$(CXXFLAGS)),)
USING_GLIBCXX := $(shell $(CXX) -x c++ $(CXXFLAGS) -E adhoc.cpp.proto 2>&1 | $(EGREP) -i -c "__GLIBCXX__")
ifneq ($(USING_GLIBCXX),0)
ifeq ($(findstring -D_GLIBCXX_DEBUG,$(CXXFLAGS)),)
CXXFLAGS += -D_GLIBCXX_DEBUG
endif # CXXFLAGS
ifeq ($(findstring -D_GLIBCXX_CONCEPT_CHECKS,$(CXXFLAGS)),)
CXXFLAGS += -D_GLIBCXX_CONCEPT_CHECKS
endif # CXXFLAGS
endif # USING_GLIBCXX
endif # GNU Debug build
# List cryptlib.cpp first and cpu.o second in an attempt to tame C++ static initialization problems. The issue
# spills into POD data types, so cpu.cpp is the second candidate for explicit initialization order.
SRCS := cryptlib.cpp cpu.cpp $(filter-out cryptlib.cpp cpu.cpp pch.cpp simple.cpp winpipes.cpp cryptlib_bds.cpp,$(wildcard *.cpp))
ifneq ($(IS_MINGW),0)
SRCS += winpipes.cpp
endif
# -Wall, -Wextra and -Wno-tautological-compare for Clang
ifneq ($(CLANG_COMPILER),0)
CXXFLAGS += -Wall -Wextra -Wno-tautological-compare
endif
# -Wcast-align if not UNALIGNED_ACCESS
ifeq ($(UNALIGNED_ACCESS),0)
# CXXFLAGS += -Wcast-align
endif
ifeq ($(findstring -pipe,$(CXXFLAGS)),)
CXXFLAGS += -pipe
endif
#################################################################
# Sources, objects and temporaries
WIN_SRCS = pch.cpp fipsalgt.cpp cryptlib_bds.cpp
ifeq ($(IS_MINGW),0)
WIN_SRCS += winpipes.cpp
endif
# List of sources to compile and objects to link
SRCS = $(filter-out $(WIN_SRCS), $(wildcard *.cpp))
OBJS = $(SRCS:.cpp=.o)
# Compiling with --save-temps creates these
TEMPS = $(SRCS:.cpp=.s) $(SRCS:.cpp=.ii)
# List of objects with crytlib.o and cpu.o at the first and second index position
OBJS := $(SRCS:.cpp=.o)
# test.o needs to be after bench.o for cygwin 1.1.4 (possible ld bug?)
TESTOBJS = bench.o bench2.o test.o validat0.o validat1.o validat2.o validat3.o adhoc.o datatest.o regtest.o fipsalgt.o dlltest.o
LIBOBJS = $(filter-out $(TESTOBJS),$(OBJS))
TESTOBJS := bench.o bench2.o test.o validat1.o validat2.o validat3.o adhoc.o datatest.o regtest.o fipsalgt.o dlltest.o
LIBOBJS := $(filter-out $(TESTOBJS),$(OBJS))
DLLSRCS = algebra.cpp algparam.cpp asn.cpp basecode.cpp cbcmac.cpp channels.cpp cryptlib.cpp des.cpp dessp.cpp dh.cpp \
dll.cpp dsa.cpp ec2n.cpp eccrypto.cpp ecp.cpp eprecomp.cpp files.cpp filters.cpp fips140.cpp fipstest.cpp \
gf2n.cpp gfpcrypt.cpp hex.cpp hmac.cpp integer.cpp iterhash.cpp misc.cpp modes.cpp modexppc.cpp mqueue.cpp \
nbtheory.cpp oaep.cpp osrng.cpp pch.cpp pkcspad.cpp pubkey.cpp queue.cpp randpool.cpp rdtables.cpp \
rijndael.cpp rng.cpp rsa.cpp sha.cpp simple.cpp skipjack.cpp strciphr.cpp trdlocal.cpp
DLLOBJS = $(DLLSRCS:.cpp=.export.o)
LIBIMPORTOBJS = $(LIBOBJS:.o=.import.o)
TESTIMPORTOBJS = $(TESTOBJS:.o=.import.o)
DLLTESTOBJS = dlltest.dllonly.o
# List cryptlib.cpp first in an attempt to tame C++ static initialization problems
DLLSRCS := cryptlib.cpp algebra.cpp algparam.cpp asn.cpp basecode.cpp cbcmac.cpp channels.cpp des.cpp dessp.cpp dh.cpp dll.cpp dsa.cpp ec2n.cpp eccrypto.cpp ecp.cpp eprecomp.cpp files.cpp filters.cpp fips140.cpp fipstest.cpp gf2n.cpp gfpcrypt.cpp hex.cpp hmac.cpp integer.cpp iterhash.cpp misc.cpp modes.cpp modexppc.cpp mqueue.cpp nbtheory.cpp oaep.cpp osrng.cpp pch.cpp pkcspad.cpp pubkey.cpp queue.cpp randpool.cpp rdtables.cpp rijndael.cpp rng.cpp rsa.cpp sha.cpp simple.cpp skipjack.cpp strciphr.cpp trdlocal.cpp
DLLOBJS := $(DLLSRCS:.cpp=.export.o)
#################################################################
# Recipes
# Import lib testing
LIBIMPORTOBJS := $(LIBOBJS:.o=.import.o)
TESTIMPORTOBJS := $(TESTOBJS:.o=.import.o)
DLLTESTOBJS := dlltest.dllonly.o
# For various targets, see https://www.gnu.org/prep/standards/html_node/Standard-Targets.html
# We want to include libcryptopp, cryptest, clean, distclean, install, install-strip, uninstall
DIST_FILES := *.h *.cpp *.asm adhoc.cpp.proto License.txt Readme.txt GNUmakefile GNUmakefile-cross Doxyfile cryptest* cryptlib* dlltest* cryptdll* cryptopp.rc TestVectors/*.txt TestData/*.dat
all cryptest: cryptest.exe
# For Shared Objects, Diff, Dist/Zip rules
LIB_VER := $(shell $(EGREP) "define CRYPTOPP_VERSION" config.h | cut -d" " -f 3)
LIB_MAJOR := $(shell echo $(LIB_VER) | cut -c 1)
LIB_MINOR := $(shell echo $(LIB_VER) | cut -c 2)
LIB_PATCH := $(shell echo $(LIB_VER) | cut -c 3)
all: cryptest.exe
ifneq ($(IS_DARWIN),0)
static: libcryptopp.a
ifeq ($(IS_DARWIN),0)
shared dynamic: libcryptopp.so
shared dynamic dylib: libcryptopp.dylib
else
shared dynamic: libcryptopp.dylib
static: libcryptopp.a
shared dynamic: libcryptopp.so
endif
asan ubsan: libcryptopp.a cryptest.exe
.PHONY: deps
deps GNUmakefile.deps:
$(CXX) $(CXXFLAGS) -MM *.cpp > GNUmakefile.deps
.PHONY: asan ubsan align aligned
asan ubsan align aligned: libcryptopp.a cryptest.exe
.PHONY: test check
test check: cryptest.exe
./cryptest.exe v
DOC_DIRECTORY := $(shell $(EGREP) "OUTPUT_DIRECTORY" Doxyfile | grep -v "\#" | cut -d "=" -f 2)
ifeq ($(DOC_DIRECTORY),)
DOC_DIRECTORY := html-docs
endif
.PHONY: docs html
docs html:
-$(RM) -r $(DOC_DIRECTORY)/
doxygen Doxyfile -d CRYPTOPP_DOXYGEN_PROCESSING
-$(RM) CryptoPPRef.zip
zip -9 CryptoPPRef.zip -x ".*" -x "*/.*" -r $(DOC_DIRECTORY)/
.PHONY: clean
clean:
-$(RM) cryptest.exe libcryptopp.a libcrypto++.a libcryptopp.so libcrypto++.so libcryptopp.dylib $(LIBOBJS) $(TESTOBJS) $(TEMPS) cryptopp.dll libcryptopp.dll.a libcryptopp.import.a cryptest.import.exe dlltest.exe $(DLLOBJS) $(LIBIMPORTOBJS) $(TESTI MPORTOBJS) $(DLLTESTOBJS)
ifneq ($(IS_DARWIN),0)
-$(RM) -r cryptest.exe.dSYM
-$(RM) libcryptopp.a libcryptopp.so libcryptopp.dylib cryptopp.dll libcryptopp.dll.a libcryptopp.import.a
-$(RM) adhoc.cpp.o adhoc.cpp.proto.o $(LIBOBJS) $(TESTOBJS) $(DLLOBJS) $(LIBIMPORTOBJS) $(TESTIMPORTOBJS) $(DLLTESTOBJS) *.stackdump core-*
-$(RM) cryptest.exe dlltest.exe cryptest.import.exe ct
ifneq ($(wildcard *.exe.dSYM),)
-$(RM) -r *.exe.dSYM/
endif
.PHONY: distclean
distclean:
-$(RM) -r GNUmakefile.deps *.o *.obj *.a *.so *.dll *.dylib *.exe *.s *.ii a.out *~ \.*~ *\.h\. *\.cpp\. *.bu *.bak adhoc.cpp adhoc.cpp.copied *.diff *.patch cryptopp.zip
ifneq ($(IS_DARWIN),0)
-$(RM) *.dSYM .DS_Store TestVectors/.DS_Store TestData/.DS_Store
distclean: clean
-$(RM) adhoc.cpp adhoc.cpp.copied GNUmakefile.deps cryptest-*result.txt *.o *.ii *.s
ifneq ($(wildcard cryptopp$(LIB_VER)\.*),)
-$(RM) cryptopp$(LIB_VER)\.*
endif
ifneq ($(wildcard $(DOC_DIRECTORY)),)
-$(RM) -r $(DOC_DIRECTORY)
endif
ifneq ($(wildcard CryptoPPRef.zip),)
-$(RM) CryptoPPRef.zip
endif
.PHONY: install
install:
$(MKDIR) -p $(PREFIX)/include/cryptopp $(PREFIX)/lib $(PREFIX)/bin
-$(CP) *.h $(PREFIX)/include/cryptopp
-$(CHMOD) 755 $(PREFIX)/include/cryptopp
-$(CHMOD) 644 $(PREFIX)/include/cryptopp/*.h
-$(CP) libcryptopp.a $(PREFIX)/lib
-$(CHMOD) 644 $(PREFIX)/lib/libcryptopp.a
-$(CP) cryptest.exe $(PREFIX)/bin
ifeq ($(IS_DARWIN),0)
-$(CP) *.so $(PREFIX)/lib
-$(CHMOD) 755 $(PREFIX)/bin/cryptest.exe
ifneq ($(IS_DARWIN),0)
-$(CP) libcryptopp.dylib $(PREFIX)/lib
-$(CHMOD) 755 $(PREFIX)/lib/libcryptopp.dylib
else
-$(CP) *.dylib $(PREFIX)/lib
-$(CP) libcryptopp.so $(PREFIX)/lib
-$(CHMOD) 755 $(PREFIX)/lib/libcryptopp.so
endif
.PHONY: install-strip
install-strip: install
-$(STRIP) -s $(PREFIX)/bin/cryptest.exe
ifeq ($(IS_DARWIN),0)
-$(STRIP) -s $(PREFIX)/lib/libcryptopp.so
else
-$(STRIP) -s $(PREFIX)/lib/libcryptopp.dylib
endif
.PHONY: uninstall remove
uninstall remove:
-$(RM) -rf $(PREFIX)/include/cryptopp
.PHONY: remove uninstall
remove uninstall:
-$(RM) -r $(PREFIX)/include/cryptopp
-$(RM) $(PREFIX)/lib/libcryptopp.a
-$(RM) $(PREFIX)/bin/cryptest.exe
ifeq ($(IS_DARWIN),0)
-$(RM) $(PREFIX)/lib/libcryptopp.so
else
ifneq ($(IS_DARWIN),0)
-$(RM) $(PREFIX)/lib/libcryptopp.dylib
else
-$(RM) $(PREFIX)/lib/libcryptopp.so
endif
DIST_FILES = *.h *.cpp *.asm License.txt Readme.txt Install.txt GNUmakefile GNUmakefile-cross \
Doxyfile cryptest_bds.bdsgroup cryptest_bds.bdsproj cryptest_bds.bpf cryptlib_bds.bdsproj \
cryptest.sln cryptest.dsp cryptest.dsw cryptest.vcproj dlltest.dsp dlltest.vcproj \
cryptlib.dsp cryptlib.vcproj cryptopp.rc TestVectors/*.txt TestData/*.dat
.PHONY: zip dist
zip dist: distclean
-zip -q -9 cryptopp.zip $(DIST_FILES)
libcryptopp.a: $(LIBOBJS)
libcryptopp.a: public_service | $(LIBOBJS)
$(AR) $(ARFLAGS) $@ $(LIBOBJS)
$(RANLIB) $@
libcryptopp.so: $(LIBOBJS)
$(CXX) -shared -o $@ $(CXXFLAGS) $(LIBOBJS)
libcryptopp.so: public_service | $(LIBOBJS)
$(CXX) -shared -o $@ $(CXXFLAGS) $(GOLD_OPTION) $(LIBOBJS) $(LDLIBS)
libcryptopp.dylib: $(LIBOBJS)
$(CXX) -shared -dynamiclib -o $@ $(CXXFLAGS) $(LIBOBJS)
$(CXX) -dynamiclib -o $@ $(CXXFLAGS) -install_name "$@" -current_version "$(LIB_MAJOR).$(LIB_MINOR).$(LIB_PATCH)" -compatibility_version "$(LIB_MAJOR).$(LIB_MINOR)" $(LIBOBJS)
.PHONY: cryptest.exe
cryptest.exe: libcryptopp.a $(TESTOBJS)
$(CXX) -o $@ $(CXXFLAGS) $(TESTOBJS) ./libcryptopp.a $(LDFLAGS) $(LDLIBS)
cryptest.exe: public_service | libcryptopp.a $(TESTOBJS)
$(CXX) -o $@ $(CXXFLAGS) $(TESTOBJS) ./libcryptopp.a $(LDFLAGS) $(GOLD_OPTION) $(LDLIBS)
nolib: $(OBJS) # makes it faster to test changes
$(CXX) -o ct $(CXXFLAGS) $(OBJS) $(LDFLAGS) $(LDLIBS)
dll: cryptest.import.exe dlltest.exe
@ -482,6 +376,41 @@ cryptest.import.exe: cryptopp.dll libcryptopp.import.a $(TESTIMPORTOBJS)
dlltest.exe: cryptopp.dll $(DLLTESTOBJS)
$(CXX) -o $@ $(CXXFLAGS) $(DLLTESTOBJS) -L. -lcryptopp.dll $(LDFLAGS) $(LDLIBS)
# This recipe requires a previous "svn co -r 541 https://svn.code.sf.net/p/cryptopp/code/trunk/c5"
.PHONY: diff
diff:
-$(RM) cryptopp$(LIB_VER).diff
-svn diff -r 541 > cryptopp$(LIB_VER).diff
# This recipe prepares the distro files
TEXT_FILES := *.h *.cpp *.asm adhoc.cpp.proto License.txt Readme.txt Doxyfile cryptest* cryptlib* dlltest* cryptdll* cryptopp.rc TestVectors/*.txt TestData/*.dat
EXEC_FILES := GNUmakefile GNUmakefile-cross TestData/ TestVectors/
.PHONY: convert
convert:
chmod a-x $(TEXT_FILES)
chmod u+x $(EXEC_FILES)
chmod u+x cryptest.sh
unix2dos --keepdate --quiet $(TEXT_FILES)
unix2dos --keepdate --quiet *.sln *.vcproj
dos2unix --keepdate --quiet GNUmakefile GNUmakefile-cross cryptest.sh
.PHONY: zip dist
zip dist: | distclean convert diff
zip -q -9 cryptopp$(LIB_VER).zip $(DIST_FILES)
ifeq ($(wildcard cryptopp$(LIB_VER).diff),cryptopp$(LIB_VER).diff)
zip -q -9 -u cryptopp$(LIB_VER).zip cryptopp$(LIB_VER).diff
endif
ifeq ($(wildcard vs2010.zip),vs2010.zip)
zip -q -9 -u cryptopp$(LIB_VER).zip vs2010.zip
endif
ifeq ($(wildcard config.recommend),config.recommend)
zip -q -9 -u cryptopp$(LIB_VER).zip config.recommend
endif
ifeq ($(wildcard cryptest-sh.zip),cryptest-sh.zip)
-zip -d cryptopp$(LIB_VER).zip cryptest-sh.zip
endif
adhoc.cpp: adhoc.cpp.proto
ifeq ($(wildcard adhoc.cpp),)
cp adhoc.cpp.proto adhoc.cpp
@ -489,32 +418,23 @@ else
touch adhoc.cpp
endif
.PHONY: system
system: ;
$(info CXX: $(CXX))
$(info CXXFLAGS: $(CXXFLAGS))
$(info GCC_COMPILER: $(GCC_COMPILER))
$(info CLANG_COMPILER: $(CLANG_COMPILER))
$(info INTEL_COMPILER: $(INTEL_COMPILER))
$(info SUN_COMPILER: $(SUN_COMPILER))
$(info IS_GCC_41: $(IS_GCC_41))
$(info IS_GCC_42: $(IS_GCC_42))
$(info IS_GCC_45: $(IS_GCC_45))
$(info IS_GCC_49: $(IS_GCC_49))
$(info UNALIGNED_ACCESS: $(UNALIGNED_ACCESS))
$(info UNAME: $(shell $(UNAME) -a))
$(info MACHINE: $(MACHINE))
$(info SYSTEM: $(SYSTEM))
$(info RELEASE: $(RELEASE))
$(info IS_X86: $(IS_X86))
$(info IS_X86_64: $(IS_X86_64))
$(info IS_DARWIN: $(IS_DARWIN))
$(info IS_LINUX: $(IS_LINUX))
$(info IS_MINGW: $(IS_MINGW))
$(info IS_CYGWIN: $(IS_CYGWIN))
$(info IS_OPENBSD: $(IS_OPENBSD))
$(info IS_SUN: $(IS_SUN))
$(info IS_FEDORA22_i686: $(IS_FEDORA22_i686))
# Include dependencies, if present. You must issue `make deps` to create them.
ifeq ($(wildcard GNUmakefile.deps),GNUmakefile.deps)
-include GNUmakefile.deps
endif # Dependencies
# Work around MacPorts/GCC issue with init_priority. Apple/GCC and Fink/GCC are fine; limit to MacPorts.
# Also see https://lists.macosforge.org/pipermail/macports-users/2015-September/039223.html
ifneq ($(MACPORTS_COMPILER),0)
ifneq ($(GCC_COMPILER),0)
ifeq ($(findstring -DMACPORTS_GCC_COMPILER,$(CXXFLAGS)),)
cryptlib.o:
$(CXX) $(CXXFLAGS) -DMACPORTS_GCC_COMPILER=1 -c cryptlib.cpp
cpu.o:
$(CXX) $(CXXFLAGS) -DMACPORTS_GCC_COMPILER=1 -c cpu.cpp
endif
endif
endif
%.dllonly.o : %.cpp
$(CXX) $(CXXFLAGS) -DCRYPTOPP_DLL_ONLY -c $< -o $@
@ -528,19 +448,24 @@ system: ;
%.o : %.cpp
$(CXX) $(CXXFLAGS) -c $<
#################################################################
# Dependencies
# Do not build dependencies for some targets
NO_DEPS = system dist zip install install-strip uninstall remove clean distclean
ifeq ($(findstring $(MAKECMDGOALS),$(NO_DEPS)),)
# Do not build dependencies when multiarch is in effect
ifeq ($(MULTIARCH),0)
-include GNUmakefile.deps
# Warn of potential configurations issues. This will go away after 5.6.3
UNALIGNED_ACCESS := $(shell $(EGREP) -c "^[[:space:]]*//[[:space:]]*\#[[:space:]]*define[[:space:]]*CRYPTOPP_NO_UNALIGNED_DATA_ACCESS" config.h)
NO_INIT_PRIORITY := $(shell $(EGREP) -c "^[[:space:]]*//[[:space:]]*\#[[:space:]]*define[[:space:]]*CRYPTOPP_INIT_PRIORITY" config.h)
COMPATIBILITY_562 := $(shell $(EGREP) -c "^[[:space:]]*\#[[:space:]]*define[[:space:]]*CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562" config.h)
.PHONY: public_service
public_service:
ifneq ($(UNALIGNED_ACCESS),0)
$(info WARNING: CRYPTOPP_NO_UNALIGNED_DATA_ACCESS is not defined in config.h.)
endif
ifneq ($(NO_INIT_PRIORITY),0)
$(info WARNING: CRYPTOPP_INIT_PRIORITY is not defined in config.h.)
endif
ifneq ($(COMPATIBILITY_562),0)
$(info WARNING: CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 is defined in config.h.)
endif
ifneq (x$(UNALIGNED_ACCESS)$(NO_INIT_PRIORITY)$(COMPATIBILITY_562),x000)
$(info WARNING: You should make these changes in config.h, and not CXXFLAGS.)
$(info WARNING: You can 'mv config.recommend config.h', but it breaks versioning.)
$(info WARNING: See http://cryptopp.com/wiki/config.h for more details.)
$(info )
endif
deps GNUmakefile.deps:
$(CXX) $(CXXFLAGS) -MM *.cpp > GNUmakefile.deps
endif # NO_DEPS

View File

@ -1,69 +1,42 @@
#################################################################
# Tool and flag setup
CXXFLAGS ?= -DNDEBUG -g2 -Os -fPIC -pipe
AS ?= as
AR ?= ar
ARFLAGS ?= -cr # ar needs the dash on OpenBSD
RANLIB ?= ranlib
STRIP ?= strip -s
CP ?= cp
MKDIR ?= mkdir
EGREP ?= egrep
UNAME ?= uname
# Default setting from environment. Disable verbose flag, add create flag
ifeq ($(findstring rv,$(ARFLAGS)),rv)
ARFLAGS = cr
endif
#########################
# CXXFLAGS
# -fPIC is supported, and enabled by default for x86_64. Its required by Android 5.1
# We can augment CXXFLAGS if the user exports them in the shell, or if the user
# omits them. However, if the user `make CXXFLAGS="-g1"`, then that's what
# the user gets. Make does not override them, and does not honor our '+='.
CXXFLAGS ?= -DNDEBUG -g2 -Os -Wall -Wextra
# Add -DNDEBUG if nothing specified
ifeq ($(filter -DDEBUG -DNDEBUG,$(CXXFLAGS)),)
CXXFLAGS += -DNDEBUG
endif
# Add a symolize if nothing specified
ifeq ($(filter -g -g1 -g2 -g3,$(CXXFLAGS)),)
CXXFLAGS += -g2
endif
# Add an optimize if nothing specified
ifeq ($(filter -O -O0 -O1 -O2 -O3 -Og -Os -Oz -Ofast,$(CXXFLAGS)),)
CXXFLAGS += -Os
endif
# the following options reduce code size, but breaks link or makes link very slow on some systems
# The following options reduce code size, but breaks link or makes link very slow on some systems
# CXXFLAGS += -ffunction-sections -fdata-sections
# LDFLAGS += -Wl,--gc-sections
CXXFLAGS += -Wno-unused-function -Wno-unused-parameter -Wno-unused-variable
#########################
# Compilers
ARFLAGS = -cr # ar needs the dash on OpenBSD
RANLIB ?= ranlib
CP = cp
MKDIR = mkdir
EGREP = egrep
CHMOD = chmod
# Cygwin change the version string to "g++ (GCC) 4.9.3"
GCC_COMPILER = $(shell $(CXX) -v 2>&1 | $(EGREP) -i -c "^(gcc|g\+\+) version")
CLANG_COMPILER = $(shell $(CXX) --version 2>&1 | $(EGREP) -i -c "clang")
INTEL_COMPILER = $(shell $(CXX) --version 2>&1 | $(EGREP) -i -c "\(ICC\)")
#########################
# Assemblers
IS_X86=0
IS_LINUX=0
IS_MINGW=0
IS_DARWIN=0
UNAME=CrossCompile
# Also see LLVM Bug 24200 (https://llvm.org/bugs/show_bug.cgi?id=24200)
# CLANG_ASSEMBLER ?= $(shell $(CXX) -xc -c /dev/null -Wa,-v -o/dev/null 2>&1 | $(EGREP) -i -c "^clang")
# TODO: Uncomment the line above when Clang's integrated assembler can parse and generate code that passes the self tests.
# Default prefix for make install
ifeq ($(PREFIX),)
PREFIX = /usr/local
endif
# Sadly, we can't actually use GCC_PRAGMA_AWARE because of GCC bug 53431.
# Its a shame because GCC has so much to offer by the way of analysis.
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
ifneq ($(CLANG_COMPILER),0)
CXXFLAGS += -Wall
endif
#################################################################
# iOS cross-compile configuration. Works in conjunction with IS_CROSS_COMPILE.
# See http://www.cryptopp.com/wiki/iOS_(Command_Line).
ifeq ($(IS_IOS),1)
CXX ?= clang++
CXX = clang++
CXXFLAGS += -DCRYPTOPP_DISABLE_ASM $(IOS_FLAGS)
CXXFLAGS += -arch $(IOS_ARCH) -isysroot $(IOS_SYSROOT)
CXXFLAGS += -stdlib=libc++
@ -72,7 +45,6 @@ ifeq ($(IS_IOS),1)
ARFLAGS = -static -o
endif
#################################################################
# Android cross-compile configuration. Works in conjunction with IS_CROSS_COMPILE.
# See http://www.cryptopp.com/wiki/Android_(Command_Line).
ifeq ($(IS_ANDROID),1)
@ -82,7 +54,6 @@ ifeq ($(IS_ANDROID),1)
LDLIBS += $(ANDROID_STL_LIB)
endif
#################################################################
# ARM embedded cross-compile configuration. Works in conjunction with IS_CROSS_COMPILE.
# See http://www.cryptopp.com/wiki/ARM_Embedded_(Command_Line)
# and http://www.cryptopp.com/wiki/ARM_Embedded_(Bare Metal).
@ -92,80 +63,82 @@ ifeq ($(IS_ARM_EMBEDDED),1)
CXXFLAGS += --sysroot=$(ARM_EMBEDDED_SYSROOT)
endif
#################################################################
# Warning options
ifneq ($(GCC_COMPILER),0)
CXXFLAGS += -Wno-type-limits -Wno-unknown-pragmas
# List cryptlib.cpp first in an attempt to tame C++ static initialization problems
SRCS := cryptlib.cpp $(filter-out cryptlib.cpp pch.cpp simple.cpp winpipes.cpp cryptlib_bds.cpp,$(wildcard *.cpp))
ifneq ($(IS_MINGW),0)
SRCS += winpipes.cpp
endif
ifneq ($(CLANG_COMPILER),0)
CXXFLAGS += -Wno-tautological-compare
endif
#################################################################
# Public service announcement
# Do not warn for some targets
NO_WARN = GNUmakefile.deps deps system dist zip install install-strip uninstall remove clean distclean
ifeq ($(findstring $(MAKECMDGOALS),$(NO_WARN)),)
UNALIGNED_ACCESS = $(shell $(EGREP) -c "^// \#define CRYPTOPP_NO_UNALIGNED_DATA_ACCESS" config.h)
ifneq ($(UNALIGNED_ACCESS),0)
$(info WARNING: CRYPTOPP_NO_UNALIGNED_DATA_ACCESS is not defined in config.h)
endif
endif # NO_WARN
#################################################################
# Sources, objects and temporaries
# List of sources to compile and objects to link
WIN_SRCS = pch.cpp fipsalgt.cpp cryptlib_bds.cpp winpipes.cpp
SRCS = $(filter-out $(WIN_SRCS), $(wildcard *.cpp))
OBJS = $(SRCS:.cpp=.o)
# Compiling with --save-temps creates these
TEMPS = $(SRCS:.cpp=.s) $(SRCS:.cpp=.ii)
# List of objects with crytlib.o at the first index position
OBJS := $(SRCS:.cpp=.o)
# test.o needs to be after bench.o for cygwin 1.1.4 (possible ld bug?)
TESTOBJS = bench.o bench2.o test.o validat1.o validat2.o validat3.o adhoc.o datatest.o regtest.o fipsalgt.o dlltest.o
LIBOBJS = $(filter-out $(TESTOBJS),$(OBJS))
TESTOBJS := bench.o bench2.o test.o validat1.o validat2.o validat3.o adhoc.o datatest.o regtest.o fipsalgt.o dlltest.o
LIBOBJS := $(filter-out $(TESTOBJS),$(OBJS))
DLLSRCS = algebra.cpp algparam.cpp asn.cpp basecode.cpp cbcmac.cpp channels.cpp cryptlib.cpp des.cpp dessp.cpp dh.cpp dll.cpp dsa.cpp ec2n.cpp eccrypto.cpp ecp.cpp eprecomp.cpp files.cpp filters.cpp fips140.cpp fipstest.cpp gf2n.cpp gfpcrypt.cpp hex.cpp hmac.cpp integer.cpp iterhash.cpp misc.cpp modes.cpp modexppc.cpp mqueue.cpp nbtheory.cpp oaep.cpp osrng.cpp pch.cpp pkcspad.cpp pubkey.cpp queue.cpp randpool.cpp rdtables.cpp rijndael.cpp rng.cpp rsa.cpp sha.cpp simple.cpp skipjack.cpp strciphr.cpp trdlocal.cpp
DLLOBJS = $(DLLSRCS:.cpp=.export.o)
# List cryptlib.cpp first in an attempt to tame C++ static initialization problems
DLLSRCS := cryptlib.cpp algebra.cpp algparam.cpp asn.cpp basecode.cpp cbcmac.cpp channels.cpp des.cpp dessp.cpp dh.cpp dll.cpp dsa.cpp ec2n.cpp eccrypto.cpp ecp.cpp eprecomp.cpp files.cpp filters.cpp fips140.cpp fipstest.cpp gf2n.cpp gfpcrypt.cpp hex.cpp hmac.cpp integer.cpp iterhash.cpp misc.cpp modes.cpp modexppc.cpp mqueue.cpp nbtheory.cpp oaep.cpp osrng.cpp pch.cpp pkcspad.cpp pubkey.cpp queue.cpp randpool.cpp rdtables.cpp rijndael.cpp rng.cpp rsa.cpp sha.cpp simple.cpp skipjack.cpp strciphr.cpp trdlocal.cpp
DLLOBJS := $(DLLSRCS:.cpp=.export.o)
#################################################################
# Recipes
# Import lib testing
LIBIMPORTOBJS := $(LIBOBJS:.o=.import.o)
TESTIMPORTOBJS := $(TESTOBJS:.o=.import.o)
DLLTESTOBJS := dlltest.dllonly.o
# For various targets, see https://www.gnu.org/prep/standards/html_node/Standard-Targets.html
# We want to include libcryptopp, cryptest, clean, distclean, install, install-strip, uninstall
all: cryptest.exe
all cryptest: cryptest.exe
ifneq ($(IS_DARWIN),0)
static: libcryptopp.a
shared dynamic dylib: libcryptopp.dylib
else
static: libcryptopp.a
shared dynamic: libcryptopp.so
endif
test: cryptest.exe
./cryptest.exe v
.PHONY: clean
clean:
-$(RM) cryptest.exe libcryptopp.a libcryptopp.so GNUmakefile.deps $(LIBOBJS) $(DLLOBJS) $(TESTOBJS)
-$(RM) -r *.dSYM
-$(RM) cryptest.exe dlltest.exe libcryptopp.a libcryptopp.so libcryptopp.dylib cryptopp.dll libcryptopp.dll.a libcryptopp.import.a cryptest.import.exe ct
-$(RM) adhoc.cpp.o adhoc.cpp.proto.o $(LIBOBJS) $(TESTOBJS) $(DLLOBJS) $(LIBIMPORTOBJS) $(TESTIMPORTOBJS) $(DLLTESTOBJS)
ifneq ($(wildcard *.dSYM),)
-$(RM) -r cryptest.exe.dSYM dlltest.exe.dSYM
endif
.PHONY: distclean
distclean: clean
-$(RM) adhoc.cpp adhoc.cpp.copied GNUmakefile.deps cryptopp$(LIB_VER).diff cryptopp$(LIB_VER).zip *.o *.ii *.s
.PHONY: install
install:
$(MKDIR) -p $(PREFIX)/include/cryptopp $(PREFIX)/lib $(PREFIX)/bin
-$(CP) *.h $(PREFIX)/include/cryptopp
-$(CP) *.a $(PREFIX)/lib
-$(CP) *.so $(PREFIX)/lib
-$(CP) *.exe $(PREFIX)/bin
-$(CHMOD) 755 $(PREFIX)/include/cryptopp
-$(CHMOD) 644 $(PREFIX)/include/cryptopp/*.h
-$(CP) libcryptopp.a $(PREFIX)/lib
-$(CHMOD) 644 $(PREFIX)/lib/libcryptopp.a
-$(CP) cryptest.exe $(PREFIX)/bin
-$(CHMOD) 755 $(PREFIX)/bin/cryptest.exe
ifneq ($(IS_DARWIN),0)
-$(CP) libcryptopp.dylib $(PREFIX)/lib
-$(CHMOD) 755 $(PREFIX)/lib/libcryptopp.dylib
else
-$(CP) libcryptopp.so $(PREFIX)/lib
-$(CHMOD) 755 $(PREFIX)/lib/libcryptopp.so
endif
.PHONY: remove
remove:
-$(RM) -rf $(PREFIX)/include/cryptopp
.PHONY: remove uninstall
remove uninstall:
-$(RM) -r $(PREFIX)/include/cryptopp
-$(RM) $(PREFIX)/lib/libcryptopp.a
-$(RM) $(PREFIX)/lib/libcryptopp.so
-$(RM) $(PREFIX)/bin/cryptest.exe
ifneq ($(IS_DARWIN),0)
-$(RM) $(PREFIX)/lib/libcryptopp.dylib
else
-$(RM) $(PREFIX)/lib/libcryptopp.so
endif
libcryptopp.a: $(LIBOBJS)
$(AR) $(ARFLAGS) $@ $(LIBOBJS)
@ -174,7 +147,6 @@ libcryptopp.a: $(LIBOBJS)
libcryptopp.so: $(LIBOBJS)
$(CXX) $(CXXFLAGS) -shared -o $@ $(LIBOBJS) $(LDFLAGS) $(LDLIBS)
.PHONY: system.exe
cryptest.exe: libcryptopp.a $(TESTOBJS)
$(CXX) -o $@ $(CXXFLAGS) $(TESTOBJS) ./libcryptopp.a $(LDFLAGS) $(LDLIBS)
@ -185,36 +157,13 @@ else
touch adhoc.cpp
endif
.PHONY: system
system: ;
$(info CXX: $(CXX))
$(info CXXFLAGS: $(CXXFLAGS))
$(info LDLIBS: $(LDLIBS))
$(info GCC_COMPILER: $(GCC_COMPILER))
$(info CLANG_COMPILER: $(CLANG_COMPILER))
$(info INTEL_COMPILER: $(INTEL_COMPILER))
$(info UNALIGNED_ACCESS: $(UNALIGNED_ACCESS))
$(info UNAME: $(shell $(UNAME) -a))
$(info MACHINE: $(MACHINE))
$(info SYSTEM: $(SYSTEM))
$(info RELEASE: $(RELEASE))
%.o : %.cpp
$(CXX) $(CXXFLAGS) -c $<
#################################################################
# Dependencies
# Do not build dependencies for some targets
NO_DEPS = system dist zip install install-strip uninstall remove clean distclean
ifeq ($(findstring $(MAKECMDGOALS),$(NO_DEPS)),)
# Do not build dependencies when multiarch is in effect
ifeq ($(MULTIARCH),0)
# Do not build dependencies when cleaning
ifneq ($(findstring clean,$(MAKECMDGOALS)),clean)
-include GNUmakefile.deps
endif
deps GNUmakefile.deps:
GNUmakefile.deps:
$(CXX) $(CXXFLAGS) -MM *.cpp > GNUmakefile.deps
endif # NO_DEPS

View File

@ -1,5 +1,5 @@
Crypto++: a C++ Class Library of Cryptographic Schemes
Version 5.6.2 - 2/20/2013
Version 5.6.3 - NOV/01/2015
Crypto++ Library is a free C++ class library of cryptographic schemes.
Currently the library contains the following algorithms:
@ -79,10 +79,10 @@ License.txt for the fine print.
The following compilers are supported for this release. Please visit
http://www.cryptopp.com the most up to date build instructions and porting notes.
* MSVC 6.0 - 2010
* GCC 3.3 - 4.5
* MSVC 6.0 - 2015
* GCC 3.3 - 5.2
* C++Builder 2010
* Intel C++ Compiler 9 - 11.1
* Intel C++ Compiler 9 - 16.0
* Sun Studio 12u1, Express 11/08, Express 06/10
*** Important Usage Notes ***
@ -449,4 +449,50 @@ the mailing list.
- fixed infinite recursion when on x64, assembly disabled, and no AESNI
- ported to MSVC 2012, GCC 4.7, Clang 3.2, Solaris Studio 12.3, Intel C++ Compiler 13.0
Written by Wei Dai
5.6.3 - maintenance release, honored API/ABI/Versioning requirements
- expanded processes to include community and its input
- fixed CVE-2015-2141
- cleared most Undefined Behavior Sanitizer (UBsan) findings
- cleared all Address Sanitizer (Asan) findings
- cleared most Valgrind findings
- cleared all Enterprise Analysis (/analyze) findings
- cleared most GCC warnings with -Wall
- cleared most Clang warnings with -Wall
- cleared most MSVC warnings with /W4
- added -fPIC for x86_64/amd64 builds. Off by default for i386
- added HKDF class for RFC 5868
- added generic DeviceState interface and RDRAND/RDSEED classes
- switched to member_ptr due to C++ 11 warnings for auto_ptr
- initialization of C++ static objects, off by default
* GCC and init_priotirty/constructor attributes
* MSVC and init_seg(lib)
* CRYPTOPP_INIT_PRIORITY disabled by default, but available
- improved OS X support
- improved GNUmakefile support for Testing and QA
- added additional self tests for improved Testing and QA
- added cryptest.sh for systematic Testing and QA
- added GNU Gold linker support
- added Visual Studio 2010 solution and project files in vs2010.zip
- added more complete ARM, ARM64, MIPS, MIPS64, S/390 and X32 (ILP32) support
- __ARM_FEATURE_UNALIGNED and definition of CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
- unconditionally define CRYPTOPP_NO_UNALIGNED_DATA_ACCESS for Makefile
target 'ubsan' and at -O3 due to GCC vectorization on x86 and x86_64
- workaround ARMEL/GCC 5.2 bug and failed self test
- fixed crash in MQV due to GCC 4.9+ and inlining
- fixed hang in SHA due to GCC 4.9+ and inlining
- fixed missing rdtables::Te under VS with ALIGNED_DATA_ACCESS
- fixed S/390 and big endian feature detection
- fixed S/390 and int128_t/uint128_t detection
- fixed X32 (ILP32) feature detection
- removed _CRT_SECURE_NO_DEPRECATE for Microsoft platforms
- utilized bound checking interfaces from ISO/IEC TR 24772 when available
- introduced CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
- added additional Doxygen documentation
5.7 - nearly identical to 5.6.3
- minor breaks to the ABI and ABI
- cleared remaining Undefined Behavior Sanitizer (UBsan) findings
- cleared remaining Valgrind findings
- removed CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
Written by Wei Dai and the Crypto++ Project

View File

@ -1,19 +1,22 @@
#include "cryptlib.h"
#include "stdcpp.h"
#include "misc.h"
#include "config.h"
#include <iosfwd>
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4100 4189 4996)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic ignored "-Wunused-variable"
#endif
USING_NAMESPACE(CryptoPP)
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-variable"
# pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
USING_NAMESPACE(std)
extern int (*AdhocTest)(int argc, char *argv[]);
int MyAdhocTest(int argc, char *argv[])
{
CRYPTOPP_UNUSED(argc), CRYPTOPP_UNUSED(argv);
return 0;
}

View File

@ -2,7 +2,6 @@
#include "pch.h"
#include "adler32.h"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
@ -47,8 +46,8 @@ void Adler32::Update(const byte *input, size_t length)
s2 %= BASE;
}
CRYPTOPP_ASSERT(s1 < BASE);
CRYPTOPP_ASSERT(s2 < BASE);
assert(s1 < BASE);
assert(s2 < BASE);
m_s1 = (word16)s1;
m_s2 = (word16)s2;

View File

@ -1,3 +1,8 @@
// adler32.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Class files for ADLER-32 checksum calculations
#ifndef CRYPTOPP_ADLER32_H
#define CRYPTOPP_ADLER32_H

5
aes.h
View File

@ -1,3 +1,8 @@
// aes.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Class file for the AES cipher (Rijndael)
#ifndef CRYPTOPP_AES_H
#define CRYPTOPP_AES_H

View File

@ -7,7 +7,6 @@
#include "algebra.h"
#include "integer.h"
#include "trap.h"
#include <vector>
@ -207,50 +206,49 @@ template <class Element, class Iterator> Element GeneralCascadeMultiplication(co
struct WindowSlider
{
WindowSlider(const Integer &expIn, bool fastNegate, unsigned int windowSizeIn=0)
: m_exp(expIn), m_windowModulus(Integer::One()), m_windowSize(windowSizeIn), m_windowBegin(0), m_fastNegate(fastNegate), m_negateNext(false), m_firstTime(true), m_finished(false)
: exp(expIn), windowModulus(Integer::One()), windowSize(windowSizeIn), windowBegin(0), fastNegate(fastNegate), negateNext(false), firstTime(true), finished(false)
{
if (m_windowSize == 0)
if (windowSize == 0)
{
const unsigned int expLen = m_exp.BitCount();
m_windowSize = expLen <= 17 ? 1 : (expLen <= 24 ? 2 : (expLen <= 70 ? 3 : (expLen <= 197 ? 4 : (expLen <= 539 ? 5 : (expLen <= 1434 ? 6 : 7)))));
unsigned int expLen = exp.BitCount();
windowSize = expLen <= 17 ? 1 : (expLen <= 24 ? 2 : (expLen <= 70 ? 3 : (expLen <= 197 ? 4 : (expLen <= 539 ? 5 : (expLen <= 1434 ? 6 : 7)))));
}
m_windowModulus <<= m_windowSize;
windowModulus <<= windowSize;
}
void FindNextWindow()
{
const unsigned int expLen = m_exp.WordCount() * WORD_BITS;
unsigned int skipCount = m_firstTime ? 0 : m_windowSize;
m_firstTime = false;
while (!m_exp.GetBit(skipCount))
unsigned int expLen = exp.WordCount() * WORD_BITS;
unsigned int skipCount = firstTime ? 0 : windowSize;
firstTime = false;
while (!exp.GetBit(skipCount))
{
if (skipCount >= expLen)
{
m_finished = true;
finished = true;
return;
}
skipCount++;
}
m_exp >>= skipCount;
m_windowBegin += skipCount;
m_expWindow = word32(m_exp % (word(1) << m_windowSize));
exp >>= skipCount;
windowBegin += skipCount;
expWindow = word32(exp % (word(1) << windowSize));
if (m_fastNegate && m_exp.GetBit(m_windowSize))
if (fastNegate && exp.GetBit(windowSize))
{
m_negateNext = true;
m_expWindow = (word32(1) << m_windowSize) - m_expWindow;
m_exp += m_windowModulus;
negateNext = true;
expWindow = (word32(1) << windowSize) - expWindow;
exp += windowModulus;
}
else
m_negateNext = false;
negateNext = false;
}
Integer m_exp, m_windowModulus;
unsigned int m_windowSize, m_windowBegin;
word32 m_expWindow;
bool m_fastNegate, m_negateNext, m_firstTime, m_finished;
Integer exp, windowModulus;
unsigned int windowSize, windowBegin;
word32 expWindow;
bool fastNegate, negateNext, firstTime, finished;
};
template <class T>
@ -263,10 +261,10 @@ void AbstractGroup<T>::SimultaneousMultiply(T *results, const T &base, const Int
for (i=0; i<expCount; i++)
{
CRYPTOPP_ASSERT(expBegin->NotNegative());
assert(expBegin->NotNegative());
exponents.push_back(WindowSlider(*expBegin++, InversionIsFast(), 0));
exponents[i].FindNextWindow();
buckets[i].resize(1<<(exponents[i].m_windowSize-1), Identity());
buckets[i].resize(1<<(exponents[i].windowSize-1), Identity());
}
unsigned int expBitPosition = 0;
@ -278,16 +276,16 @@ void AbstractGroup<T>::SimultaneousMultiply(T *results, const T &base, const Int
notDone = false;
for (i=0; i<expCount; i++)
{
if (!exponents[i].m_finished && expBitPosition == exponents[i].m_windowBegin)
if (!exponents[i].finished && expBitPosition == exponents[i].windowBegin)
{
Element &bucket = buckets[i][exponents[i].m_expWindow/2];
if (exponents[i].m_negateNext)
Element &bucket = buckets[i][exponents[i].expWindow/2];
if (exponents[i].negateNext)
Accumulate(bucket, Inverse(g));
else
Accumulate(bucket, g);
exponents[i].FindNextWindow();
}
notDone = notDone || !exponents[i].m_finished;
notDone = notDone || !exponents[i].finished;
}
if (notDone)

View File

@ -1,3 +1,8 @@
// algebra.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Classes and functions for performing mathematics over different fields
#ifndef CRYPTOPP_ALGEBRA_H
#define CRYPTOPP_ALGEBRA_H
@ -49,8 +54,10 @@ public:
typedef T Element;
AbstractRing() {m_mg.m_pRing = this;}
AbstractRing(const AbstractRing &source) : AbstractGroup<T>(source) {m_mg.m_pRing = this;}
AbstractRing& operator=(const AbstractRing &source) {CRYPTOPP_UNUSED(source);return *this;}
AbstractRing(const AbstractRing &source)
{CRYPTOPP_UNUSED(source); m_mg.m_pRing = this;}
AbstractRing& operator=(const AbstractRing &source)
{CRYPTOPP_UNUSED(source); return *this;}
virtual bool IsUnit(const Element &a) const =0;
virtual const Element& MultiplicativeIdentity() const =0;
@ -210,7 +217,7 @@ public:
{Element::Divide(r, q, a, d);}
bool operator==(const EuclideanDomainOf<T> &rhs) const
{CRYPTOPP_UNUSED(rhs);return true;}
{CRYPTOPP_UNUSED(rhs); return true;}
private:
mutable Element result;

View File

@ -5,8 +5,7 @@
#ifndef CRYPTOPP_IMPORTS
#include "algparam.h"
#include "misc.h"
#include "trap.h"
#include "integer.h"
NAMESPACE_BEGIN(CryptoPP)
@ -20,10 +19,10 @@ bool CombinedNameValuePairs::GetVoidValue(const char *name, const std::type_info
return m_pairs1.GetVoidValue(name, valueType, pValue) || m_pairs2.GetVoidValue(name, valueType, pValue);
}
void AlgorithmParametersBase::operator=(const AlgorithmParametersBase& rhs)
void AlgorithmParametersBase::operator=(const AlgorithmParametersBase &rhs)
{
CRYPTOPP_UNUSED(rhs);
CRYPTOPP_ASSERT(false);
assert(false);
}
bool AlgorithmParametersBase::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
@ -61,7 +60,6 @@ AlgorithmParameters::AlgorithmParameters(const AlgorithmParameters &x)
AlgorithmParameters & AlgorithmParameters::operator=(const AlgorithmParameters &x)
{
// Should this be guarded for operations on itself??? This class befuddles me at times...
m_next.reset(const_cast<AlgorithmParameters &>(x).m_next.release());
return *this;
}

View File

@ -1,17 +1,26 @@
// algparam.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Classes and functions for working with NameValuePairs
#ifndef CRYPTOPP_ALGPARAM_H
#define CRYPTOPP_ALGPARAM_H
#include "cryptlib.h"
#include "smartptr.h"
#include "integer.h"
#include "secblock.h"
#include "config.h"
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-value"
# pragma GCC diagnostic ignored "-Wunused-variable"
// TODO: fix 6011 when the API/ABI can change
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 6011 28193)
#endif
#include "smartptr.h"
#include "secblock.h"
#include "integer.h"
#include "misc.h"
NAMESPACE_BEGIN(CryptoPP)
//! used to pass byte array input as part of a NameValuePairs object
@ -159,8 +168,9 @@ private:
};
template <class BASE, class T>
GetValueHelperClass<T, BASE> GetValueHelper(const T *pObject, const char *name, const std::type_info &valueType, void *pValue, const NameValuePairs *searchFirst=NULL)
GetValueHelperClass<T, BASE> GetValueHelper(const T *pObject, const char *name, const std::type_info &valueType, void *pValue, const NameValuePairs *searchFirst=NULL, BASE *dummy=NULL)
{
CRYPTOPP_UNUSED(dummy);
return GetValueHelperClass<T, BASE>(pObject, name, valueType, pValue, searchFirst);
}
@ -172,6 +182,68 @@ GetValueHelperClass<T, T> GetValueHelper(const T *pObject, const char *name, con
// ********************************************************
// VC60 workaround
#if defined(_MSC_VER) && (_MSC_VER < 1300)
template <class R>
R Hack_DefaultValueFromConstReferenceType(const R &)
{
return R();
}
template <class R>
bool Hack_GetValueIntoConstReference(const NameValuePairs &source, const char *name, const R &value)
{
return source.GetValue(name, const_cast<R &>(value));
}
template <class T, class BASE>
class AssignFromHelperClass
{
public:
AssignFromHelperClass(T *pObject, const NameValuePairs &source)
: m_pObject(pObject), m_source(source), m_done(false)
{
if (source.GetThisObject(*pObject))
m_done = true;
else if (typeid(BASE) != typeid(T))
pObject->BASE::AssignFrom(source);
}
template <class R>
AssignFromHelperClass & operator()(const char *name, void (T::*pm)(R)) // VC60 workaround: "const R &" here causes compiler error
{
if (!m_done)
{
R value = Hack_DefaultValueFromConstReferenceType(reinterpret_cast<R>(*(int *)NULL));
if (!Hack_GetValueIntoConstReference(m_source, name, value))
throw InvalidArgument(std::string(typeid(T).name()) + ": Missing required parameter '" + name + "'");
(m_pObject->*pm)(value);
}
return *this;
}
template <class R, class S>
AssignFromHelperClass & operator()(const char *name1, const char *name2, void (T::*pm)(R, S)) // VC60 workaround: "const R &" here causes compiler error
{
if (!m_done)
{
R value1 = Hack_DefaultValueFromConstReferenceType(reinterpret_cast<R>(*(int *)NULL));
if (!Hack_GetValueIntoConstReference(m_source, name1, value1))
throw InvalidArgument(std::string(typeid(T).name()) + ": Missing required parameter '" + name1 + "'");
S value2 = Hack_DefaultValueFromConstReferenceType(reinterpret_cast<S>(*(int *)NULL));
if (!Hack_GetValueIntoConstReference(m_source, name2, value2))
throw InvalidArgument(std::string(typeid(T).name()) + ": Missing required parameter '" + name2 + "'");
(m_pObject->*pm)(value1, value2);
}
return *this;
}
private:
T *m_pObject;
const NameValuePairs &m_source;
bool m_done;
};
#else
template <class T, class BASE>
class AssignFromHelperClass
{
@ -219,10 +291,12 @@ private:
const NameValuePairs &m_source;
bool m_done;
};
#endif
template <class BASE, class T>
AssignFromHelperClass<T, BASE> AssignFromHelper(T *pObject, const NameValuePairs &source)
AssignFromHelperClass<T, BASE> AssignFromHelper(T *pObject, const NameValuePairs &source, BASE *dummy=NULL)
{
CRYPTOPP_UNUSED(dummy);
return AssignFromHelperClass<T, BASE>(pObject, source);
}
@ -260,7 +334,6 @@ public:
AlgorithmParametersBase(const char *name, bool throwIfNotUsed)
: m_name(name), m_throwIfNotUsed(throwIfNotUsed), m_used(false) {}
// TODO: determine a library policy; implement the policy.
virtual ~AlgorithmParametersBase() CRYPTOPP_THROW
{
#ifdef CRYPTOPP_UNCAUGHT_EXCEPTION_AVAILABLE
@ -273,7 +346,7 @@ public:
throw ParameterNotUsed(m_name);
}
#ifndef CRYPTOPP_UNCAUGHT_EXCEPTION_AVAILABLE
catch(...)
catch(const Exception&)
{
}
#endif
@ -316,7 +389,7 @@ public:
void MoveInto(void *buffer) const
{
AlgorithmParametersTemplate<T>* p = new(buffer) AlgorithmParametersTemplate<T>(*this);
CRYPTOPP_UNUSED(p);
CRYPTOPP_UNUSED(p); // silence warning
}
protected:
@ -380,7 +453,11 @@ protected:
typedef AlgorithmParameters MakeParameters;
#else
template <class T>
#if __APPLE__
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed = false)
#else
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed = true)
#endif
{
return AlgorithmParameters()(name, value, throwIfNotUsed);
}
@ -392,8 +469,4 @@ AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwI
NAMESPACE_END
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic pop
#endif
#endif

View File

@ -37,11 +37,11 @@ void ARC4_Base::UncheckedSetKey(const byte *key, unsigned int keyLen, const Name
unsigned int keyIndex = 0, stateIndex = 0;
for (i=0; i<256; i++)
{
byte a = m_state[i];
unsigned int a = m_state[i];
stateIndex += key[keyIndex] + a;
stateIndex &= 0xff;
m_state[i] = m_state[stateIndex];
m_state[stateIndex] = a;
m_state[stateIndex] = byte(a);
if (++keyIndex >= keyLen)
keyIndex = 0;
}
@ -53,19 +53,19 @@ void ARC4_Base::UncheckedSetKey(const byte *key, unsigned int keyLen, const Name
template <class T>
static inline unsigned int MakeByte(T &x, T &y, byte *s)
{
byte a = s[x];
y = (y+a) & 0xff;
byte b = s[y];
s[x] = b;
s[y] = a;
x = (x+1) & 0xff;
unsigned int a = s[x];
y = byte((y+a) & 0xff);
unsigned int b = s[y];
s[x] = byte(b);
s[y] = byte(a);
x = byte((x+1) & 0xff);
return s[(a+b) & 0xff];
}
void ARC4_Base::GenerateBlock(byte *output, size_t size)
{
while (size--)
*output++ = (byte)MakeByte(m_x, m_y, m_state);
*output++ = static_cast<byte>(MakeByte(m_x, m_y, m_state));
}
void ARC4_Base::ProcessData(byte *outString, const byte *inString, size_t length)
@ -88,7 +88,7 @@ void ARC4_Base::ProcessData(byte *outString, const byte *inString, size_t length
{
do
{
*outString++ = *inString++ ^ MakeByte(x, y, s);
*outString++ = *inString++ ^ byte(MakeByte(x, y, s));
}
while(--length);
}

11
arc4.h
View File

@ -1,13 +1,22 @@
// arc4.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Implementation of ARC4
#ifndef CRYPTOPP_ARC4_H
#define CRYPTOPP_ARC4_H
#include "cryptlib.h"
#include "strciphr.h"
#include "secblock.h"
#include "smartptr.h"
NAMESPACE_BEGIN(CryptoPP)
namespace Weak1 {
//! _
//! \class ARC4_Base
//! \brief Allegedly RC4
class CRYPTOPP_NO_VTABLE ARC4_Base : public VariableKeyLength<16, 1, 256>, public RandomNumberGenerator, public SymmetricCipher, public SymmetricCipherDocumentation
{
public:

View File

@ -1,8 +1,12 @@
// argnames.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Standard names for retrieving values when working with \p NameValuePairs
#ifndef CRYPTOPP_ARGNAMES_H
#define CRYPTOPP_ARGNAMES_H
#include "cryptlib.h"
#include "integer.h"
NAMESPACE_BEGIN(CryptoPP)
@ -74,6 +78,8 @@ CRYPTOPP_DEFINE_NAME_STRING(MaxLineLength) //< int
CRYPTOPP_DEFINE_NAME_STRING(DigestSize) //!< int, in bytes
CRYPTOPP_DEFINE_NAME_STRING(L1KeyLength) //!< int, in bytes
CRYPTOPP_DEFINE_NAME_STRING(TableSize) //!< int, in bytes
CRYPTOPP_DEFINE_NAME_STRING(DerivedKey) //< ByteArrayParameter, key derivation, derived key
CRYPTOPP_DEFINE_NAME_STRING(DerivedLength) //< int, key derivation, derived key length in bytes
DOCUMENTED_NAMESPACE_END

18
asn.cpp
View File

@ -1,16 +1,17 @@
// asn.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
#ifndef CRYPTOPP_IMPORTS
#include "asn.h"
#include "trap.h"
#include <iomanip>
#include <time.h>
NAMESPACE_BEGIN(CryptoPP)
USING_NAMESPACE(std)
/// DER Length
size_t DERLengthEncode(BufferedTransformation &bt, lword length)
@ -74,9 +75,7 @@ bool BERLengthDecode(BufferedTransformation &bt, lword &length, bool &definiteLe
bool BERLengthDecode(BufferedTransformation &bt, size_t &length)
{
// Initialize to silence warning from diagnostic tools
lword lw = 0;
bool definiteLength;
if (!BERLengthDecode(bt, lw, definiteLength))
BERDecodeError();
@ -245,7 +244,7 @@ size_t OID::DecodeValue(BufferedTransformation &bt, word32 &v)
void OID::DEREncode(BufferedTransformation &bt) const
{
CRYPTOPP_ASSERT(m_values.size() >= 2);
assert(m_values.size() >= 2);
ByteQueue temp;
temp.Put(byte(m_values[0] * 40 + m_values[1]));
for (size_t i=2; i<m_values.size(); i++)
@ -351,7 +350,8 @@ void EncodedObjectFilter::Put(const byte *inString, size_t length)
if (m_lengthRemaining == 0)
m_state = IDENTIFIER;
case TAIL: case ALL_DONE: ;;
case TAIL: // silence warnings
case ALL_DONE:
default: ;;
}
@ -405,13 +405,14 @@ void BERGeneralDecoder::Init(byte asnTag)
BERGeneralDecoder::~BERGeneralDecoder()
{
try // avoid throwing in desstructor
try // avoid throwing in constructor
{
if (!m_finished)
MessageEnd();
}
catch (const Exception&)
{
assert(0);
}
}
@ -489,6 +490,8 @@ DERGeneralEncoder::DERGeneralEncoder(BufferedTransformation &outQueue, byte asnT
{
}
// TODO: GCC (and likely other compilers) identify this as a copy constructor; and not a constructor.
// We have to wait until Crypto++ 6.0 to fix it becuase the signature change breaks versioning.
DERGeneralEncoder::DERGeneralEncoder(DERGeneralEncoder &outQueue, byte asnTag)
: ByteQueue(), m_outQueue(outQueue), m_finished(false), m_asnTag(asnTag)
{
@ -496,13 +499,14 @@ DERGeneralEncoder::DERGeneralEncoder(DERGeneralEncoder &outQueue, byte asnTag)
DERGeneralEncoder::~DERGeneralEncoder()
{
try // avoid throwing in destructor
try // avoid throwing in constructor
{
if (!m_finished)
MessageEnd();
}
catch (const Exception&)
{
assert(0);
}
}

30
asn.h
View File

@ -1,10 +1,17 @@
// asn.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Classes and functions for working with ANS.1 objects
#ifndef CRYPTOPP_ASN_H
#define CRYPTOPP_ASN_H
#include "cryptlib.h"
#include "filters.h"
#include "smartptr.h"
#include "stdcpp.h"
#include "queue.h"
#include "trap.h"
#include <vector>
#include "misc.h"
NAMESPACE_BEGIN(CryptoPP)
@ -134,7 +141,7 @@ public:
~BERGeneralDecoder();
bool IsDefiniteLength() const {return m_definiteLength;}
lword RemainingLength() const {CRYPTOPP_ASSERT(m_definiteLength); return m_length;}
lword RemainingLength() const {assert(m_definiteLength); return m_length;}
bool EndReached() const;
byte PeekByte() const;
void CheckByte(byte b);
@ -152,16 +159,27 @@ protected:
private:
void Init(byte asnTag);
void StoreInitialize(const NameValuePairs &parameters) {CRYPTOPP_ASSERT(false);}
void StoreInitialize(const NameValuePairs &parameters)
{CRYPTOPP_UNUSED(parameters); assert(false);}
lword ReduceLength(lword delta);
};
// GCC (and likely other compilers) identify the explicit DERGeneralEncoder as a copy constructor;
// and not a constructor. We had to remove the default asnTag value to point the compiler in the
// proper direction. We did not break the library or versioning based on the output of
// `nm --demangle libcryptopp.a | grep DERGeneralEncoder::DERGeneralEncoder | grep -v " U "`.
//! DER General Encoder
class CRYPTOPP_DLL DERGeneralEncoder : public ByteQueue
{
public:
#if defined(CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562)
explicit DERGeneralEncoder(BufferedTransformation &outQueue, byte asnTag = SEQUENCE | CONSTRUCTED);
explicit DERGeneralEncoder(DERGeneralEncoder &outQueue, byte asnTag = SEQUENCE | CONSTRUCTED);
#else
explicit DERGeneralEncoder(BufferedTransformation &outQueue, byte asnTag /*= SEQUENCE | CONSTRUCTED*/);
explicit DERGeneralEncoder(DERGeneralEncoder &outQueue, byte asnTag /*= SEQUENCE | CONSTRUCTED*/);
#endif
~DERGeneralEncoder();
// call this to denote end of sequence
@ -321,11 +339,9 @@ size_t DEREncodeUnsigned(BufferedTransformation &out, T w, byte asnTag = INTEGER
}
//! BER Decode Unsigned
// VC60 workaround: std::numeric_limits<T>::max conflicts with MFC max macro
// CW41 workaround: std::numeric_limits<T>::max causes a template error
template <class T>
void BERDecodeUnsigned(BufferedTransformation &in, T &w, byte asnTag = INTEGER,
T minValue = 0, T maxValue = 0xffffffff)
T minValue = 0, T maxValue = ((std::numeric_limits<T>::max)()))
{
byte b;
if (!in.Get(b) || b != asnTag)

View File

@ -5,7 +5,6 @@
#ifndef CRYPTOPP_IMPORTS
#include "authenc.h"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
@ -98,7 +97,7 @@ void AuthenticatedSymmetricCipherBase::Update(const byte *input, size_t length)
m_totalFooterLength += length;
break;
default:
CRYPTOPP_ASSERT(false);
assert(false);
}
}
@ -130,7 +129,7 @@ reswitch:
AuthenticateData(outString, length);
break;
default:
CRYPTOPP_ASSERT(false);
assert(false);
}
}
@ -170,7 +169,7 @@ void AuthenticatedSymmetricCipherBase::TruncatedFinal(byte *mac, size_t macSize)
break;
default:
CRYPTOPP_ASSERT(false);
assert(false);
}
m_state = State_KeySet;

View File

@ -1,13 +1,18 @@
// authenc.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Base classes for working with authenticated encryption modes of encryption
#ifndef CRYPTOPP_AUTHENC_H
#define CRYPTOPP_AUTHENC_H
#include "cryptlib.h"
#include "secblock.h"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
//! .
//! \class AuthenticatedSymmetricCipherBase
//! \brief
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipherBase : public AuthenticatedSymmetricCipher
{
public:
@ -15,7 +20,7 @@ public:
bool IsRandomAccess() const {return false;}
bool IsSelfInverting() const {return true;}
void UncheckedSetKey(const byte *,unsigned int,const CryptoPP::NameValuePairs &) {CRYPTOPP_ASSERT(false);}
void UncheckedSetKey(const byte *,unsigned int,const CryptoPP::NameValuePairs &) {assert(false);}
void SetKey(const byte *userKey, size_t keylength, const NameValuePairs &params);
void Restart() {if (m_state > State_KeySet) m_state = State_KeySet;}

View File

@ -1,26 +1,36 @@
// base32.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Class files for the Base32 encoder and decoder
#ifndef CRYPTOPP_BASE32_H
#define CRYPTOPP_BASE32_H
#include "cryptlib.h"
#include "basecode.h"
NAMESPACE_BEGIN(CryptoPP)
//! Converts given data to base 32, the default code is based on draft-ietf-idn-dude-02.txt
/*! To specify alternative code, call Initialize() with EncodingLookupArray parameter. */
//! \class Base32Encoder
//! \brief Base32 encodes data
//! \details Converts data to base32. The default code is based on draft-ietf-idn-dude-02.txt.
//! \details To specify alternative alpahabet or code, call Initialize() with EncodingLookupArray parameter.
class Base32Encoder : public SimpleProxyFilter
{
public:
Base32Encoder(BufferedTransformation *attachment = NULL, bool uppercase = true, int outputGroupSize = 0, const std::string &separator = ":", const std::string &terminator = "")
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
{
IsolatedInitialize(MakeParameters(Name::Uppercase(), uppercase)(Name::GroupSize(), outputGroupSize)(Name::Separator(), ConstByteArrayParameter(separator)));
IsolatedInitialize(MakeParameters(Name::Uppercase(), uppercase)(Name::GroupSize(), outputGroupSize)(Name::Separator(), ConstByteArrayParameter(separator))(Name::Terminator(), ConstByteArrayParameter(terminator)));
}
void IsolatedInitialize(const NameValuePairs &parameters);
};
//! Decode base 32 data back to bytes, the default code is based on draft-ietf-idn-dude-02.txt
/*! To specify alternative code, call Initialize() with DecodingLookupArray parameter. */
//! \class Base32Decoder
//! \brief Base32 decodes data
//! \details Decode base32 data. The default code is based on draft-ietf-idn-dude-02.txt
//! \details To specify alternative alpahabet or code, call Initialize() with EncodingLookupArray parameter.
class Base32Decoder : public BaseN_Decoder
{
public:

View File

@ -7,10 +7,10 @@ NAMESPACE_BEGIN(CryptoPP)
// Base64
static const byte s_vec1[] =
static const byte s_stdVec[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Base64URL
static const byte s_vec2[] =
static const byte s_urlVec[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
static const byte s_padding = '=';
@ -23,7 +23,7 @@ void Base64Encoder::IsolatedInitialize(const NameValuePairs &parameters)
m_filter->Initialize(CombinedNameValuePairs(
parameters,
MakeParameters(Name::EncodingLookupArray(), &s_vec1[0], false)
MakeParameters(Name::EncodingLookupArray(), &s_stdVec[0], false)
(Name::PaddingByte(), s_padding)
(Name::GroupSize(), insertLineBreaks ? maxLineLength : 0)
(Name::Separator(), ConstByteArrayParameter(lineBreak))
@ -40,7 +40,7 @@ void Base64URLEncoder::IsolatedInitialize(const NameValuePairs &parameters)
m_filter->Initialize(CombinedNameValuePairs(
parameters,
MakeParameters(Name::EncodingLookupArray(), &s_vec2[0], false)
MakeParameters(Name::EncodingLookupArray(), &s_urlVec[0], false)
(Name::PaddingByte(), s_padding)
(Name::GroupSize(), insertLineBreaks ? maxLineLength : 0)
(Name::Separator(), ConstByteArrayParameter(lineBreak))
@ -55,7 +55,7 @@ const int *Base64Decoder::GetDecodingLookupArray()
if (!s_initialized)
{
InitializeDecodingLookupArray(s_array, s_vec1, 64, false);
InitializeDecodingLookupArray(s_array, s_stdVec, 64, false);
s_initialized = true;
}
return s_array;
@ -68,7 +68,7 @@ const int *Base64URLDecoder::GetDecodingLookupArray()
if (!s_initialized)
{
InitializeDecodingLookupArray(s_array, s_vec2, 64, false);
InitializeDecodingLookupArray(s_array, s_urlVec, 64, false);
s_initialized = true;
}
return s_array;

View File

@ -1,12 +1,20 @@
// .h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Class files for the Base64Encoder, Base64Decoder, Base64URLEncoder and Base64URLDecoder
#ifndef CRYPTOPP_BASE64_H
#define CRYPTOPP_BASE64_H
#include "cryptlib.h"
#include "basecode.h"
NAMESPACE_BEGIN(CryptoPP)
//! Base64 Encoder Class
// https://tools.ietf.org/html/rfc4648#section-4
//! \class Base64Encoder
//! \brief Base64 encodes data
//! \details Base64 encodes data per RFC 4648 (http://tools.ietf.org/html/rfc4648#section-4)
//! \details To specify alternative alpahabet or code, call Initialize() with EncodingLookupArray parameter.
class Base64Encoder : public SimpleProxyFilter
{
public:
@ -19,22 +27,27 @@ public:
void IsolatedInitialize(const NameValuePairs &parameters);
};
//! Base64 Decoder Class
// https://tools.ietf.org/html/rfc4648#section-4
//! \class Base64Decoder
//! \brief Base64 decodes data
//! \details Base64 decodes data per RFC 4648 (http://tools.ietf.org/html/rfc4648#section-4)
//! \details To specify alternative alpahabet or code, call Initialize() with EncodingLookupArray parameter.
class Base64Decoder : public BaseN_Decoder
{
public:
Base64Decoder(BufferedTransformation *attachment = NULL)
: BaseN_Decoder(GetDecodingLookupArray(), 6, attachment) {}
void IsolatedInitialize(const NameValuePairs &parameters) {}
void IsolatedInitialize(const NameValuePairs &parameters)
{CRYPTOPP_UNUSED(parameters);}
private:
static const int * CRYPTOPP_API GetDecodingLookupArray();
};
//! Base64 URL Encoder Class
// https://tools.ietf.org/html/rfc4648#section-5
//! \class Base64URLEncoder
//! \brief Base64 encodes data using a web safe alphabet
//! \details Base64 encodes data using a web safe alphabet per RFC 4648 (http://tools.ietf.org/html/rfc4648#section-5)
//! \details To specify alternative alpahabet or code, call Initialize() with EncodingLookupArray parameter.
class Base64URLEncoder : public SimpleProxyFilter
{
public:
@ -47,14 +60,18 @@ public:
void IsolatedInitialize(const NameValuePairs &parameters);
};
//! Base64 URL Decoder Class
//! \class Base64URLDecoder
//! \brief Base64 decodes data using a web safe alphabet
//! \details Base64 decodes data using a web safe alphabet per RFC 4648 (http://tools.ietf.org/html/rfc4648#section-5)
//! \details To specify alternative alpahabet or code, call Initialize() with EncodingLookupArray parameter.
class Base64URLDecoder : public BaseN_Decoder
{
public:
Base64URLDecoder(BufferedTransformation *attachment = NULL)
: BaseN_Decoder(GetDecodingLookupArray(), 6, attachment) {}
void IsolatedInitialize(const NameValuePairs &parameters) {}
void IsolatedInitialize(const NameValuePairs &parameters)
{CRYPTOPP_UNUSED(parameters);}
private:
static const int * CRYPTOPP_API GetDecodingLookupArray();

View File

@ -1,19 +1,22 @@
// basecode.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4100)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic ignored "-Wunused-value"
#endif
#ifndef CRYPTOPP_IMPORTS
#include "basecode.h"
#include "fltrimpl.h"
#include "trap.h"
#include <ctype.h>
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic ignored "-Wunused-value"
# pragma GCC diagnostic ignored "-Wunused-variable"
#endif
NAMESPACE_BEGIN(CryptoPP)
void BaseN_Encoder::IsolatedInitialize(const NameValuePairs &parameters)
@ -54,7 +57,7 @@ size_t BaseN_Encoder::Put2(const byte *begin, size_t length, int messageEnd, boo
unsigned int b = begin[m_inputPosition++], bitsLeftInSource = 8;
while (true)
{
CRYPTOPP_ASSERT(m_bitPos < m_bitsPerChar);
assert(m_bitPos < m_bitsPerChar);
unsigned int bitsLeftInTarget = m_bitsPerChar-m_bitPos;
m_outBuf[m_bytePos] |= b >> (8-bitsLeftInTarget);
if (bitsLeftInSource >= bitsLeftInTarget)
@ -75,13 +78,13 @@ size_t BaseN_Encoder::Put2(const byte *begin, size_t length, int messageEnd, boo
}
}
CRYPTOPP_ASSERT(m_bytePos <= m_outputBlockSize);
assert(m_bytePos <= m_outputBlockSize);
if (m_bytePos == m_outputBlockSize)
{
int i;
for (i=0; i<m_bytePos; i++)
{
CRYPTOPP_ASSERT(m_outBuf[i] < (1 << m_bitsPerChar));
assert(m_outBuf[i] < (1 << m_bitsPerChar));
m_outBuf[i] = m_alphabet[m_outBuf[i]];
}
FILTER_OUTPUT(1, m_outBuf, m_outputBlockSize, 0);
@ -180,14 +183,14 @@ void BaseN_Decoder::InitializeDecodingLookupArray(int *lookup, const byte *alpha
{
if (caseInsensitive && isalpha(alphabet[i]))
{
CRYPTOPP_ASSERT(lookup[toupper(alphabet[i])] == -1);
assert(lookup[toupper(alphabet[i])] == -1);
lookup[toupper(alphabet[i])] = i;
CRYPTOPP_ASSERT(lookup[tolower(alphabet[i])] == -1);
assert(lookup[tolower(alphabet[i])] == -1);
lookup[tolower(alphabet[i])] = i;
}
else
{
CRYPTOPP_ASSERT(lookup[alphabet[i]] == -1);
assert(lookup[alphabet[i]] == -1);
lookup[alphabet[i]] = i;
}
}

View File

@ -1,18 +1,25 @@
// basecode.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Base class files for working with encoders and decoders.
#ifndef CRYPTOPP_BASECODE_H
#define CRYPTOPP_BASECODE_H
#include "cryptlib.h"
#include "filters.h"
#include "algparam.h"
#include "argnames.h"
NAMESPACE_BEGIN(CryptoPP)
//! base n encoder, where n is a power of 2
//! \class BaseN_Encoder
//! \details base n encoder, where n is a power of 2
class CRYPTOPP_DLL BaseN_Encoder : public Unflushable<Filter>
{
public:
BaseN_Encoder(BufferedTransformation *attachment=NULL)
: m_alphabet(NULL) {Detach(attachment);}
{Detach(attachment);}
BaseN_Encoder(const byte *alphabet, int log2base, BufferedTransformation *attachment=NULL, int padding=-1)
{
@ -33,12 +40,13 @@ private:
SecByteBlock m_outBuf;
};
//! base n decoder, where n is a power of 2
//! \class BaseN_Decoder
//! \details base n encoder, where n is a power of 2
class CRYPTOPP_DLL BaseN_Decoder : public Unflushable<Filter>
{
public:
BaseN_Decoder(BufferedTransformation *attachment=NULL)
: m_lookup(NULL) {Detach(attachment);}
{Detach(attachment);}
BaseN_Decoder(const int *lookup, int log2base, BufferedTransformation *attachment=NULL)
{
@ -53,7 +61,7 @@ public:
private:
const int *m_lookup;
int /*m_padding,*/ m_bitsPerChar, m_outputBlockSize;
int m_padding, m_bitsPerChar, m_outputBlockSize;
int m_bytePos, m_bitPos;
SecByteBlock m_outBuf;
};

107
bench.cpp
View File

@ -1,17 +1,17 @@
// bench.cpp - written and placed in the public domain by Wei Dai
#define _CRT_SECURE_NO_DEPRECATE
#include "cryptlib.h"
#include "bench.h"
#include "validate.h"
#include "stdcpp.h"
#include "smartptr.h"
#include "aes.h"
#include "blumshub.h"
#include "files.h"
#include "filters.h"
#include "hex.h"
#include "modes.h"
#include "factory.h"
#include "smartptr.h"
#include "cpu.h"
#include <time.h>
@ -19,7 +19,13 @@
#include <iostream>
#include <iomanip>
// These are noisy enoguh due to test.cpp. Turn them off here.
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)
#ifdef CLOCKS_PER_SEC
const double CLOCK_TICKS_PER_SECOND = (double)CLOCKS_PER_SEC;
@ -32,40 +38,40 @@ const double CLOCK_TICKS_PER_SECOND = 1000000.0;
double logtotal = 0, g_allocatedTime, g_hertz;
unsigned int logcount = 0;
static const byte *const key=(byte *)"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
static const byte defaultKey[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
void OutputResultBytes(const char *name, double length, double timeTaken)
{
double mbs = length / timeTaken / (1024*1024);
std::cout << "\n<TR><TH>" << name;
// std::cout << "<TD>" << std::setprecision(3) << length / (1024*1024);
std::cout << std::setiosflags(std::ios::fixed);
// std::cout << "<TD>" << std::setprecision(3) << timeTaken;
std::cout << "<TD>" << std::setprecision(0) << std::setiosflags(std::ios::fixed) << mbs;
cout << "\n<TR><TH>" << name;
// cout << "<TD>" << setprecision(3) << length / (1024*1024);
cout << setiosflags(ios::fixed);
// cout << "<TD>" << setprecision(3) << timeTaken;
cout << "<TD>" << setprecision(0) << setiosflags(ios::fixed) << mbs;
if (g_hertz)
std::cout << "<TD>" << std::setprecision(1) << std::setiosflags(std::ios::fixed) << timeTaken * g_hertz / length;
std::cout << std::setiosflags(std::ios::fixed);
cout << "<TD>" << setprecision(1) << setiosflags(ios::fixed) << timeTaken * g_hertz / length;
cout << resetiosflags(ios::fixed);
logtotal += log(mbs);
logcount++;
}
void OutputResultKeying(double iterations, double timeTaken)
{
std::cout << "<TD>" << std::setprecision(3) << std::setiosflags(std::ios::fixed) << (1000*1000*timeTaken/iterations);
cout << "<TD>" << setprecision(3) << setiosflags(ios::fixed) << (1000*1000*timeTaken/iterations);
if (g_hertz)
std::cout << "<TD>" << std::setprecision(0) << std::setiosflags(std::ios::fixed) << timeTaken * g_hertz / iterations;
cout << "<TD>" << setprecision(0) << setiosflags(ios::fixed) << timeTaken * g_hertz / iterations;
}
void OutputResultOperations(const char *name, const char *operation, bool pc, unsigned long iterations, double timeTaken)
{
std::cout << "\n<TR><TH>" << name << " " << operation << (pc ? " with precomputation" : "");
// std::cout << "<TD>" << iterations;
// std::cout << std::setiosflags(std::ios::fixed);
// std::cout << "<TD>" << std::setprecision(3) << timeTaken;
std::cout << "<TD>" << std::setprecision(2) << std::setiosflags(std::ios::fixed) << (1000*timeTaken/iterations);
cout << "\n<TR><TH>" << name << " " << operation << (pc ? " with precomputation" : "");
// cout << "<TD>" << iterations;
// cout << setiosflags(ios::fixed);
// cout << "<TD>" << setprecision(3) << timeTaken;
cout << "<TD>" << setprecision(2) << setiosflags(ios::fixed) << (1000*timeTaken/iterations);
if (g_hertz)
std::cout << "<TD>" << std::setprecision(2) << std::setiosflags(std::ios::fixed) << timeTaken * g_hertz / iterations / 1000000;
std::cout << std::setiosflags(std::ios::fixed);
cout << "<TD>" << setprecision(2) << setiosflags(ios::fixed) << timeTaken * g_hertz / iterations / 1000000;
cout << resetiosflags(ios::fixed);
logtotal += log(iterations/timeTaken);
logcount++;
@ -173,7 +179,7 @@ void BenchMarkKeying(SimpleKeyingInterface &c, size_t keyLength, const NameValue
do
{
for (unsigned int i=0; i<1024; i++)
c.SetKey(key, keyLength, params);
c.SetKey(defaultKey, keyLength, params);
timeTaken = double(clock() - start) / CLOCK_TICKS_PER_SECOND;
iterations += 1024;
}
@ -187,35 +193,41 @@ void BenchMarkKeying(SimpleKeyingInterface &c, size_t keyLength, const NameValue
template <class T_FactoryOutput, class T_Interface>
void BenchMarkByName2(const char *factoryName, size_t keyLength = 0, const char *displayName=NULL, const NameValuePairs &params = g_nullNameValuePairs, T_FactoryOutput *x=NULL, T_Interface *y=NULL)
{
std::string name = factoryName;
CRYPTOPP_UNUSED(x), CRYPTOPP_UNUSED(y), CRYPTOPP_UNUSED(params);
std::string name(factoryName ? factoryName : "");
if (displayName)
name = displayName;
else if (keyLength)
name += " (" + IntToString(keyLength * 8) + "-bit key)";
auto_ptr<T_FactoryOutput> obj(ObjectFactoryRegistry<T_FactoryOutput>::Registry().CreateObject(factoryName));
member_ptr<T_FactoryOutput> obj(ObjectFactoryRegistry<T_FactoryOutput>::Registry().CreateObject(factoryName));
if (!keyLength)
keyLength = obj->DefaultKeyLength();
obj->SetKey(key, keyLength, CombinedNameValuePairs(params, MakeParameters(Name::IV(), ConstByteArrayParameter(key, obj->IVSize()), false)));
obj->SetKey(defaultKey, keyLength, CombinedNameValuePairs(params, MakeParameters(Name::IV(), ConstByteArrayParameter(defaultKey, obj->IVSize()), false)));
BenchMark(name.c_str(), *static_cast<T_Interface *>(obj.get()), g_allocatedTime);
BenchMarkKeying(*obj, keyLength, CombinedNameValuePairs(params, MakeParameters(Name::IV(), ConstByteArrayParameter(key, obj->IVSize()), false)));
BenchMarkKeying(*obj, keyLength, CombinedNameValuePairs(params, MakeParameters(Name::IV(), ConstByteArrayParameter(defaultKey, obj->IVSize()), false)));
}
//VC60 workaround: compiler bug triggered without the extra dummy parameters
template <class T_FactoryOutput>
void BenchMarkByName(const char *factoryName, size_t keyLength = 0, const char *displayName=NULL, const NameValuePairs &params = g_nullNameValuePairs, T_FactoryOutput *x=NULL)
{
CRYPTOPP_UNUSED(x), CRYPTOPP_UNUSED(params);
BenchMarkByName2<T_FactoryOutput, T_FactoryOutput>(factoryName, keyLength, displayName, params, x, x);
}
template <class T>
void BenchMarkByNameKeyLess(const char *factoryName, const char *displayName=NULL, const NameValuePairs &params = g_nullNameValuePairs, T *x=NULL)
{
CRYPTOPP_UNUSED(x), CRYPTOPP_UNUSED(params);
std::string name = factoryName;
if (displayName)
name = displayName;
auto_ptr<T> obj(ObjectFactoryRegistry<T>::Registry().CreateObject(factoryName));
member_ptr<T> obj(ObjectFactoryRegistry<T>::Registry().CreateObject(factoryName));
BenchMark(name.c_str(), *obj, g_allocatedTime);
}
@ -232,18 +244,18 @@ void BenchmarkAll(double t, double hertz)
{
cpb = "<TH>Cycles Per Byte";
cpk = "<TH>Cycles to<br>Setup Key and IV";
std::cout << "CPU frequency of the test platform is " << g_hertz << " Hz.\n";
cout << "CPU frequency of the test platform is " << g_hertz << " Hz.\n";
}
else
{
cpb = cpk = "";
std::cout << "CPU frequency of the test platform was not provided.\n";
cout << "CPU frequency of the test platform was not provided.\n";
}
std::cout << "<TABLE border=1><COLGROUP><COL align=left><COL align=right><COL align=right><COL align=right><COL align=right>" << std::endl;
std::cout << "<THEAD><TR><TH>Algorithm<TH>MiB/Second" << cpb << "<TH>Microseconds to<br>Setup Key and IV" << cpk << std::endl;
cout << "<TABLE border=1><COLGROUP><COL align=left><COL align=right><COL align=right><COL align=right><COL align=right>" << endl;
cout << "<THEAD><TR><TH>Algorithm<TH>MiB/Second" << cpb << "<TH>Microseconds to<br>Setup Key and IV" << cpk << endl;
std::cout << "\n<TBODY style=\"background: yellow\">";
cout << "\n<TBODY style=\"background: yellow\">";
#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE
if (HasCLMUL())
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM");
@ -256,7 +268,7 @@ void BenchmarkAll(double t, double hertz)
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/CCM");
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/EAX");
std::cout << "\n<TBODY style=\"background: white\">";
cout << "\n<TBODY style=\"background: white\">";
#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE
if (HasCLMUL())
BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES)");
@ -273,7 +285,7 @@ void BenchmarkAll(double t, double hertz)
BenchMarkByName<MessageAuthenticationCode>("CMAC(AES)");
BenchMarkByName<MessageAuthenticationCode>("DMAC(AES)");
std::cout << "\n<TBODY style=\"background: yellow\">";
cout << "\n<TBODY style=\"background: yellow\">";
BenchMarkByNameKeyLess<HashTransformation>("CRC32");
BenchMarkByNameKeyLess<HashTransformation>("Adler32");
BenchMarkByNameKeyLess<HashTransformation>("MD5");
@ -291,7 +303,7 @@ void BenchmarkAll(double t, double hertz)
BenchMarkByNameKeyLess<HashTransformation>("RIPEMD-128");
BenchMarkByNameKeyLess<HashTransformation>("RIPEMD-256");
std::cout << "\n<TBODY style=\"background: white\">";
cout << "\n<TBODY style=\"background: white\">";
BenchMarkByName<SymmetricCipher>("Panama-LE");
BenchMarkByName<SymmetricCipher>("Panama-BE");
BenchMarkByName<SymmetricCipher>("Salsa20");
@ -302,7 +314,7 @@ void BenchmarkAll(double t, double hertz)
BenchMarkByName<SymmetricCipher>("SEAL-3.0-LE");
BenchMarkByName<SymmetricCipher>("WAKE-OFB-LE");
std::cout << "\n<TBODY style=\"background: yellow\">";
cout << "\n<TBODY style=\"background: yellow\">";
BenchMarkByName<SymmetricCipher>("AES/CTR", 16);
BenchMarkByName<SymmetricCipher>("AES/CTR", 24);
BenchMarkByName<SymmetricCipher>("AES/CTR", 32);
@ -332,13 +344,28 @@ void BenchmarkAll(double t, double hertz)
BenchMarkByName<SymmetricCipher>("CAST-128/CTR");
BenchMarkByName<SymmetricCipher>("SKIPJACK/CTR");
BenchMarkByName<SymmetricCipher>("SEED/CTR", 0, "SEED/CTR (1/2 K table)");
std::cout << "</TABLE>" << std::endl;
cout << "</TABLE>" << endl;
BenchmarkAll2(t, hertz);
std::cout << "Throughput Geometric Average: " << std::setiosflags(std::ios::fixed) << exp(logtotal/logcount) << std::endl;
cout << "Throughput Geometric Average: " << setiosflags(ios::fixed) << exp(logtotal/logcount) << endl;
time_t endTime = time(NULL);
std::cout << "\nTest ended at " << asctime(localtime(&endTime));
// Safer functions on Windows for C&A, https://github.com/weidai11/cryptopp/issues/55
#if defined(CRYPTOPP_MSC_VERSION)
tm localTime = {};
char timeBuf[64];
errno_t err;
const time_t endTime = time(NULL);
err = localtime_s(&localTime, &endTime);
assert(err == 0);
err = asctime_s(timeBuf, sizeof(timeBuf), &localTime);
assert(err == 0);
cout << "\nTest ended at " << timeBuf;
#else
const time_t endTime = time(NULL);
cout << "\nTest ended at " << asctime(localtime(&endTime));
#endif
#endif
}

View File

@ -1,10 +1,15 @@
// bench2.cpp - written and placed in the public domain by Wei Dai
#include "cryptlib.h"
#include "pubkey.h"
#include "gfpcrypt.h"
#include "eccrypto.h"
#include "bench.h"
#include "validate.h"
#include "files.h"
#include "hex.h"
#include "files.h"
#include "filters.h"
#include "hex.h"
#include "rsa.h"
#include "nr.h"
#include "dsa.h"
@ -27,7 +32,13 @@
#include <iostream>
#include <iomanip>
// These are noisy enoguh due to test.cpp. Turn them off here.
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)
void OutputResultOperations(const char *name, const char *operation, bool pc, unsigned long iterations, double timeTaken);
@ -198,6 +209,8 @@ void BenchMarkAgreement(const char *name, AuthenticatedKeyAgreementDomain &d, do
template <class SCHEME>
void BenchMarkCrypto(const char *filename, const char *name, double timeTotal, SCHEME *x=NULL)
{
CRYPTOPP_UNUSED(x);
FileSource f(filename, true, new HexDecoder());
typename SCHEME::Decryptor priv(f);
typename SCHEME::Encryptor pub(priv);
@ -209,6 +222,8 @@ void BenchMarkCrypto(const char *filename, const char *name, double timeTotal, S
template <class SCHEME>
void BenchMarkSignature(const char *filename, const char *name, double timeTotal, SCHEME *x=NULL)
{
CRYPTOPP_UNUSED(x);
FileSource f(filename, true, new HexDecoder());
typename SCHEME::Signer priv(f);
typename SCHEME::Verifier pub(priv);
@ -220,6 +235,8 @@ void BenchMarkSignature(const char *filename, const char *name, double timeTotal
template <class D>
void BenchMarkKeyAgreement(const char *filename, const char *name, double timeTotal, D *x=NULL)
{
CRYPTOPP_UNUSED(x);
FileSource f(filename, true, new HexDecoder());
D d(f);
BenchMarkKeyGen(name, d, timeTotal);
@ -232,22 +249,22 @@ void BenchmarkAll2(double t, double hertz)
{
g_hertz = hertz;
std::cout << "<TABLE border=1><COLGROUP><COL align=left><COL align=right><COL align=right>" << std::endl;
std::cout << "<THEAD><TR><TH>Operation<TH>Milliseconds/Operation" << (g_hertz ? "<TH>Megacycles/Operation" : "") << std::endl;
cout << "<TABLE border=1><COLGROUP><COL align=left><COL align=right><COL align=right>" << endl;
cout << "<THEAD><TR><TH>Operation<TH>Milliseconds/Operation" << (g_hertz ? "<TH>Megacycles/Operation" : "") << endl;
std::cout << "\n<TBODY style=\"background: yellow\">";
cout << "\n<TBODY style=\"background: yellow\">";
BenchMarkCrypto<RSAES<OAEP<SHA> > >("TestData/rsa1024.dat", "RSA 1024", t);
BenchMarkCrypto<LUCES<OAEP<SHA> > >("TestData/luc1024.dat", "LUC 1024", t);
BenchMarkCrypto<DLIES<> >("TestData/dlie1024.dat", "DLIES 1024", t);
BenchMarkCrypto<LUC_IES<> >("TestData/lucc512.dat", "LUCELG 512", t);
std::cout << "\n<TBODY style=\"background: white\">";
cout << "\n<TBODY style=\"background: white\">";
BenchMarkCrypto<RSAES<OAEP<SHA> > >("TestData/rsa2048.dat", "RSA 2048", t);
BenchMarkCrypto<LUCES<OAEP<SHA> > >("TestData/luc2048.dat", "LUC 2048", t);
BenchMarkCrypto<DLIES<> >("TestData/dlie2048.dat", "DLIES 2048", t);
BenchMarkCrypto<LUC_IES<> >("TestData/lucc1024.dat", "LUCELG 1024", t);
std::cout << "\n<TBODY style=\"background: yellow\">";
cout << "\n<TBODY style=\"background: yellow\">";
BenchMarkSignature<RSASS<PSSR, SHA> >("TestData/rsa1024.dat", "RSA 1024", t);
BenchMarkSignature<RWSS<PSSR, SHA> >("TestData/rw1024.dat", "RW 1024", t);
BenchMarkSignature<LUCSS<PSSR, SHA> >("TestData/luc1024.dat", "LUC 1024", t);
@ -257,7 +274,7 @@ void BenchmarkAll2(double t, double hertz)
BenchMarkSignature<ESIGN<SHA> >("TestData/esig1023.dat", "ESIGN 1023", t);
BenchMarkSignature<ESIGN<SHA> >("TestData/esig1536.dat", "ESIGN 1536", t);
std::cout << "\n<TBODY style=\"background: white\">";
cout << "\n<TBODY style=\"background: white\">";
BenchMarkSignature<RSASS<PSSR, SHA> >("TestData/rsa2048.dat", "RSA 2048", t);
BenchMarkSignature<RWSS<PSSR, SHA> >("TestData/rw2048.dat", "RW 2048", t);
BenchMarkSignature<LUCSS<PSSR, SHA> >("TestData/luc2048.dat", "LUC 2048", t);
@ -265,7 +282,7 @@ void BenchmarkAll2(double t, double hertz)
BenchMarkSignature<LUC_HMP<SHA> >("TestData/lucs1024.dat", "LUC-HMP 1024", t);
BenchMarkSignature<ESIGN<SHA> >("TestData/esig2046.dat", "ESIGN 2046", t);
std::cout << "\n<TBODY style=\"background: yellow\">";
cout << "\n<TBODY style=\"background: yellow\">";
BenchMarkKeyAgreement<XTR_DH>("TestData/xtrdh171.dat", "XTR-DH 171", t);
BenchMarkKeyAgreement<XTR_DH>("TestData/xtrdh342.dat", "XTR-DH 342", t);
BenchMarkKeyAgreement<DH>("TestData/dh1024.dat", "DH 1024", t);
@ -275,7 +292,7 @@ void BenchmarkAll2(double t, double hertz)
BenchMarkKeyAgreement<MQV>("TestData/mqv1024.dat", "MQV 1024", t);
BenchMarkKeyAgreement<MQV>("TestData/mqv2048.dat", "MQV 2048", t);
std::cout << "\n<TBODY style=\"background: white\">";
cout << "\n<TBODY style=\"background: white\">";
{
ECIES<ECP>::Decryptor cpriv(GlobalRNG(), ASN1::secp256k1());
ECIES<ECP>::Encryptor cpub(cpriv);
@ -294,7 +311,7 @@ void BenchmarkAll2(double t, double hertz)
BenchMarkAgreement("ECMQVC over GF(p) 256", ecmqvc, t);
}
std::cout << "<TBODY style=\"background: yellow\">" << std::endl;
cout << "<TBODY style=\"background: yellow\">" << endl;
{
ECIES<EC2N>::Decryptor cpriv(GlobalRNG(), ASN1::sect233r1());
ECIES<EC2N>::Encryptor cpub(cpriv);
@ -312,5 +329,5 @@ void BenchmarkAll2(double t, double hertz)
BenchMarkKeyGen("ECMQVC over GF(2^n) 233", ecmqvc, t);
BenchMarkAgreement("ECMQVC over GF(2^n) 233", ecmqvc, t);
}
std::cout << "</TABLE>" << std::endl;
cout << "</TABLE>" << endl;
}

View File

@ -17,7 +17,7 @@ void Blowfish::Base::UncheckedSetKey(const byte *key_string, unsigned int keylen
memcpy(sbox, s_init, sizeof(s_init));
// Xor key string into encryption key vector
for (i=0 ; i<static_cast<unsigned int>(ROUNDS)+2 ; ++i)
for (i=0 ; i<ROUNDS+2 ; ++i)
{
data = 0 ;
for (k=0 ; k<4 ; ++k )
@ -27,7 +27,7 @@ void Blowfish::Base::UncheckedSetKey(const byte *key_string, unsigned int keylen
crypt_block(dspace, pbox);
for (i=0; i<static_cast<unsigned int>(ROUNDS); i+=2)
for (i=0; i<ROUNDS; i+=2)
crypt_block(pbox+i, pbox+i+2);
crypt_block(pbox+ROUNDS, sbox);
@ -36,7 +36,7 @@ void Blowfish::Base::UncheckedSetKey(const byte *key_string, unsigned int keylen
crypt_block(sbox+i, sbox+i+2);
if (!IsForwardTransformation())
for (i=0; i<(static_cast<unsigned int>(ROUNDS)+2)/2; i++)
for (i=0; i<(ROUNDS+2)/2; i++)
std::swap(pbox[i], pbox[ROUNDS+1-i]);
}

View File

@ -1,24 +1,32 @@
// blowfish.h - written and placed in the public domain by Wei Dai
//! \file
//! \brief Class files for the Blowfish algorithm
#ifndef CRYPTOPP_BLOWFISH_H
#define CRYPTOPP_BLOWFISH_H
/** \file */
#include "seckey.h"
#include "secblock.h"
NAMESPACE_BEGIN(CryptoPP)
//! _
//! \class Blowfish_Info
//! \brief The cipher's key, iv, block size and name information.
struct Blowfish_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 4, 56>, public FixedRounds<16>
{
static const char *StaticAlgorithmName() {return "Blowfish";}
};
//! <a href="http://www.weidai.com/scan-mirror/cs.html#Blowfish">Blowfish</a>
// <a href="http://www.weidai.com/scan-mirror/cs.html#Blowfish">Blowfish</a>
//! \class Blowfish
//! \brief Provides Blowfish encryption and decryption
class Blowfish : public Blowfish_Info, public BlockCipherDocumentation
{
//! \class Base
//! \brief Class specific implementation and overrides used to operate the cipher.
//! \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<Blowfish_Info>
{
public:

View File

@ -2,6 +2,7 @@
#include "pch.h"
#include "blumshub.h"
#include "integer.h"
NAMESPACE_BEGIN(CryptoPP)
@ -28,7 +29,7 @@ byte PublicBlumBlumShub::GenerateByte()
{
byte b=0;
for (int i=0; i<8; i++)
b = (b << 1) | PublicBlumBlumShub::GenerateBit();
b = byte((b << 1) | PublicBlumBlumShub::GenerateBit());
return b;
}

View File

@ -1,9 +1,9 @@
#ifndef CRYPTOPP_BLUMSHUB_H
#define CRYPTOPP_BLUMSHUB_H
#include "config.h"
#include "integer.h"
#include "cryptlib.h"
#include "modarith.h"
#include "integer.h"
NAMESPACE_BEGIN(CryptoPP)
@ -26,6 +26,9 @@ protected:
ModularArithmetic modn;
word maxBits, bitsLeft;
Integer current;
friend class BlumGoldwasserPublicKey;
friend class BlumGoldwasserPrivateKey;
};
//! BlumBlumShub with factorization of the modulus

View File

@ -10,6 +10,11 @@ See comments at top of rijndael.cpp for more details.
*/
#include "pch.h"
#include "config.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4456 6246)
#endif
#include "camellia.h"
#include "misc.h"

View File

@ -1,11 +1,10 @@
#ifndef CRYPTOPP_CAMELLIA_H
#define CRYPTOPP_CAMELLIA_H
#include "config.h"
/** \file
*/
#include "config.h"
#include "seckey.h"
#include "secblock.h"

View File

@ -4,7 +4,6 @@
#include "pch.h"
#include "cast.h"
#include "misc.h"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
@ -16,15 +15,15 @@ NAMESPACE_BEGIN(CryptoPP)
/* CAST uses three different round functions */
#define f1(l, r, km, kr) \
t = rotlMod(km + r, kr); \
t = rotlVariable(km + r, kr); \
l ^= ((S[0][U8a(t)] ^ S[1][U8b(t)]) - \
S[2][U8c(t)]) + S[3][U8d(t)];
#define f2(l, r, km, kr) \
t = rotlMod(km ^ r, kr); \
t = rotlVariable(km ^ r, kr); \
l ^= ((S[0][U8a(t)] - S[1][U8b(t)]) + \
S[2][U8c(t)]) ^ S[3][U8d(t)];
#define f3(l, r, km, kr) \
t = rotlMod(km - r, kr); \
t = rotlVariable(km - r, kr); \
l ^= ((S[0][U8a(t)] + S[1][U8b(t)]) ^ \
S[2][U8c(t)]) - S[3][U8d(t)];
@ -283,7 +282,7 @@ void CAST256::Base::UncheckedSetKey(const byte *userKey, unsigned int keylength,
int i1=8*j+i;
int i2=8*(11-j)+i;
CRYPTOPP_ASSERT(i1<i2);
assert(i1<i2);
std::swap(K[i1],K[i2]);
std::swap(K[i1+4],K[i2+4]);

View File

@ -5,7 +5,6 @@
#ifndef CRYPTOPP_IMPORTS
#include "ccm.h"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
@ -31,7 +30,7 @@ void CCM_Base::Resync(const byte *iv, size_t len)
BlockCipher &cipher = AccessBlockCipher();
m_L = REQUIRED_BLOCKSIZE-1-(int)len;
CRYPTOPP_ASSERT(m_L >= 2);
assert(m_L >= 2);
if (m_L > 8)
m_L = 8;
@ -49,7 +48,7 @@ void CCM_Base::Resync(const byte *iv, size_t len)
m_messageLength = 0;
}
void CCM_Base::UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
void CCM_Base::UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword /*footerLength*/)
{
if (m_state != State_IVSet)
throw BadState(AlgorithmName(), "SpecifyDataLengths", "or after State_IVSet");
@ -67,7 +66,7 @@ void CCM_Base::UncheckedSpecifyDataLengths(lword headerLength, lword messageLeng
if (headerLength>0)
{
CRYPTOPP_ASSERT(m_bufferedDataLength == 0);
assert(m_bufferedDataLength == 0);
if (headerLength < ((1<<16) - (1<<8)))
{

3
ccm.h
View File

@ -6,7 +6,6 @@
NAMESPACE_BEGIN(CryptoPP)
//! .
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CCM_Base : public AuthenticatedSymmetricCipherBase
{
public:
@ -72,7 +71,6 @@ protected:
CTR_Mode_ExternalCipher::Encryption m_ctr;
};
//! .
template <class T_BlockCipher, int T_DefaultDigestSize, bool T_IsEncryption>
class CCM_Final : public CCM_Base
{
@ -89,6 +87,7 @@ private:
};
/// <a href="http://www.cryptolounge.org/wiki/CCM">CCM</a>
//! \brief CCM mode of operation
template <class T_BlockCipher, int T_DefaultDigestSize = 16>
struct CCM : public AuthenticatedSymmetricCipherDocumentation
{

View File

@ -4,9 +4,11 @@
#ifndef CRYPTOPP_IMPORTS
#include "cryptlib.h"
#include "channels.h"
NAMESPACE_BEGIN(CryptoPP)
USING_NAMESPACE(std)
#if 0
void MessageSwitch::AddDefaultRoute(BufferedTransformation &destination, const std::string &channel)
@ -35,7 +37,7 @@ public:
MessageRouteIterator(MessageSwitch &ms, const std::string &channel)
: m_channel(channel)
{
std::pair<MapIterator, MapIterator> range = cs.m_routeMap.equal_range(channel);
pair<MapIterator, MapIterator> range = cs.m_routeMap.equal_range(channel);
if (range.first == range.second)
{
m_useDefault = true;
@ -95,7 +97,7 @@ void MessageSwitch::MessageSeriesEnd(int propagation=-1);
void ChannelRouteIterator::Reset(const std::string &channel)
{
m_channel = channel;
std::pair<MapIterator, MapIterator> range = m_cs.m_routeMap.equal_range(channel);
pair<MapIterator, MapIterator> range = m_cs.m_routeMap.equal_range(channel);
if (range.first == range.second)
{
m_useDefault = true;
@ -166,8 +168,9 @@ WasBlocked:
return 0;
}
void ChannelSwitch::IsolatedInitialize(const NameValuePairs &parameters/* =g_nullNameValuePairs */)
void ChannelSwitch::IsolatedInitialize(const NameValuePairs& parameters)
{
CRYPTOPP_UNUSED(parameters);
m_routeMap.clear();
m_defaultRoutes.clear();
m_blocked = false;
@ -200,6 +203,7 @@ bool ChannelSwitch::ChannelFlush(const std::string &channel, bool completeFlush,
bool ChannelSwitch::ChannelMessageSeriesEnd(const std::string &channel, int propagation, bool blocking)
{
CRYPTOPP_UNUSED(blocking);
if (m_blocked)
{
m_blocked = false;
@ -229,10 +233,10 @@ byte * ChannelSwitch::ChannelCreatePutSpace(const std::string &channel, size_t &
if (!m_it.End())
{
BufferedTransformation &target = m_it.Destination();
const std::string &channel = m_it.Channel();
const std::string &ch = m_it.Channel();
m_it.Next();
if (m_it.End()) // there is only one target channel
return target.ChannelCreatePutSpace(channel, size);
return target.ChannelCreatePutSpace(ch, size);
}
size = 0;
return NULL;
@ -293,7 +297,7 @@ void ChannelSwitch::AddRoute(const std::string &inChannel, BufferedTransformatio
void ChannelSwitch::RemoveRoute(const std::string &inChannel, BufferedTransformation &destination, const std::string &outChannel)
{
typedef ChannelSwitch::RouteMap::iterator MapIterator;
std::pair<MapIterator, MapIterator> range = m_routeMap.equal_range(inChannel);
pair<MapIterator, MapIterator> range = m_routeMap.equal_range(inChannel);
for (MapIterator it = range.first; it != range.second; ++it)
if (it->second.first == &destination && it->second.second == outChannel)

View File

@ -1,6 +1,7 @@
#ifndef CRYPTOPP_CHANNELS_H
#define CRYPTOPP_CHANNELS_H
#include "cryptlib.h"
#include "simple.h"
#include "smartptr.h"
#include <map>

View File

@ -5,7 +5,6 @@
#ifndef CRYPTOPP_IMPORTS
#include "cmac.h"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
@ -81,7 +80,7 @@ void CMAC_Base::Update(const byte *input, size_t length)
if (length > blockSize)
{
CRYPTOPP_ASSERT(m_counter == 0);
assert(m_counter == 0);
size_t leftOver = 1 + cipher.AdvancedProcessBlocks(m_reg, input, m_reg, length-1, BlockTransformation::BT_DontIncrementInOutPointers|BlockTransformation::BT_XorInput);
input += (length - leftOver);
length = leftOver;
@ -89,12 +88,12 @@ void CMAC_Base::Update(const byte *input, size_t length)
if (length > 0)
{
CRYPTOPP_ASSERT(m_counter + length <= blockSize);
assert(m_counter + length <= blockSize);
xorbuf(m_reg+m_counter, input, length);
m_counter += (unsigned int)length;
}
CRYPTOPP_ASSERT(m_counter > 0);
assert(m_counter > 0);
}
void CMAC_Base::TruncatedFinal(byte *mac, size_t size)

334
config.h
View File

@ -4,7 +4,7 @@
// ***************** Important Settings ********************
// define this if running on a big-endian CPU
#if !defined(IS_LITTLE_ENDIAN) && (defined(__BIG_ENDIAN__) || defined(__sparc) || defined(__sparc__) || defined(__hppa__) || defined(__MIPSEB__) || defined(__ARMEB__) || (defined(__MWERKS__) && !defined(__INTEL__)))
#if !defined(IS_LITTLE_ENDIAN) && (defined(__BIG_ENDIAN__) || (defined(__s390__) || defined(__s390x__) || defined(__zarch__)) || defined(__sparc) || defined(__sparc__) || defined(__hppa__) || defined(__MIPSEB__) || defined(__ARMEB__) || (defined(__MWERKS__) && !defined(__INTEL__)))
# define IS_BIG_ENDIAN
#endif
@ -14,6 +14,15 @@
# define IS_LITTLE_ENDIAN
#endif
// Sanity checks. Some processors have more than big-, little- and bi-endian modes. PDP mode, where order results in "4312", should
// raise red flags immediately. Additionally, mis-classified machines, like (previosuly) S/390, should raise red flags immediately.
#if defined(IS_BIG_ENDIAN) && defined(__GNUC__) && defined(__BYTE_ORDER__) && (__BYTE_ORDER__ != __ORDER_BIG_ENDIAN__)
# error "IS_BIG_ENDIAN is set, but __BYTE_ORDER__ does not equal __ORDER_BIG_ENDIAN__"
#endif
#if defined(IS_LITTLE_ENDIAN) && defined(__GNUC__) && defined(__BYTE_ORDER__) && (__BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__)
# error "IS_LITTLE_ENDIAN is set, but __BYTE_ORDER__ does not equal __ORDER_LITTLE_ENDIAN__"
#endif
// define this if you want to disable all OS-dependent features,
// such as sockets and OS-provided random number generators
// #define NO_OS_DEPENDENCE
@ -23,21 +32,29 @@
// This macro will be ignored if NO_OS_DEPENDENCE is defined.
#define USE_MS_CRYPTOAPI
// Define this to ensure C/C++ standard compliance and adherence
// to aliasing rules and other alignment fodder. If you experience
// a break at -O3 with GCC, you should try this first.
// #define CRYPTOPP_NO_UNALIGNED_DATA_ACCESS
// Define this to ensure C/C++ standard compliance and respect for GCC aliasing rules and other alignment fodder. If you
// experience a break with GCC at -O3, you should try this first. Guard it in case its set on the command line (and it differs).
#ifndef CRYPTOPP_NO_UNALIGNED_DATA_ACCESS
// # define CRYPTOPP_NO_UNALIGNED_DATA_ACCESS
#endif
// ***************** Less Important Settings ***************
// Library version
#define CRYPTOPP_VERSION 563
// define this to retain (as much as possible) old deprecated function and class names
// #define CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
// Cygwin requires aligned data acess. It vectorizes word32's on i386, too.
#if defined(__CYGWIN__) || defined(__CYGWIN32__)
# define CRYPTOPP_NO_UNALIGNED_DATA_ACCESS
// define this to retain (as much as possible) ABI and binary compatibility with Crypto++ 5.6.2.
// Also see https://cryptopp.com/wiki/Config.h#Avoid_MAINTAIN_BACKWARDS_COMPATIBILITY
#if (CRYPTOPP_VERSION <= 600)
# if !defined(CRYPTOPP_NO_BACKWARDS_COMPATIBILITY_562) && !defined(CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562)
# define CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
# endif
#endif
// File system code to write to GZIP archive.
#define GZIP_OS_CODE 0
// Try this if your CPU has 256K internal cache or a slow multiply instruction
@ -49,31 +66,31 @@
// CACM paper.
// #define LCRNG_ORIGINAL_NUMBERS
// choose which style of sockets to wrap (mostly useful for cygwin which has both)
#define PREFER_BERKELEY_STYLE_SOCKETS
// #define PREFER_WINDOWS_STYLE_SOCKETS
// Set the name of Rijndael cipher, was "Rijndael" before version 5.3
#define CRYPTOPP_RIJNDAEL_NAME "AES"
// Only one or the other, but not both
#if (defined(DEBUG) || defined(_DEBUG)) && (defined(NDEBUG) || defined(_NDEBUG))
# error Both DEBUG and NDEBUG are defined.
// choose which style of sockets to wrap (mostly useful for MinGW which has both)
#if !defined(NO_BERKELEY_STYLE_SOCKETS) && !defined(PREFER_BERKELEY_STYLE_SOCKETS)
# define PREFER_BERKELEY_STYLE_SOCKETS
#endif
// CRYPTOPP_POSIX_ASSERT unconditionally disables the library assert and yields to
// Posix assert. Note that you always get an assert if CRYPTOPP_DEBUG is defined.
// If you don't want an assert, then be sure to define Posix's NDEBUG or _NDEBUG.
// #define CRYPTOPP_POSIX_ASSERT 1
// #if !defined(NO_WINDOWS_STYLE_SOCKETS) && !defined(PREFER_WINDOWS_STYLE_SOCKETS)
// # define PREFER_WINDOWS_STYLE_SOCKETS
// #endif
// Recognize two build types: debug and release. If NDEBUG is defined, then it is a
// Release build *without* asserts. Otherwise, it is a Debug build *with* asserts.
// If the developer does not build with either NDEBUG or DEBUG, then we error on
// the side of security and stability, and presume its a Debug build. For Debug
// builds, CRYPTOPP_ASSERT will alert to problems it detects, like NULL pointers,
// 0 sizes, overflow and undefined behavior.
#if !defined(NDEBUG) && !defined(_NDEBUG)
# define CRYPTOPP_DEBUG 1
// set the name of Rijndael cipher, was "Rijndael" before version 5.3
#define CRYPTOPP_RIJNDAEL_NAME "AES"
// CRYPTOPP_INIT_PRIORITY attempts to manage initialization of C++ static objects.
// Under GCC, the library uses init_priority attribute in the range
// [CRYPTOPP_INIT_PRIORITY, CRYPTOPP_INIT_PRIORITY+100]. Under Windows,
// CRYPTOPP_INIT_PRIORITY enlists "#pragma init_seg(lib)".
// #define CRYPTOPP_INIT_PRIORITY 250
// CRYPTOPP_USER_PRIORITY is for other libraries and user code that is using Crypto++
// and managing C++ static object creation. It is guaranteed not to conflict with
// values used by (or would be used by) the Crypto++ library.
#if defined(CRYPTOPP_INIT_PRIORITY) && (CRYPTOPP_INIT_PRIORITY > 0)
# define CRYPTOPP_USER_PRIORITY (CRYPTOPP_INIT_PRIORITY + 101)
#else
# define CRYPTOPP_USER_PRIORITY 500
#endif
// ***************** Important Settings Again ********************
@ -89,24 +106,20 @@
// Defining this will cause Crypto++ to make only one call to CryptAcquireContext.
#define WORKAROUND_MS_BUG_Q258000
// Define this if you are working around Clang's integrated assembler bug
// and issues with {prefix|noprefix} (https://llvm.org/bugs/show_bug.cgi?id=18916).
// When the LLVM project fixes it, then we turn it on/off automatically.
#define WORKAROUND_LLVM_BUG_18916
// Define this if you are working around Clang's integrated assembler bug
// and issues ".intel_syntax" (https://llvm.org/bugs/show_bug.cgi?id=24232).
// When the LLVM project fixes it, then we turn it on/off automatically.
#define WORKAROUND_LLVM_BUG_24232
// Define this if you are working with Clang's integrated assembler. As far as we know,
// the only way to tell is `$(CXX) -xc -c /dev/null -Wa,-v -o/dev/null 2>&1`. The
// integrated assembler will return `clang: error: unsupported argument '-v' option`.
#if defined(__clang__)
# define CRYPTOPP_CLANG_INTEGRATED_ASSEMBLER
#endif
#ifdef CRYPTOPP_DOXYGEN_PROCESSING
// Document the namespce exists. Put it here before CryptoPP is undefined below.
//! \namespace CryptoPP
//! \brief Crypto++ library namespace
//! \details Nearly all classes are located in the CryptoPP namespace. Within
//! the namespace, there are two additional namespaces.
//! <ul>
//! <li>Name - the namespace for names used with \p NameValuePairs and documented in argnames.h
//! <li>Weak - the namespace for weak and wounded algorithms, like ARC4, MD5 and Pananma
//! </ul>
namespace CryptoPP { }
// Bring in the symbols fund in the weak namespace; and fold Weak1 into Weak
# define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
# define Weak1 Weak
// Avoid putting "CryptoPP::" in front of everything in Doxygen output
# define CryptoPP
# define NAMESPACE_BEGIN(x)
@ -162,22 +175,45 @@ const lword LWORD_MAX = W64LIT(0xffffffffffffffff);
#define CRYPTOPP_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
#ifdef __clang__
#define CRYPTOPP_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
#endif
#ifdef _MSC_VER
#define CRYPTOPP_MSC_VERSION (_MSC_VER)
#endif
// Need GCC 4.6/Clang 1.7 or above due to "GCC diagnostic {push|pop}"
#if (CRYPTOPP_GCC_VERSION >= 40600) || (CRYPTOPP_CLANG_VERSION >= 10700)
#define CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 1
#endif
// Detect availabliltiy of int128_t and uint128_t in preprocessor, http://gcc.gnu.org/ml/gcc-help/2015-08/msg00185.html.
// Both GCC and Clang respond to it.
#if ((defined(__GNUC__) || defined(__clang__) || defined(_INTEL_COMPILER)) && (__SIZEOF_INT128__ >= 16))
#define CRYPTOPP_NATIVE_DWORD_AVAILABLE
#define CRYPTOPP_WORD128_AVAILABLE
typedef word32 hword;
typedef word64 word;
typedef __uint128_t dword;
typedef __uint128_t word128;
// define hword, word, and dword. these are used for multiprecision integer arithmetic
// Intel compiler won't have _umul128 until version 10.0. See http://softwarecommunity.intel.com/isn/Community/en-US/forums/thread/30231625.aspx
#if (defined(_MSC_VER) && (!defined(__INTEL_COMPILER) || __INTEL_COMPILER >= 1000) && (defined(_M_X64) || defined(_M_IA64))) || (defined(__DECCXX) && defined(__alpha__)) || (defined(__INTEL_COMPILER) && defined(__x86_64__)) || (defined(__SUNPRO_CC) && defined(__x86_64__))
#elif (defined(_MSC_VER) && (!defined(__INTEL_COMPILER) || __INTEL_COMPILER >= 1000) && (defined(_M_X64) || defined(_M_IA64))) || (defined(__DECCXX) && defined(__alpha__)) || (defined(__INTEL_COMPILER) && defined(__x86_64__)) || (defined(__SUNPRO_CC) && defined(__x86_64__))
typedef word32 hword;
typedef word64 word;
#else
#define CRYPTOPP_NATIVE_DWORD_AVAILABLE
#if defined(__alpha__) || defined(__ia64__) || defined(_ARCH_PPC64) || defined(__x86_64__) || defined(__mips64) || defined(__sparc64__)
#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && !(CRYPTOPP_GCC_VERSION == 40001 && defined(__APPLE__)) && CRYPTOPP_GCC_VERSION >= 30400
#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && !(CRYPTOPP_GCC_VERSION == 40001 && defined(__APPLE__)) && (CRYPTOPP_GCC_VERSION >= 30400)
// GCC 4.0.1 on MacOS X is missing __umodti3 and __udivti3
// mode(TI) division broken on amd64 with GCC earlier than GCC 3.4
#define CRYPTOPP_WORD128_AVAILABLE
typedef word32 hword;
typedef word64 word;
typedef __uint128_t dword;
typedef __uint128_t word128;
#define CRYPTOPP_WORD128_AVAILABLE
#else
// if we're here, it means we're on a 64-bit CPU but we don't have a way to obtain 128-bit multiplication results
typedef word16 hword;
@ -192,23 +228,15 @@ const lword LWORD_MAX = W64LIT(0xffffffffffffffff);
typedef word64 dword;
#endif
#endif
// Handle missing ssize_t on Windows. Typedef's taken from:
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx
#if (defined(_WIN32) || defined(_WIN64)) && !(defined(__MINGW__) || defined(__MINGW32__))
# if defined(_WIN64)
typedef __int64 LONG_PTR;
# else
typedef long LONG_PTR;
# endif
typedef LONG_PTR SSIZE_T;
typedef SSIZE_T ssize_t;
#endif
#ifndef CRYPTOPP_BOOL_SLOW_WORD64
#define CRYPTOPP_BOOL_SLOW_WORD64 0
#endif
// Produce a compiler error. It can be commented out, but you may not get the benefit of the fastest integers.
#if (__SIZEOF_INT128__ >= 16) && !defined(CRYPTOPP_WORD128_AVAILABLE)
# error "An int128_t and uint128_t are available, but CRYPTOPP_WORD128_AVAILABLE is not defined"
#endif
const unsigned int WORD_SIZE = sizeof(word);
const unsigned int WORD_BITS = WORD_SIZE * 8;
@ -216,7 +244,8 @@ NAMESPACE_END
#ifndef CRYPTOPP_L1_CACHE_LINE_SIZE
// This should be a lower bound on the L1 cache line size. It's used for defense against timing attacks.
#if defined(_M_X64) || defined(__x86_64__)
// Also see http://stackoverflow.com/questions/794632/programmatically-get-the-cache-line-size.
#if defined(_M_X64) || defined(__x86_64__) || (__ILP32__ >= 1)
#define CRYPTOPP_L1_CACHE_LINE_SIZE 64
#else
// L1 cache line size is 32 on Pentium III and earlier
@ -246,7 +275,7 @@ NAMESPACE_END
#endif
#ifndef CRYPTOPP_SECTION_ALIGN16
#if defined(__GNUC__) && !defined(__APPLE__)
#if defined(__GNUC__) && !defined(__APPLE__)
// the alignment attribute doesn't seem to work without this section attribute when -fdata-sections is turned on
#define CRYPTOPP_SECTION_ALIGN16 __attribute__((section ("CryptoPP_Align16")))
#else
@ -281,19 +310,22 @@ NAMESPACE_END
#endif
#ifdef _MSC_VER
// 4127: conditional expression is constant
// 4231: nonstandard extension used : 'extern' before template explicit instantiation
// 4250: dominance
// 4251: member needs to have dll-interface
// 4275: base needs to have dll-interface
// 4505: unreferenced local function
// 4512: assignment operator not generated
// 4660: explicitly instantiating a class that's already implicitly instantiated
// 4661: no suitable definition provided for explicit template instantiation request
// 4786: identifer was truncated in debug information
// 4355: 'this' : used in base member initializer list
// 4910: '__declspec(dllexport)' and 'extern' are incompatible on an explicit instantiation
# pragma warning(disable: 4231 4250 4251 4275 4660 4661 4786 4355 4910)
# pragma warning(disable: 4127 4231 4250 4251 4275 4505 4512 4660 4661 4786 4355 4910)
// Security related, possible defects
// http://blogs.msdn.com/b/vcblog/archive/2010/12/14/off-by-default-compiler-warnings-in-visual-c.aspx
# pragma warning(once: 4191 4242 4263 4264 4265 4266 4302 4826 4905 4906 4928)
# pragma warning(once: 4191 4242 4263 4264 4266 4302 4826 4905 4906 4928)
#endif
#ifdef __BORLANDC__
@ -301,6 +333,12 @@ NAMESPACE_END
# pragma warn -8037
#endif
// [GCC Bug 53431] "C++ preprocessor ignores #pragma GCC diagnostic". Clang honors it.
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#if (defined(_MSC_VER) && _MSC_VER <= 1300) || defined(__MWERKS__) || defined(_STLPORT_VERSION)
#define CRYPTOPP_DISABLE_UNCAUGHT_EXCEPTION
#endif
@ -318,15 +356,16 @@ NAMESPACE_END
// C++Builder 2010 does not allow "call label" where label is defined within inline assembly
#define CRYPTOPP_X86_ASM_AVAILABLE
#if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(CRYPTOPP_MSVC6PP_OR_LATER) || CRYPTOPP_GCC_VERSION >= 30300)
#if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(CRYPTOPP_MSVC6PP_OR_LATER) || CRYPTOPP_GCC_VERSION >= 30300 || defined(__SSE2__))
#define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 0
#endif
// SSSE3 was actually introduced in GNU as 2.17, which was released 6/23/2006, but we can't tell what version of binutils is installed.
// GCC 4.1.2 was released on 2/13/2007, so we'll use that as a proxy for the binutils version.
#if !defined(CRYPTOPP_DISABLE_SSSE3) && (_MSC_VER >= 1400 || CRYPTOPP_GCC_VERSION >= 40102)
// SSE3 was actually introduced in GNU as 2.17, which was released 6/23/2006, but we can't tell what version of binutils is installed.
// GCC 4.1.2 was released on 2/13/2007, so we'll use that as a proxy for the binutils version. Also see the output of
// `gcc -dM -E -march=native - < /dev/null | grep -i SSE` for preprocessor defines available.
#if !defined(CRYPTOPP_DISABLE_SSSE3) && (_MSC_VER >= 1400 || CRYPTOPP_GCC_VERSION >= 40102 || defined(__SSSE3__) || defined(__SSE3__))
#define CRYPTOPP_BOOL_SSSE3_ASM_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_SSSE3_ASM_AVAILABLE 0
@ -337,26 +376,26 @@ NAMESPACE_END
#define CRYPTOPP_X64_MASM_AVAILABLE
#endif
#if !defined(CRYPTOPP_DISABLE_ASM) &&!defined(CRYPTOPP_CLANG_INTEGRATED_ASSEMBLER) && defined(__GNUC__) && defined(__x86_64__)
#if !defined(CRYPTOPP_DISABLE_ASM) && defined(__GNUC__) && defined(__x86_64__)
#define CRYPTOPP_X64_ASM_AVAILABLE
#endif
#if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(CRYPTOPP_MSVC6PP_OR_LATER) || defined(__SSE2__))
#if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(CRYPTOPP_MSVC6PP_OR_LATER) || defined(__SSE2__) || defined(__AES__))
#define CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE 0
#endif
#if !defined(CRYPTOPP_DISABLE_SSSE3) && !defined(CRYPTOPP_DISABLE_AESNI) && CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE && (CRYPTOPP_GCC_VERSION >= 40400 || _MSC_FULL_VER >= 150030729 || __INTEL_COMPILER >= 1110)
#if !defined(CRYPTOPP_DISABLE_SSSE3) && !defined(CRYPTOPP_DISABLE_AESNI) && CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE && (CRYPTOPP_GCC_VERSION >= 40400 || _MSC_FULL_VER >= 150030729 || __INTEL_COMPILER >= 1110 || defined(__AES__))
#define CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE 0
#endif
#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE || CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)
#define CRYPTOPP_BOOL_ALIGN16_ENABLED 1
#define CRYPTOPP_BOOL_ALIGN16 1
#else
#define CRYPTOPP_BOOL_ALIGN16_ENABLED 0
#define CRYPTOPP_BOOL_ALIGN16 0
#endif
// how to allocate 16-byte aligned memory (for SSE2)
@ -389,25 +428,46 @@ NAMESPACE_END
# define CRYPTOPP_CONSTANT(x) static const int x;
#endif
#if defined(_M_X64) || defined(__x86_64__)
#define CRYPTOPP_BOOL_X64 1
// Linux provides X32, which is 32-bit integers, longs and pointers on x86_64 using the full x86_64 register set.
// Detect via __ILP32__ (http://wiki.debian.org/X32Port). Both GCC and Clang provide the preprocessor macro.
#if ((__ILP32__ >= 1) || (_ILP32 >= 1))
#define CRYPTOPP_BOOL_X32 1
#else
#define CRYPTOPP_BOOL_X64 0
#define CRYPTOPP_BOOL_X32 0
#endif
// see http://predef.sourceforge.net/prearch.html
#if defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_X86_) || defined(__I86__) || defined(__INTEL__)
#if (defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_X86_) || defined(__I86__) || defined(__INTEL__)) && !CRYPTOPP_BOOL_X32
#define CRYPTOPP_BOOL_X86 1
#else
#define CRYPTOPP_BOOL_X86 0
#endif
// CRYPTOPP_NO_UNALIGNED_DATA_ACCESS can be set on the command line or in config.h above.
#if !defined(CRYPTOPP_NO_UNALIGNED_DATA_ACCESS) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86 || defined(__powerpc__))
#define CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
#if (defined(_M_X64) || defined(__x86_64__)) && !CRYPTOPP_BOOL_X32
#define CRYPTOPP_BOOL_X64 1
#else
#define CRYPTOPP_BOOL_X64 0
#endif
#define CRYPTOPP_VERSION 562
// Undo the ASM and Intrinsic related defines due to X32.
#if CRYPTOPP_BOOL_X32
# undef CRYPTOPP_BOOL_X64
# undef CRYPTOPP_X64_ASM_AVAILABLE
# undef CRYPTOPP_X64_MASM_AVAILABLE
#endif
#if !defined(CRYPTOPP_NO_UNALIGNED_DATA_ACCESS) && !defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS)
#if (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || defined(__powerpc__) || (__ARM_FEATURE_UNALIGNED >= 1))
#define CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
#endif
#endif
// For use in template parameters; also see CRYPTOPP_BOOL_ALIGN16 for MMX and above.
#if defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS)
#define CRYPTOPP_BOOL_ALIGN 0
#else
#define CRYPTOPP_BOOL_ALIGN 1
#endif
// ***************** determine availability of OS features ********************
@ -522,11 +582,15 @@ NAMESPACE_END
#define CRYPTOPP_STATIC_TEMPLATE_CLASS CRYPTOPP_EXTERN_STATIC_TEMPLATE_CLASS
#endif
// ***************** C++11 and C++14 related ********************
// ************** Unused variable ***************
// Portable way to suppress warning
#define CRYPTOPP_UNUSED(x) ((void)x)
// Visual Studio and C++11 language features began at Visual Studio 2010, https://msdn.microsoft.com/en-us/library/hh567368%28v=vs.110%29.aspx.
// Intel and C++11 language features, https://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler
// GCC and C++11 language features, https://gcc.gnu.org/projects/cxx0x.html
// ***************** C++11 related ********************
// Visual Studio and C++11 language features began at Visual Studio 2010, http://msdn.microsoft.com/en-us/library/hh567368%28v=vs.110%29.aspx.
// Intel and C++11 language features, http://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler
// GCC and C++11 language features, http://gcc.gnu.org/projects/cxx0x.html
// Clang and C++11 language features, http://clang.llvm.org/cxx_status.html
#if (_MSC_VER >= 1600) || (__cplusplus >= 201103L)
# define CRYPTOPP_CXX11 1
@ -543,72 +607,52 @@ NAMESPACE_END
# endif
#endif
// C++14 adds a operator”” and Small String Optimizations (SSO)
// TODO: change this when Microsoft adds support
#if (_MSC_VER >= 2300) || (__cplusplus >= 201402L)
# define CRYPTOPP_CXX14 1
// C++11 or C++14 is available
#if defined(CRYPTOPP_CXX11)
// alignof/alignas: MS at VS2013 (18.00); GCC at 4.8; Clang at 3.3; and Intel 15.0.
#if (CRYPTOPP_MSC_VERSION >= 1800)
# define CRYPTOPP_CXX11_ALIGNOF 1
#elif defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1500)
# define CRYPTOPP_CXX11_ALIGNOF 1
#elif defined(__clang__)
# if __has_feature(cxx_alignof)
# define CRYPTOPP_CXX11_ALIGNOF 1
# endif
#elif (CRYPTOPP_GCC_VERSION >= 40800)
# define CRYPTOPP_CXX11_ALIGNOF 1
#endif
// C++11 or C++14 is available
#if defined(CRYPTOPP_CXX11) || defined(CRYPTOPP_CXX14)
// Everone appears to provide this list
#define CRYPTOPP_CXX11_UNIQUE_PTR 1
// #define CRYPTOPP_CXX11_ALIGNAS 1
// #define CRYPTOPP_CXX11_ALIGNOF 1
// std::move: MS at VS2015 (19.00); GCC at 4.6; Clang at 2.9; and Intel 11.1.
#if (_MSC_VER >= 1600) || (__INTEL_COMPILER >= 1110)
# define CRYPTOPP_CXX11_MOVE 1
#elif (__clang_major__ >= 3 || (__clang_major__ == 2 && __clang_minor__ >= 9))
# define CRYPTOPP_CXX11_MOVE 1
#elif (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
# define CRYPTOPP_CXX11_MOVE 1
#endif // std::move
// R-values: MS at VS2010 (16.00); GCC at 4.3; Clang at 2.9; and Intel 11.1.
#if (_MSC_VER >= 1600) || (__INTEL_COMPILER >= 1110)
# define CRYPTOPP_CXX11_RVALUES 1
#elif (__clang_major__ >= 3 || (__clang_major__ == 2 && __clang_minor__ >= 9))
# define CRYPTOPP_CXX11_RVALUES 1
#elif (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
# define CRYPTOPP_CXX11_RVALUES 1
#endif // R-value compilers
// template aliases: MS at VS 2015 (v19.00); GCC at 4.7; Clang at 3.0; and Intel 12.1.
#if (_MSC_VER >= 1900) || (__INTEL_COMPILER >= 1210)
# define CRYPTOPP_CXX11_TEMPLATE_ALIAS 1
#elif defined(__clang__)
# if (__has_feature(cxx_alias_templates))
# define CCRYPTOPP_CXX11_TEMPLATE_ALIAS 1
# endif
#elif (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))
# define CRYPTOPP_CXX11_TEMPLATE_ALIAS 1
#endif // template aliases
// noexcept: MS at VS2015 (19.00); GCC at 4.6; Clang at 3.0; and Intel 14.0.
#if (_MSC_VER >= 1900) || (__INTEL_COMPILER >= 1400)
#if (CRYPTOPP_MSC_VERSION >= 1900)
# define CRYPTOPP_CXX11_NOEXCEPT 1
#elif defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1400)
# define CRYPTOPP_CXX11_NOEXCEPT 1
#elif defined(__clang__)
# if __has_feature(cxx_noexcept)
# define CRYPTOPP_CXX11_NOEXCEPT 1
# endif
#elif (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
#elif (CRYPTOPP_GCC_VERSION >= 40600)
# define CRYPTOPP_CXX11_NOEXCEPT 1
#endif // noexcept compilers
// static assert: MS at VS2010 (16.00); GCC at 4.3; Clang at 3.0; and Intel 11.1.
#if (_MSC_VER >= 1600) || (__INTEL_COMPILER >= 1110)
# define CRYPTOPP_CXX11_STATIC_ASSERT 1
// variadic templates: MS at VS2013 (18.00); GCC at 4.3; Clang at 2.9; and Intel 12.1.
#if (CRYPTOPP_MSC_VERSION >= 1800)
# define CRYPTOPP_CXX11_VARIADIC_TEMPLATES 1
#elif defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1210)
# define CRYPTOPP_CXX11_VARIADIC_TEMPLATES 1
#elif defined(__clang__)
# if __has_feature(cxx_static_assert)
# define CRYPTOPP_CXX11_STATIC_ASSERT 1
# if __has_feature(cxx_variadic_templates)
# define CRYPTOPP_CXX11_VARIADIC_TEMPLATES 1
# endif
#elif (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
# define CRYPTOPP_CXX11_STATIC_ASSERT 1
#endif // static assert
#elif (CRYPTOPP_GCC_VERSION >= 40300)
# define CRYPTOPP_CXX11_VARIADIC_TEMPLATES 1
#endif // noexcept compilers
#endif // #endif // CRYPTOPP_CXX11
// TODO: Emplacement, R-values and Move semantics
// Needed because we are catching warnings with GCC and MSC
#endif // CRYPTOPP_CXX11
#if defined(CRYPTOPP_CXX11_NOEXCEPT)
# define CRYPTOPP_THROW noexcept(false)
@ -618,11 +662,9 @@ NAMESPACE_END
# define CRYPTOPP_NO_THROW
#endif // CRYPTOPP_CXX11_NOEXCEPT
// This tests compatibility with C++11 nullptr
#if defined(__clang__)
# if (__has_feature(cxx_nullptr))
# define NULL nullptr
# endif
// OK to comment the following out, but please report it so we can fix it.
#if (defined(__cplusplus) && (__cplusplus >= 199711L)) && !defined(CRYPTOPP_UNCAUGHT_EXCEPTION_AVAILABLE)
# error "std::uncaught_exception is not available. This is likely a configuration error."
#endif
#endif // CRYPTOPP_CONFIG_H
#endif

622
config.recommend Normal file
View File

@ -0,0 +1,622 @@
#ifndef CRYPTOPP_CONFIG_H
#define CRYPTOPP_CONFIG_H
// ***************** Important Settings ********************
// define this if running on a big-endian CPU
#if !defined(IS_LITTLE_ENDIAN) && (defined(__BIG_ENDIAN__) || (defined(__s390__) || defined(__s390x__) || defined(__zarch__)) || defined(__sparc) || defined(__sparc__) || defined(__hppa__) || defined(__MIPSEB__) || defined(__ARMEB__) || (defined(__MWERKS__) && !defined(__INTEL__)))
# define IS_BIG_ENDIAN
#endif
// define this if running on a little-endian CPU
// big endian will be assumed if IS_LITTLE_ENDIAN is not defined
#ifndef IS_BIG_ENDIAN
# define IS_LITTLE_ENDIAN
#endif
// Sanity checks. Some processors have more than big-, little- and bi-endian modes. PDP mode, where order results in "4312", should
// raise red flags immediately. Additionally, mis-classified machines, like (previosuly) S/390, should raise red flags immediately.
#if defined(IS_BIG_ENDIAN) && defined(__GNUC__) && defined(__BYTE_ORDER__) && (__BYTE_ORDER__ != __ORDER_BIG_ENDIAN__)
# error "IS_BIG_ENDIAN is set, but __BYTE_ORDER__ does not equal __ORDER_BIG_ENDIAN__"
#endif
#if defined(IS_LITTLE_ENDIAN) && defined(__GNUC__) && defined(__BYTE_ORDER__) && (__BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__)
# error "IS_LITTLE_ENDIAN is set, but __BYTE_ORDER__ does not equal __ORDER_LITTLE_ENDIAN__"
#endif
// define this if you want to disable all OS-dependent features,
// such as sockets and OS-provided random number generators
// #define NO_OS_DEPENDENCE
// Define this to use features provided by Microsoft's CryptoAPI.
// Currently the only feature used is random number generation.
// This macro will be ignored if NO_OS_DEPENDENCE is defined.
#define USE_MS_CRYPTOAPI
// Define this to ensure C/C++ standard compliance and respect for GCC aliasing rules and other alignment fodder. If you
// experience a break with GCC at -O3, you should try this first. Guard it in case its set on the command line (and it differs).
#ifndef CRYPTOPP_NO_UNALIGNED_DATA_ACCESS
# define CRYPTOPP_NO_UNALIGNED_DATA_ACCESS
#endif
// ***************** Less Important Settings ***************
// Library version
#define CRYPTOPP_VERSION 563
// define this to retain (as much as possible) old deprecated function and class names
// #define CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
// define this to retain (as much as possible) ABI and binary compatibility with Crypto++ 5.6.2.
// Also see https://cryptopp.com/wiki/Config.h#Avoid_MAINTAIN_BACKWARDS_COMPATIBILITY
#if (CRYPTOPP_VERSION <= 600)
# if !defined(CRYPTOPP_NO_BACKWARDS_COMPATIBILITY_562) && !defined(CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562)
// # define CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
# endif
#endif
// File system code to write to GZIP archive.
#define GZIP_OS_CODE 0
// Try this if your CPU has 256K internal cache or a slow multiply instruction
// and you want a (possibly) faster IDEA implementation using log tables
// #define IDEA_LARGECACHE
// Define this if, for the linear congruential RNG, you want to use
// the original constants as specified in S.K. Park and K.W. Miller's
// CACM paper.
// #define LCRNG_ORIGINAL_NUMBERS
// choose which style of sockets to wrap (mostly useful for cygwin which has both)
#define PREFER_BERKELEY_STYLE_SOCKETS
// #define PREFER_WINDOWS_STYLE_SOCKETS
// set the name of Rijndael cipher, was "Rijndael" before version 5.3
#define CRYPTOPP_RIJNDAEL_NAME "AES"
// CRYPTOPP_INIT_PRIORITY attempts to manage initialization of C++ static objects.
// Under GCC, the library uses init_priority attribute in the range
// [CRYPTOPP_INIT_PRIORITY, CRYPTOPP_INIT_PRIORITY+100]. Under Windows,
// CRYPTOPP_INIT_PRIORITY enlists "#pragma init_seg(lib)".
#define CRYPTOPP_INIT_PRIORITY 250
// CRYPTOPP_USER_PRIORITY is for other libraries and user code that is using Crypto++
// and managing C++ static object creation. It is guaranteed not to conflict with
// values used by (or would be used by) the Crypto++ library.
#if defined(CRYPTOPP_INIT_PRIORITY) && (CRYPTOPP_INIT_PRIORITY > 0)
# define CRYPTOPP_USER_PRIORITY (CRYPTOPP_INIT_PRIORITY + 101)
#else
# define CRYPTOPP_USER_PRIORITY 500
#endif
// ***************** Important Settings Again ********************
// But the defaults should be ok.
// namespace support is now required
#ifdef NO_NAMESPACE
# error namespace support is now required
#endif
// Define this to workaround a Microsoft CryptoAPI bug where
// each call to CryptAcquireContext causes a 100 KB memory leak.
// Defining this will cause Crypto++ to make only one call to CryptAcquireContext.
#define WORKAROUND_MS_BUG_Q258000
#ifdef CRYPTOPP_DOXYGEN_PROCESSING
// Avoid putting "CryptoPP::" in front of everything in Doxygen output
# define CryptoPP
# define NAMESPACE_BEGIN(x)
# define NAMESPACE_END
// Get Doxygen to generate better documentation for these typedefs
# define DOCUMENTED_TYPEDEF(x, y) class y : public x {};
#else
# define NAMESPACE_BEGIN(x) namespace x {
# define NAMESPACE_END }
# define DOCUMENTED_TYPEDEF(x, y) typedef x y;
#endif
#define ANONYMOUS_NAMESPACE_BEGIN namespace {
#define USING_NAMESPACE(x) using namespace x;
#define DOCUMENTED_NAMESPACE_BEGIN(x) namespace x {
#define DOCUMENTED_NAMESPACE_END }
// What is the type of the third parameter to bind?
// For Unix, the new standard is ::socklen_t (typically unsigned int), and the old standard is int.
// Unfortunately there is no way to tell whether or not socklen_t is defined.
// To work around this, TYPE_OF_SOCKLEN_T is a macro so that you can change it from the makefile.
#ifndef TYPE_OF_SOCKLEN_T
# if defined(_WIN32) || defined(__CYGWIN__)
# define TYPE_OF_SOCKLEN_T int
# else
# define TYPE_OF_SOCKLEN_T ::socklen_t
# endif
#endif
#if defined(__CYGWIN__) && defined(PREFER_WINDOWS_STYLE_SOCKETS)
# define __USE_W32_SOCKETS
#endif
typedef unsigned char byte; // put in global namespace to avoid ambiguity with other byte typedefs
NAMESPACE_BEGIN(CryptoPP)
typedef unsigned short word16;
typedef unsigned int word32;
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 word64;
#define W64LIT(x) x##ui64
#else
typedef unsigned long long word64;
#define W64LIT(x) x##ULL
#endif
// define large word type, used for file offsets and such
typedef word64 lword;
const lword LWORD_MAX = W64LIT(0xffffffffffffffff);
#ifdef __GNUC__
#define CRYPTOPP_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
#ifdef __clang__
#define CRYPTOPP_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
#endif
#ifdef _MSC_VER
#define CRYPTOPP_MSC_VERSION (_MSC_VER)
#endif
// Need GCC 4.6/Clang 1.7 or above due to "GCC diagnostic {push|pop}"
#if (CRYPTOPP_GCC_VERSION >= 40600) || (CRYPTOPP_CLANG_VERSION >= 10700)
#define CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 1
#endif
// Detect availabliltiy of int128_t and uint128_t in preprocessor, http://gcc.gnu.org/ml/gcc-help/2015-08/msg00185.html.
// Both GCC and Clang respond to it.
#if ((defined(__GNUC__) || defined(__clang__) || defined(_INTEL_COMPILER)) && (__SIZEOF_INT128__ >= 16))
#define CRYPTOPP_NATIVE_DWORD_AVAILABLE
#define CRYPTOPP_WORD128_AVAILABLE
typedef word32 hword;
typedef word64 word;
typedef __uint128_t dword;
typedef __uint128_t word128;
// define hword, word, and dword. these are used for multiprecision integer arithmetic
// Intel compiler won't have _umul128 until version 10.0. See http://softwarecommunity.intel.com/isn/Community/en-US/forums/thread/30231625.aspx
#elif (defined(_MSC_VER) && (!defined(__INTEL_COMPILER) || __INTEL_COMPILER >= 1000) && (defined(_M_X64) || defined(_M_IA64))) || (defined(__DECCXX) && defined(__alpha__)) || (defined(__INTEL_COMPILER) && defined(__x86_64__)) || (defined(__SUNPRO_CC) && defined(__x86_64__))
typedef word32 hword;
typedef word64 word;
#else
#define CRYPTOPP_NATIVE_DWORD_AVAILABLE
#if defined(__alpha__) || defined(__ia64__) || defined(_ARCH_PPC64) || defined(__x86_64__) || defined(__mips64) || defined(__sparc64__)
#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && !(CRYPTOPP_GCC_VERSION == 40001 && defined(__APPLE__)) && (CRYPTOPP_GCC_VERSION >= 30400)
// GCC 4.0.1 on MacOS X is missing __umodti3 and __udivti3
// mode(TI) division broken on amd64 with GCC earlier than GCC 3.4
#define CRYPTOPP_WORD128_AVAILABLE
typedef word32 hword;
typedef word64 word;
typedef __uint128_t dword;
typedef __uint128_t word128;
#else
// if we're here, it means we're on a 64-bit CPU but we don't have a way to obtain 128-bit multiplication results
typedef word16 hword;
typedef word32 word;
typedef word64 dword;
#endif
#else
// being here means the native register size is probably 32 bits or less
#define CRYPTOPP_BOOL_SLOW_WORD64 1
typedef word16 hword;
typedef word32 word;
typedef word64 dword;
#endif
#endif
#ifndef CRYPTOPP_BOOL_SLOW_WORD64
#define CRYPTOPP_BOOL_SLOW_WORD64 0
#endif
// Produce a compiler error. It can be commented out, but you may not get the benefit of the fastest integers.
#if (__SIZEOF_INT128__ >= 16) && !defined(CRYPTOPP_WORD128_AVAILABLE)
# error "An int128_t and uint128_t are available, but CRYPTOPP_WORD128_AVAILABLE is not defined"
#endif
const unsigned int WORD_SIZE = sizeof(word);
const unsigned int WORD_BITS = WORD_SIZE * 8;
NAMESPACE_END
#ifndef CRYPTOPP_L1_CACHE_LINE_SIZE
// This should be a lower bound on the L1 cache line size. It's used for defense against timing attacks.
// Also see http://stackoverflow.com/questions/794632/programmatically-get-the-cache-line-size.
#if defined(_M_X64) || defined(__x86_64__) || (__ILP32__ >= 1)
#define CRYPTOPP_L1_CACHE_LINE_SIZE 64
#else
// L1 cache line size is 32 on Pentium III and earlier
#define CRYPTOPP_L1_CACHE_LINE_SIZE 32
#endif
#endif
#if defined(_MSC_VER)
#if _MSC_VER == 1200
#include <malloc.h>
#endif
#if _MSC_VER > 1200 || defined(_mm_free)
#define CRYPTOPP_MSVC6PP_OR_LATER // VC 6 processor pack or later
#else
#define CRYPTOPP_MSVC6_NO_PP // VC 6 without processor pack
#endif
#endif
#ifndef CRYPTOPP_ALIGN_DATA
#if defined(CRYPTOPP_MSVC6PP_OR_LATER)
#define CRYPTOPP_ALIGN_DATA(x) __declspec(align(x))
#elif defined(__GNUC__)
#define CRYPTOPP_ALIGN_DATA(x) __attribute__((aligned(x)))
#else
#define CRYPTOPP_ALIGN_DATA(x)
#endif
#endif
#ifndef CRYPTOPP_SECTION_ALIGN16
#if defined(__GNUC__) && !defined(__APPLE__)
// the alignment attribute doesn't seem to work without this section attribute when -fdata-sections is turned on
#define CRYPTOPP_SECTION_ALIGN16 __attribute__((section ("CryptoPP_Align16")))
#else
#define CRYPTOPP_SECTION_ALIGN16
#endif
#endif
#if defined(_MSC_VER) || defined(__fastcall)
#define CRYPTOPP_FASTCALL __fastcall
#else
#define CRYPTOPP_FASTCALL
#endif
// VC60 workaround: it doesn't allow typename in some places
#if defined(_MSC_VER) && (_MSC_VER < 1300)
#define CPP_TYPENAME
#else
#define CPP_TYPENAME typename
#endif
// VC60 workaround: can't cast unsigned __int64 to float or double
#if defined(_MSC_VER) && !defined(CRYPTOPP_MSVC6PP_OR_LATER)
#define CRYPTOPP_VC6_INT64 (__int64)
#else
#define CRYPTOPP_VC6_INT64
#endif
#ifdef _MSC_VER
#define CRYPTOPP_NO_VTABLE __declspec(novtable)
#else
#define CRYPTOPP_NO_VTABLE
#endif
#ifdef _MSC_VER
// 4127: conditional expression is constant
// 4231: nonstandard extension used : 'extern' before template explicit instantiation
// 4250: dominance
// 4251: member needs to have dll-interface
// 4275: base needs to have dll-interface
// 4505: unreferenced local function
// 4512: assignment operator not generated
// 4660: explicitly instantiating a class that's already implicitly instantiated
// 4661: no suitable definition provided for explicit template instantiation request
// 4786: identifer was truncated in debug information
// 4355: 'this' : used in base member initializer list
// 4910: '__declspec(dllexport)' and 'extern' are incompatible on an explicit instantiation
# pragma warning(disable: 4127 4231 4250 4251 4275 4505 4512 4660 4661 4786 4355 4910)
// Security related, possible defects
// http://blogs.msdn.com/b/vcblog/archive/2010/12/14/off-by-default-compiler-warnings-in-visual-c.aspx
# pragma warning(once: 4191 4242 4263 4264 4266 4302 4826 4905 4906 4928)
#endif
#ifdef __BORLANDC__
// 8037: non-const function called for const object. needed to work around BCB2006 bug
# pragma warn -8037
#endif
// [GCC Bug 53431] "C++ preprocessor ignores #pragma GCC diagnostic". Clang honors it.
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#if (defined(_MSC_VER) && _MSC_VER <= 1300) || defined(__MWERKS__) || defined(_STLPORT_VERSION)
#define CRYPTOPP_DISABLE_UNCAUGHT_EXCEPTION
#endif
#ifndef CRYPTOPP_DISABLE_UNCAUGHT_EXCEPTION
#define CRYPTOPP_UNCAUGHT_EXCEPTION_AVAILABLE
#endif
#ifdef CRYPTOPP_DISABLE_X86ASM // for backwards compatibility: this macro had both meanings
#define CRYPTOPP_DISABLE_ASM
#define CRYPTOPP_DISABLE_SSE2
#endif
#if !defined(CRYPTOPP_DISABLE_ASM) && ((defined(_MSC_VER) && defined(_M_IX86)) || (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))))
// C++Builder 2010 does not allow "call label" where label is defined within inline assembly
#define CRYPTOPP_X86_ASM_AVAILABLE
#if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(CRYPTOPP_MSVC6PP_OR_LATER) || CRYPTOPP_GCC_VERSION >= 30300 || defined(__SSE2__))
#define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 0
#endif
// SSE3 was actually introduced in GNU as 2.17, which was released 6/23/2006, but we can't tell what version of binutils is installed.
// GCC 4.1.2 was released on 2/13/2007, so we'll use that as a proxy for the binutils version. Also see the output of
// `gcc -dM -E -march=native - < /dev/null | grep -i SSE` for preprocessor defines available.
#if !defined(CRYPTOPP_DISABLE_SSSE3) && (_MSC_VER >= 1400 || CRYPTOPP_GCC_VERSION >= 40102 || defined(__SSSE3__) || defined(__SSE3__))
#define CRYPTOPP_BOOL_SSSE3_ASM_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_SSSE3_ASM_AVAILABLE 0
#endif
#endif
#if !defined(CRYPTOPP_DISABLE_ASM) && defined(_MSC_VER) && defined(_M_X64)
#define CRYPTOPP_X64_MASM_AVAILABLE
#endif
#if !defined(CRYPTOPP_DISABLE_ASM) && defined(__GNUC__) && defined(__x86_64__)
#define CRYPTOPP_X64_ASM_AVAILABLE
#endif
#if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(CRYPTOPP_MSVC6PP_OR_LATER) || defined(__SSE2__) || defined(__AES__))
#define CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE 0
#endif
#if !defined(CRYPTOPP_DISABLE_SSSE3) && !defined(CRYPTOPP_DISABLE_AESNI) && CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE && (CRYPTOPP_GCC_VERSION >= 40400 || _MSC_FULL_VER >= 150030729 || __INTEL_COMPILER >= 1110 || defined(__AES__))
#define CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE 0
#endif
#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE || CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)
#define CRYPTOPP_BOOL_ALIGN16 1
#else
#define CRYPTOPP_BOOL_ALIGN16 0
#endif
// how to allocate 16-byte aligned memory (for SSE2)
#if defined(CRYPTOPP_MSVC6PP_OR_LATER)
#define CRYPTOPP_MM_MALLOC_AVAILABLE
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
#define CRYPTOPP_MALLOC_ALIGNMENT_IS_16
#elif defined(__linux__) || defined(__sun__) || defined(__CYGWIN__)
#define CRYPTOPP_MEMALIGN_AVAILABLE
#else
#define CRYPTOPP_NO_ALIGNED_ALLOC
#endif
// how to disable inlining
#if defined(_MSC_VER) && _MSC_VER >= 1300
# define CRYPTOPP_NOINLINE_DOTDOTDOT
# define CRYPTOPP_NOINLINE __declspec(noinline)
#elif defined(__GNUC__)
# define CRYPTOPP_NOINLINE_DOTDOTDOT
# define CRYPTOPP_NOINLINE __attribute__((noinline))
#else
# define CRYPTOPP_NOINLINE_DOTDOTDOT ...
# define CRYPTOPP_NOINLINE
#endif
// how to declare class constants
#if (defined(_MSC_VER) && _MSC_VER <= 1300) || defined(__INTEL_COMPILER)
# define CRYPTOPP_CONSTANT(x) enum {x};
#else
# define CRYPTOPP_CONSTANT(x) static const int x;
#endif
// Linux provides X32, which is 32-bit integers, longs and pointers on x86_64 using the full x86_64 register set.
// Detect via __ILP32__ (http://wiki.debian.org/X32Port). Both GCC and Clang provide the preprocessor macro.
#if ((__ILP32__ >= 1) || (_ILP32 >= 1))
#define CRYPTOPP_BOOL_X32 1
#else
#define CRYPTOPP_BOOL_X32 0
#endif
// see http://predef.sourceforge.net/prearch.html
#if (defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_X86_) || defined(__I86__) || defined(__INTEL__)) && !CRYPTOPP_BOOL_X32
#define CRYPTOPP_BOOL_X86 1
#else
#define CRYPTOPP_BOOL_X86 0
#endif
#if (defined(_M_X64) || defined(__x86_64__)) && !CRYPTOPP_BOOL_X32
#define CRYPTOPP_BOOL_X64 1
#else
#define CRYPTOPP_BOOL_X64 0
#endif
// Undo the ASM and Intrinsic related defines due to X32.
#if CRYPTOPP_BOOL_X32
# undef CRYPTOPP_BOOL_X64
# undef CRYPTOPP_X64_ASM_AVAILABLE
# undef CRYPTOPP_X64_MASM_AVAILABLE
#endif
#if !defined(CRYPTOPP_NO_UNALIGNED_DATA_ACCESS) && !defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS)
#if (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || defined(__powerpc__) || (__ARM_FEATURE_UNALIGNED >= 1))
#define CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
#endif
#endif
// For use in template parameters; also see CRYPTOPP_BOOL_ALIGN16_ENABLED.
#if defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS)
#define CRYPTOPP_BOOL_ALIGN 0
#else
#define CRYPTOPP_BOOL_ALIGN 1
#endif
// ***************** determine availability of OS features ********************
#ifndef NO_OS_DEPENDENCE
#if defined(_WIN32) || defined(__CYGWIN__)
#define CRYPTOPP_WIN32_AVAILABLE
#endif
#if defined(__unix__) || defined(__MACH__) || defined(__NetBSD__) || defined(__sun)
#define CRYPTOPP_UNIX_AVAILABLE
#endif
#if defined(CRYPTOPP_WIN32_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE)
# define HIGHRES_TIMER_AVAILABLE
#endif
#ifdef CRYPTOPP_UNIX_AVAILABLE
# define HAS_BERKELEY_STYLE_SOCKETS
#endif
#ifdef CRYPTOPP_WIN32_AVAILABLE
# define HAS_WINDOWS_STYLE_SOCKETS
#endif
#if defined(HIGHRES_TIMER_AVAILABLE) && (defined(HAS_BERKELEY_STYLE_SOCKETS) || defined(HAS_WINDOWS_STYLE_SOCKETS))
# define SOCKETS_AVAILABLE
#endif
#if defined(HAS_WINDOWS_STYLE_SOCKETS) && (!defined(HAS_BERKELEY_STYLE_SOCKETS) || defined(PREFER_WINDOWS_STYLE_SOCKETS))
# define USE_WINDOWS_STYLE_SOCKETS
#else
# define USE_BERKELEY_STYLE_SOCKETS
#endif
#if defined(HIGHRES_TIMER_AVAILABLE) && defined(CRYPTOPP_WIN32_AVAILABLE) && !defined(USE_BERKELEY_STYLE_SOCKETS)
# define WINDOWS_PIPES_AVAILABLE
#endif
#if defined(CRYPTOPP_WIN32_AVAILABLE) && defined(USE_MS_CRYPTOAPI)
# define NONBLOCKING_RNG_AVAILABLE
# define OS_RNG_AVAILABLE
#endif
#if defined(CRYPTOPP_UNIX_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING)
# define NONBLOCKING_RNG_AVAILABLE
# define BLOCKING_RNG_AVAILABLE
# define OS_RNG_AVAILABLE
# define HAS_PTHREADS
# define THREADS_AVAILABLE
#endif
#ifdef CRYPTOPP_WIN32_AVAILABLE
# define HAS_WINTHREADS
# define THREADS_AVAILABLE
#endif
#endif // NO_OS_DEPENDENCE
// ***************** DLL related ********************
#if defined(CRYPTOPP_WIN32_AVAILABLE) && !defined(CRYPTOPP_DOXYGEN_PROCESSING)
#ifdef CRYPTOPP_EXPORTS
#define CRYPTOPP_IS_DLL
#define CRYPTOPP_DLL __declspec(dllexport)
#elif defined(CRYPTOPP_IMPORTS)
#define CRYPTOPP_IS_DLL
#define CRYPTOPP_DLL __declspec(dllimport)
#else
#define CRYPTOPP_DLL
#endif
#define CRYPTOPP_API __cdecl
#else // CRYPTOPP_WIN32_AVAILABLE
#define CRYPTOPP_DLL
#define CRYPTOPP_API
#endif // CRYPTOPP_WIN32_AVAILABLE
#if defined(__MWERKS__)
#define CRYPTOPP_EXTERN_DLL_TEMPLATE_CLASS extern class CRYPTOPP_DLL
#elif defined(__BORLANDC__) || defined(__SUNPRO_CC)
#define CRYPTOPP_EXTERN_DLL_TEMPLATE_CLASS template class CRYPTOPP_DLL
#else
#define CRYPTOPP_EXTERN_DLL_TEMPLATE_CLASS extern template class CRYPTOPP_DLL
#endif
#if defined(CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES) && !defined(CRYPTOPP_IMPORTS)
#define CRYPTOPP_DLL_TEMPLATE_CLASS template class CRYPTOPP_DLL
#else
#define CRYPTOPP_DLL_TEMPLATE_CLASS CRYPTOPP_EXTERN_DLL_TEMPLATE_CLASS
#endif
#if defined(__MWERKS__)
#define CRYPTOPP_EXTERN_STATIC_TEMPLATE_CLASS extern class
#elif defined(__BORLANDC__) || defined(__SUNPRO_CC)
#define CRYPTOPP_EXTERN_STATIC_TEMPLATE_CLASS template class
#else
#define CRYPTOPP_EXTERN_STATIC_TEMPLATE_CLASS extern template class
#endif
#if defined(CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES) && !defined(CRYPTOPP_EXPORTS)
#define CRYPTOPP_STATIC_TEMPLATE_CLASS template class
#else
#define CRYPTOPP_STATIC_TEMPLATE_CLASS CRYPTOPP_EXTERN_STATIC_TEMPLATE_CLASS
#endif
// ************** Unused variable ***************
// Portable way to suppress warning
#define CRYPTOPP_UNUSED(x) ((void)x)
// ***************** C++11 related ********************
// Visual Studio and C++11 language features began at Visual Studio 2010, https://msdn.microsoft.com/en-us/library/hh567368%28v=vs.110%29.aspx.
// Intel and C++11 language features, https://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler
// GCC and C++11 language features, https://gcc.gnu.org/projects/cxx0x.html
// Clang and C++11 language features, http://clang.llvm.org/cxx_status.html
#if (_MSC_VER >= 1600) || (__cplusplus >= 201103L)
# define CRYPTOPP_CXX11 1
#endif
// Hack ahead. Apple's standard library does not have C++'s unique_ptr in C++11. We can't
// test for unique_ptr directly because some of the non-Apple Clangs on OS X fail the same
// way. However, modern standard libraries have <forward_list>, so we test for it instead.
// Thanks to Jonathan Wakely for devising the clever test for modern/ancient versions.
// TODO: test under Xcode 3, where g++ is really g++.
#if defined(__clang__)
# if !(__has_include(<forward_list>))
# undef CRYPTOPP_CXX11
# endif
#endif
// C++11 or C++14 is available
#if defined(CRYPTOPP_CXX11)
// noexcept: MS at VS2015 (19.00); GCC at 4.6; Clang at 3.0; and Intel 14.0.
#if (_MSC_VER >= 1900) || (__INTEL_COMPILER >= 1400)
# define CRYPTOPP_CXX11_NOEXCEPT 1
#elif defined(__clang__)
# if __has_feature(cxx_noexcept)
# define CRYPTOPP_CXX11_NOEXCEPT 1
# endif
#elif (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
# define CRYPTOPP_CXX11_NOEXCEPT 1
#endif // noexcept compilers
#if defined(CRYPTOPP_CXX11_NOEXCEPT)
# define CRYPTOPP_THROW noexcept(false)
# define CRYPTOPP_NO_THROW noexcept(true)
#else
# define CRYPTOPP_THROW
# define CRYPTOPP_NO_THROW
#endif // CRYPTOPP_CXX11_NOEXCEPT
#endif // CRYPTOPP_CXX11
#if !defined(CRYPTOPP_CXX11_NOEXCEPT)
# define CRYPTOPP_THROW
# define CRYPTOPP_NO_THROW
#endif
// OK to comment the following out, but please report it so we can fix it.
#if (defined(__cplusplus) && (__cplusplus >= 199711L)) && !defined(CRYPTOPP_UNCAUGHT_EXCEPTION_AVAILABLE)
# error "std::uncaught_exception is not available. This is likely a configuration error."
#endif
#endif

93
cpu.cpp
View File

@ -1,6 +1,11 @@
// cpu.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
#ifndef EXCEPTION_EXECUTE_HANDLER
# define EXCEPTION_EXECUTE_HANDLER 1
#endif
#ifndef CRYPTOPP_IMPORTS
@ -23,7 +28,7 @@ NAMESPACE_BEGIN(CryptoPP)
#if _MSC_VER >= 1400 && CRYPTOPP_BOOL_X64
bool CpuId(word32 input, word32 *output)
bool CpuId(word32 input, word32 output[4])
{
__cpuid((int *)output, input);
return true;
@ -33,35 +38,31 @@ bool CpuId(word32 input, word32 *output)
#ifndef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY
extern "C" {
typedef void (*SigHandler)(int);
typedef void (*SigHandler)(int);
static jmp_buf s_jmpNoCPUID;
static jmp_buf s_jmpNoSSE2;
// Declare it so we can attach the attribute
static void SigIllHandlerCPUID(int) CRYPTOPP_UNUSED_FUNCTION;
static void SigIllHandlerCPUID(int)
{
longjmp(s_jmpNoCPUID, 1);
}
// Declare it so we can attach the attribute
static void SigIllHandlerSSE2(int) CRYPTOPP_UNUSED_FUNCTION;
static void SigIllHandlerSSE2(int)
{
longjmp(s_jmpNoSSE2, 1);
}
}
#endif // CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY
bool CpuId(word32 input, word32 *output)
static jmp_buf s_jmpNoCPUID;
static void SigIllHandlerCPUID(int)
{
#ifdef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY
longjmp(s_jmpNoCPUID, 1);
}
static jmp_buf s_jmpNoSSE2;
static void SigIllHandlerSSE2(int)
{
longjmp(s_jmpNoSSE2, 1);
}
}
#endif
bool CpuId(word32 input, word32 output[4])
{
#if defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY)
__try
{
__asm
{
mov eax, input
mov ecx, 0
cpuid
mov edi, output
mov [edi], eax
@ -70,10 +71,16 @@ bool CpuId(word32 input, word32 *output)
mov [edi+12], edx
}
}
__except (1)
// GetExceptionCode() == EXCEPTION_ILLEGAL_INSTRUCTION
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
// function 0 returns the highest basic function understood in EAX
if(input == 0)
return !!output[0];
return true;
#else
SigHandler oldHandler = signal(SIGILL, SigIllHandlerCPUID);
@ -85,16 +92,17 @@ bool CpuId(word32 input, word32 *output)
result = false;
else
{
asm
asm volatile
(
// save ebx in case -fPIC is being used
#if CRYPTOPP_BOOL_X86
"push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
#else
// TODO: this might need an early clobber on EDI.
# if CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64
"pushq %%rbx; cpuid; mov %%ebx, %%edi; popq %%rbx"
#endif
# else
"push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
# endif
: "=a" (output[0]), "=D" (output[1]), "=c" (output[2]), "=d" (output[3])
: "a" (input)
: "a" (input), "c" (0)
);
}
@ -119,7 +127,8 @@ static bool TrySSE2()
return _mm_cvtsi128_si32(x) == 0;
#endif
}
__except (1)
// GetExceptionCode() == EXCEPTION_ILLEGAL_INSTRUCTION
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
@ -147,11 +156,27 @@ static bool TrySSE2()
#endif
}
#if 0
static bool g_x86DetectionDone = false;
static bool g_hasMMX = false, g_hasISSE = false, g_hasSSE2 = false, g_hasSSSE3 = false, g_hasAESNI = false, g_hasCLMUL = false, g_isP4 = false;
static word32 g_cacheLineSize = CRYPTOPP_L1_CACHE_LINE_SIZE;
#else
bool g_x86DetectionDone = false;
bool g_hasSSE = false, g_hasSSE2 = false, g_hasSSSE3 = false, g_hasMMX = false, g_hasAESNI = false, g_hasCLMUL = false, g_isP4 = false;
bool g_hasMMX = false, g_hasISSE = false, g_hasSSE2 = false, g_hasSSSE3 = false, g_hasAESNI = false, g_hasCLMUL = false, g_isP4 = false;
word32 g_cacheLineSize = CRYPTOPP_L1_CACHE_LINE_SIZE;
#endif
// MacPorts/GCC does not provide constructor(priority). Apple/GCC and Fink/GCC do provide it.
#define HAVE_GCC_CONSTRUCTOR1 (__GNUC__ && (CRYPTOPP_INIT_PRIORITY > 0) && ((CRYPTOPP_GCC_VERSION >= 40300) || (CRYPTOPP_CLANG_VERSION >= 20900) || (_INTEL_COMPILER >= 1000)) && !(MACPORTS_GCC_COMPILER > 0))
#define HAVE_GCC_CONSTRUCTOR0 (__GNUC__ && (CRYPTOPP_INIT_PRIORITY > 0) && !(MACPORTS_GCC_COMPILER > 0))
#if HAVE_GCC_CONSTRUCTOR1
void __attribute__ ((constructor (CRYPTOPP_INIT_PRIORITY + 50))) DetectX86Features()
#elif HAVE_GCC_CONSTRUCTOR0
void __attribute__ ((constructor)) DetectX86Features()
#else
void DetectX86Features()
#endif
{
word32 cpuid[4], cpuid1[4];
if (!CpuId(0, cpuid))
@ -167,7 +192,7 @@ void DetectX86Features()
g_hasCLMUL = g_hasSSE2 && (cpuid1[2] & (1<<1));
if ((cpuid1[3] & (1 << 25)) != 0)
g_hasSSE = true;
g_hasISSE = true;
else
{
word32 cpuid2[4];
@ -175,7 +200,7 @@ void DetectX86Features()
if (cpuid2[0] >= 0x080000001)
{
CpuId(0x080000001, cpuid2);
g_hasSSE = (cpuid2[3] & (1 << 22)) != 0;
g_hasISSE = (cpuid2[3] & (1 << 22)) != 0;
}
}

118
cpu.h
View File

@ -1,6 +1,8 @@
#ifndef CRYPTOPP_CPU_H
#define CRYPTOPP_CPU_H
#include "config.h"
#ifdef CRYPTOPP_GENERATE_X64_MASM
#define CRYPTOPP_X86_ASM_AVAILABLE
@ -10,11 +12,9 @@
#else
#include "config.h"
#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE
#include <emmintrin.h>
#endif
# if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE
# include <emmintrin.h>
# endif
#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE
#if !defined(__GNUC__) || defined(__SSSE3__) || defined(__INTEL_COMPILER)
@ -96,52 +96,56 @@ _mm_aesdeclast_si128 (__m128i a, __m128i b)
NAMESPACE_BEGIN(CryptoPP)
#if CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X64
#if CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64
#define CRYPTOPP_CPUID_AVAILABLE
// these should not be used directly
extern CRYPTOPP_DLL bool g_x86DetectionDone;
extern CRYPTOPP_DLL bool g_hasMMX;
extern CRYPTOPP_DLL bool g_hasISSE;
extern CRYPTOPP_DLL bool g_hasSSE2;
extern CRYPTOPP_DLL bool g_hasSSSE3;
extern CRYPTOPP_DLL bool g_hasAESNI;
extern CRYPTOPP_DLL bool g_hasCLMUL;
extern CRYPTOPP_DLL bool g_isP4;
extern CRYPTOPP_DLL word32 g_cacheLineSize;
CRYPTOPP_DLL void CRYPTOPP_API DetectX86Features();
CRYPTOPP_DLL bool CRYPTOPP_API CpuId(word32 input, word32 *output);
#if CRYPTOPP_BOOL_X64
inline bool HasSSE2() {return true;}
inline bool HasSSE() {return true;}
inline bool HasMMX() {return true;}
#else
extern CRYPTOPP_DLL bool g_hasSSE2;
extern CRYPTOPP_DLL bool g_hasSSE;
extern CRYPTOPP_DLL bool g_hasMMX;
inline bool HasSSE2()
{
if (!g_x86DetectionDone)
DetectX86Features();
return g_hasSSE2;
}
inline bool HasSSE()
{
if (!g_x86DetectionDone)
DetectX86Features();
return g_hasSSE;
}
CRYPTOPP_DLL bool CRYPTOPP_API CpuId(word32 input, word32 output[4]);
inline bool HasMMX()
{
#if CRYPTOPP_BOOL_X64
return true;
#else
if (!g_x86DetectionDone)
DetectX86Features();
return g_hasMMX;
#endif
}
inline bool HasISSE()
{
#if CRYPTOPP_BOOL_X64
return true;
#else
if (!g_x86DetectionDone)
DetectX86Features();
return g_hasISSE;
#endif
}
inline bool HasSSE2()
{
#if CRYPTOPP_BOOL_X64
return true;
#else
if (!g_x86DetectionDone)
DetectX86Features();
return g_hasSSE2;
#endif
}
inline bool HasSSSE3()
{
@ -209,23 +213,6 @@ inline int GetCacheLineSize()
#define ASC(x, y) __asm {x label##y}
#define CRYPTOPP_NAKED __declspec(naked)
#define AS_HEX(y) 0x##y
#elif defined(__clang__) && defined(CRYPTOPP_CLANG_INTEGRATED_ASSEMBLER)
#define CRYPTOPP_GNU_STYLE_INLINE_ASSEMBLY
// define these in two steps to allow arguments to be expanded
#define GNU_AS1(x) "\n\t" #x ";"
#define GNU_AS2(x, y) "\n\t" #x ", " #y ";"
#define GNU_AS3(x, y, z) "\n\t" #x ", " #y ", " #z ";"
#define GNU_ASL(x) "\n\t#x:"
#define GNU_ASJ(x, y, z) "\n\t#x " #y #z ";"
#define AS1(x) GNU_AS1(x)
#define AS2(x, y) GNU_AS2(x, y)
#define AS3(x, y, z) GNU_AS3(x, y, z)
#define ASS(x, y, a, b, c, d) "\n\t" #x ", " #y ", " #a "*64+" #b "*16+" #c "*4+" #d ";"
#define ASL(x) GNU_ASL(x)
#define ASJ(x, y, z) GNU_ASJ(x, y, z)
#define ASC(x, y) "\n\t" #x " " #y ";"
#define CRYPTOPP_NAKED
#define AS_HEX(y) 0x##y
#else
#define CRYPTOPP_GNU_STYLE_INLINE_ASSEMBLY
// define these in two steps to allow arguments to be expanded
@ -245,18 +232,6 @@ inline int GetCacheLineSize()
#define AS_HEX(y) 0x##y
#endif
// https://llvm.org/bugs/show_bug.cgi?id=18916
#if defined(__clang__) && defined(WORKAROUND_LLVM_BUG_18916)
# define GNU_AS_ATT_SYNTAX ".att_syntax;"
# define GNU_AS_INTEL_SYNTAX ".intel_syntax;" "\n"
#elif defined(__GNUC__)
# define GNU_AS_ATT_SYNTAX ".att_syntax prefix;"
# define GNU_AS_INTEL_SYNTAX ".intel_syntax noprefix;"
#else
# define GNU_AS_ATT_SYNTAX ".att_syntax prefix;"
# define GNU_AS_INTEL_SYNTAX ".intel_syntax noprefix;"
#endif
#define IF0(y)
#define IF1(y) y
@ -287,11 +262,31 @@ inline int GetCacheLineSize()
#define AS_REG_7d ebp
#define WORD_SZ 4
#define WORD_REG(x) e##x
#define WORD_REG32(x) e##x
#define WORD_PTR DWORD PTR
#define AS_PUSH_IF86(x) AS1(push e##x)
#define AS_POP_IF86(x) AS1(pop e##x)
#define AS_JCXZ jecxz
#elif CRYPTOPP_BOOL_X32
#define AS_REG_1 ecx
#define AS_REG_2 edx
#define AS_REG_3 r8d
#define AS_REG_4 r9d
#define AS_REG_5 eax
#define AS_REG_6 r10d
#define AS_REG_7 r11d
#define AS_REG_1d ecx
#define AS_REG_2d edx
#define AS_REG_3d r8d
#define AS_REG_4d r9d
#define AS_REG_5d eax
#define AS_REG_6d r10d
#define AS_REG_7d r11d
#define WORD_SZ 4
#define WORD_REG(x) e##x
#define WORD_PTR DWORD PTR
#define AS_PUSH_IF86(x) AS1(push r##x)
#define AS_POP_IF86(x) AS1(pop r##x)
#define AS_JCXZ jecxz
#elif CRYPTOPP_BOOL_X64
#ifdef CRYPTOPP_GENERATE_X64_MASM
#define AS_REG_1 rcx
@ -326,7 +321,6 @@ inline int GetCacheLineSize()
#endif
#define WORD_SZ 8
#define WORD_REG(x) r##x
#define WORD_REG32(x) e##x
#define WORD_PTR QWORD PTR
#define AS_PUSH_IF86(x)
#define AS_POP_IF86(x)

View File

@ -52,7 +52,7 @@ BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
# ADD BASE LINK32 kernel32.lib user32.lib advapi32.lib /nologo /dll /machine:I386
# ADD LINK32 advapi32.lib /nologo /base:"0x42900000" /dll /map /debug /machine:I386 /out:"DLL_Release/cryptopp.dll" /opt:ref
# SUBTRACT LINK32 /pdb:none
# Begin Custom Build
@ -90,7 +90,7 @@ BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
# ADD BASE LINK32 kernel32.lib user32.lib advapi32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
# ADD LINK32 advapi32.lib /nologo /base:"0x42900000" /dll /incremental:no /debug /machine:I386 /out:"DLL_Debug/cryptopp.dll" /opt:ref
# SUBTRACT LINK32 /pdb:none
# Begin Custom Build
@ -591,10 +591,6 @@ SOURCE=.\strciphr.h
# End Source File
# Begin Source File
SOURCE=.\trap.h
# End Source File
# Begin Source File
SOURCE=.\trdlocal.h
# End Source File
# Begin Source File

View File

@ -2,10 +2,9 @@
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="cryptopp"
Name="cryptdll"
ProjectGUID="{EBD86293-69A9-456B-B814-916E12AA9BBF}"
RootNamespace="cryptopp"
SccLocalPath="."
RootNamespace="cryptdll"
>
<Platforms>
<Platform
@ -23,7 +22,6 @@
OutputDirectory="$(PlatformName)\DLL_Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
@ -34,25 +32,13 @@
/>
<Tool
Name="VCCustomBuildTool"
Description="Adding MAC to DLL"
CommandLine="Win32\output\release\cryptest mac_dll &quot;$(TargetPath)&quot;&#x0D;&#x0A;echo mac done &gt; &quot;$(OutDir)&quot;\cryptopp.mac.done&#x0D;&#x0A;"
AdditionalDependencies=""
Outputs="$(OutDir)\cryptopp.mac.done"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\DLL_Release/cryptopp.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/Zm200 "
Optimization="1"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
@ -83,13 +69,15 @@
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="cryptlib.lib"
OutputFile="$(OutDir)\cryptopp.dll"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="$(PlatformName)\DLL_Output\$(ConfigurationName) $(NOINHERIT)"
GenerateDebugInformation="true"
ProgramDatabaseFile="$(TargetDir)cryptopp.pdb"
ProgramDatabaseFile="$(TargetDir)\cryptopp.pdb"
OptimizeReferences="2"
BaseAddress="0x42900000"
ImportLibrary="$(TargetDir)cryptopp.lib"
ImportLibrary="$(TargetDir)\cryptopp.lib"
/>
<Tool
Name="VCALinkTool"
@ -97,9 +85,6 @@
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -118,7 +103,6 @@
OutputDirectory="$(PlatformName)\DLL_Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
@ -129,25 +113,13 @@
/>
<Tool
Name="VCCustomBuildTool"
Description="Adding MAC to DLL"
CommandLine="Win32\output\release\cryptest mac_dll &quot;$(TargetPath)&quot;&#x0D;&#x0A;echo mac done &gt; &quot;$(OutDir)&quot;\cryptopp.mac.done&#x0D;&#x0A;"
AdditionalDependencies=""
Outputs="$(OutDir)\cryptopp.mac.done"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="3"
TypeLibraryName=".\DLL_Release/cryptopp.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/Zm200 "
Optimization="1"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
@ -177,13 +149,15 @@
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="cryptlib.lib"
OutputFile="$(OutDir)\cryptopp.dll"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="$(PlatformName)\DLL_Output\$(ConfigurationName) $(NOINHERIT)"
GenerateDebugInformation="true"
ProgramDatabaseFile="$(TargetDir)cryptopp.pdb"
ProgramDatabaseFile="$(TargetDir)\cryptopp.pdb"
OptimizeReferences="2"
BaseAddress="0x42900000"
ImportLibrary="$(TargetDir)cryptopp.lib"
ImportLibrary="$(TargetDir)\cryptopp.lib"
TargetMachine="17"
/>
<Tool
@ -192,9 +166,6 @@
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -213,35 +184,23 @@
OutputDirectory="$(PlatformName)\DLL_Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
Description="Adding MAC to DLL"
CommandLine="Win32\output\debug\cryptest mac_dll &quot;$(TargetPath)&quot;&#x0D;&#x0A;echo mac done &gt; &quot;$(OutDir)&quot;\cryptopp.mac.done&#x0D;&#x0A;"
AdditionalDependencies=""
Outputs="$(OutDir)\cryptopp.mac.done"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="_DEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\DLL_Debug/cryptopp.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/Zm200 "
Optimization="0"
EnableIntrinsicFunctions="true"
PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS;_USRDLL;CRYPTOPP_EXPORTS;CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2=1;USE_PRECOMPILED_HEADERS"
@ -268,13 +227,15 @@
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="cryptlib.lib"
OutputFile="$(OutDir)\cryptopp.dll"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="$(PlatformName)\DLL_Output\$(ConfigurationName) $(NOINHERIT)"
GenerateDebugInformation="true"
ProgramDatabaseFile="$(TargetDir)cryptopp.pdb"
ProgramDatabaseFile="$(TargetDir)\cryptopp.pdb"
OptimizeReferences="2"
BaseAddress="0x42900000"
ImportLibrary="$(TargetDir)cryptopp.lib"
ImportLibrary="$(TargetDir)\cryptopp.lib"
/>
<Tool
Name="VCALinkTool"
@ -282,9 +243,6 @@
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -303,35 +261,23 @@
OutputDirectory="$(PlatformName)\DLL_Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
Description="Adding MAC to DLL"
CommandLine="Win32\output\debug\cryptest mac_dll &quot;$(TargetPath)&quot;&#x0D;&#x0A;echo mac done &gt; &quot;$(OutDir)&quot;\cryptopp.mac.done&#x0D;&#x0A;"
AdditionalDependencies=""
Outputs="$(OutDir)\cryptopp.mac.done"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="_DEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="3"
TypeLibraryName=".\DLL_Debug/cryptopp.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/Zm200 "
Optimization="0"
EnableIntrinsicFunctions="true"
PreprocessorDefinitions="_DEBUG;WIN32;_WINDOWS;_USRDLL;CRYPTOPP_EXPORTS;CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2=1;USE_PRECOMPILED_HEADERS"
@ -357,13 +303,15 @@
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="cryptlib.lib"
OutputFile="$(OutDir)\cryptopp.dll"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="$(PlatformName)\DLL_Output\$(ConfigurationName) $(NOINHERIT)"
GenerateDebugInformation="true"
ProgramDatabaseFile="$(TargetDir)cryptopp.pdb"
ProgramDatabaseFile="$(TargetDir)\cryptopp.pdb"
OptimizeReferences="2"
BaseAddress="0x42900000"
ImportLibrary="$(TargetDir)cryptopp.lib"
ImportLibrary="$(TargetDir)\cryptopp.lib"
TargetMachine="17"
/>
<Tool
@ -372,9 +320,6 @@
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -2379,21 +2324,37 @@
<File
RelativePath="x64dll.asm"
>
<FileConfiguration
Name="Release|Win32"
ExcludedFromBuild="true"
>
<Tool
Name="VCCustomBuildTool"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|x64"
>
<Tool
Name="VCCustomBuildTool"
CommandLine="ml64.exe /c /nologo /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\x64dll.obj"
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|Win32"
ExcludedFromBuild="true"
>
<Tool
Name="VCCustomBuildTool"
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|x64"
>
<Tool
Name="VCCustomBuildTool"
CommandLine="ml64.exe /c /nologo /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\x64dll.obj"
/>
</FileConfiguration>
@ -2527,6 +2488,10 @@
RelativePath="hex.h"
>
</File>
<File
RelativePath="hkdf.h"
>
</File>
<File
RelativePath="hmac.h"
>
@ -2655,10 +2620,6 @@
RelativePath="strciphr.h"
>
</File>
<File
RelativePath="trap.h"
>
</File>
<File
RelativePath="trdlocal.h"
>

View File

@ -52,7 +52,7 @@ BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /OPT:NOWIN98
# ADD BASE LINK32 kernel32.lib user32.lib advapi32.lib Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /OPT:NOWIN98
# ADD LINK32 Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /out:"DLL_Release/cryptest.exe" /libpath:"DLL_Release" /OPT:NOWIN98 /OPT:REF /OPT:ICF
# SUBTRACT LINK32 /pdb:none /incremental:yes
# Begin Special Build Tool
@ -82,7 +82,7 @@ BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /OPT:NOWIN98
# ADD BASE LINK32 kernel32.lib user32.lib advapi32.lib Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /OPT:NOWIN98
# ADD LINK32 Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /out:"DLL_Debug/cryptest.exe" /pdbtype:sept /libpath:"DLL_Debug" /OPT:NOWIN98
# Begin Special Build Tool
SOURCE="$(InputPath)"
@ -110,7 +110,7 @@ BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
# ADD BASE LINK32 kernel32.lib user32.lib advapi32.lib /nologo /subsystem:console /machine:I386
# ADD LINK32 advapi32.lib Ws2_32.lib /nologo /subsystem:console /map /debug /machine:I386 /OPT:NOWIN98 /OPT:REF /OPT:ICF
# SUBTRACT LINK32 /pdb:none
@ -135,7 +135,7 @@ BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
# ADD BASE LINK32 kernel32.lib user32.lib advapi32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
# ADD LINK32 advapi32.lib Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /OPT:NOWIN98
# SUBTRACT LINK32 /pdb:none
@ -188,10 +188,6 @@ SOURCE=.\test.cpp
# End Source File
# Begin Source File
SOURCE=.\validat0.cpp
# End Source File
# Begin Source File
SOURCE=.\validat1.cpp
# End Source File
# Begin Source File

728
cryptest.sh Executable file
View File

@ -0,0 +1,728 @@
#!/bin/bash
# cryptest.sh - written and placed in public domain by Jeffrey Walton and Uri Blumenthal.
# Copyright assigned to Crypto++ project.
# This is a test script that can be used on some Linux/Unix/Apple machines
# to automate building the library and running the self test with various
# combinations of flags, options, and conditions.
# Everything is tee'd into cryptest-result.txt. Change it to suite your taste.
# You should be able to use `egrep "(error|FAILED)" cryptest-result.txt` to
# quickly find errors and failures.
# Set to suite your taste
TEST_RESULTS=cryptest-result.txt
WARN_TEST_RESULTS=cryptest-warn-result.txt
# Respect user's preferred flags, but filter the stuff we expliclty test
#if [ ! -z "CXXFLAGS" ]; then
# ADD_CXXFLAGS=$(echo "$CXXFLAGS" | sed 's/\(-DDEBUG\|-DNDEBUG\|-O[0-9]\|-Os\|-Og\|-fsanitize=address\|-fsanitize=undefined\|-DDCRYPTOPP_NO_UNALIGNED_DATA_ACCESS\|-DDCRYPTOPP_NO_UNALIGNED_DATA_ACCESS\|-DDCRYPTOPP_NO_BACKWARDS_COMPATIBILITY_562\)//g')
#else\
# ADD_CXXFLAGS=""
#fi
# I can't seem to get the expression to work in sed on Apple. It returns the original CXXFLAGS.
# If you want to test with additional flags, then put them in ADD_CXXFLAGS below.
# ADD_CXXFLAGS="-mrdrnd -mrdseed"
ADD_CXXFLAGS=""
IS_DARWIN=$(uname -s | grep -i -c darwin)
IS_LINUX=$(uname -s | grep -i -c linux)
IS_CYGWIN=$(uname -s | grep -i -c cygwin)
IS_MINGW=$(uname -s | grep -i -c mingw)
IS_OPENBSD=$(uname -s | grep -i -c openbsd)
# We need to use the C++ compiler to determine if c++11 is available. Otherwise
# a mis-detection occurs on Mac OS X 10.9 and above. Below, we use the same
# Implicit Variables as make. Also see
# https://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html
if [ -z "$CXX" ]; then
if [ "$IS_DARWIN" -ne "0" ]; then
CXX=c++
else
# Linux, MinGW, Cygwin and fallback ...
CXX=g++
fi
fi
# Fixup
if [ "$CXX" == "gcc" ]; then
CXX=g++
fi
# Fixup
if [ "$IS_OPENBSD" -ne "0" ]; then
MAKE=gmake
else
MAKE=make
fi
# Use the compiler driver, and not cpp, to tell us if the flag is consumed.
$CXX -x c++ -dM -E -std=c++11 - < /dev/null > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
HAVE_CXX11=1
else
HAVE_CXX11=0
fi
# OpenBSD 5.7 and OS X 10.5 cannot consume -std=c++03
$CXX -x c++ -dM -E -std=c++03 - < /dev/null > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
HAVE_CXX03=1
else
HAVE_CXX03=0
fi
# Set to 0 if you don't have UBsan
$CXX -x c++ -dM -E -fsanitize=undefined -std=c++11 - < /dev/null > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
HAVE_UBSAN=1
else
HAVE_UBSAN=0
fi
# Fixup...
if [ "$IS_CYGWIN" -ne "0" ] || [ "$IS_MINGW" -ne "0" ]; then
HAVE_UBSAN=0
fi
# Set to 0 if you don't have Asan
$CXX -x c++ -dM -E -fsanitize=address -std=c++11 - < /dev/null > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
HAVE_ASAN=1
else
HAVE_ASAN=0
fi
# Fixup...
if [ "$IS_CYGWIN" -ne "0" ] || [ "$IS_MINGW" -ne "0" ]; then
HAVE_ASAN=0
fi
# Set to 0 if you don't have Valgrind. Valgrind tests take a long time...
HAVE_VALGRIND=$(which valgrind 2>&1 | grep -v "no valgrind" | grep -i -c valgrind)
# Echo back to ensure something is not missed.
echo
echo "HAVE_CXX03: $HAVE_CXX03"
echo "HAVE_CXX11: $HAVE_CXX11"
echo "HAVE_ASAN: $HAVE_ASAN"
echo "HAVE_UBSAN: $HAVE_UBSAN"
if [ "$HAVE_VALGRIND" -ne "0" ]; then
echo "HAVE_VALGRIND: $HAVE_VALGRIND"
fi
if [ "$IS_DARWIN" -ne "0" ]; then
echo "IS_DARWIN: $IS_DARWIN"
fi
if [ "$IS_LINUX" -ne "0" ]; then
echo "IS_LINUX: $IS_LINUX"
fi
if [ "$IS_CYGWIN" -ne "0" ]; then
echo "IS_CYGWIN: $IS_CYGWIN"
fi
if [ "$IS_MINGW" -ne "0" ]; then
echo "IS_MINGW: $IS_MINGW"
fi
echo "User CXXFLAGS: $CXXFLAGS"
echo "Retained CXXFLAGS: $ADD_CXXFLAGS"
echo "Compiler:" $($CXX --version | head -1)
# Remove previous test results
rm -f "$TEST_RESULTS" > /dev/null 2>&1
touch "$TEST_RESULTS"
TEST_BEGIN=$(date)
echo
echo "Start time: $TEST_BEGIN"
############################################
############################################
############################################
# Basic debug build
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, default CXXFLAGS" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O2"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Basic release build
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, default CXXFLAGS" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Basic debug build, DISABLE_ASM
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, default CXXFLAGS, DISABLE_ASM" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O2 -DCRYPTOPP_DISABLE_ASM"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Basic release build, DISABLE_ASM
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, default CXXFLAGS, DISABLE_ASM" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -DCRYPTOPP_DISABLE_ASM"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# c++03 debug build
if [ "$HAVE_CXX03" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, c++03" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O2 -std=c++03 $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# c++03 release build
if [ "$HAVE_CXX03" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, c++03" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++03 $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# c++11 debug build
if [ "$HAVE_CXX11" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, c++11" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O2 -std=c++11 $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# c++11 release build
if [ "$HAVE_CXX11" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, c++11" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++11 $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Debug build, all backwards compatibility.
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, MAINTAIN_BACKWARDS_COMPATIBILITY" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O2 -DCRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Release build, all backwards compatibility.
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, MAINTAIN_BACKWARDS_COMPATIBILITY" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -DCRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Debug build, init_priority
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, INIT_PRIORITY" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O1 -DCRYPTOPP_INIT_PRIORITY=250 $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Release build, init_priority
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, INIT_PRIORITY" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -DCRYPTOPP_INIT_PRIORITY=250 $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Release build, no unaligned data access
# This test will not be needed in Crypto++ 5.7 and above
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, NO_UNALIGNED_DATA_ACCESS" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -DCRYPTOPP_NO_UNALIGNED_DATA_ACCESS $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Release build, no backwards compatibility with Crypto++ 5.6.2.
# This test will not be needed in Crypto++ 5.7 and above
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, NO_BACKWARDS_COMPATIBILITY_562" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -DCRYPTOPP_NO_BACKWARDS_COMPATIBILITY_562 $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Debug build, OS Independence
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, NO_OS_DEPENDENCE" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O1 -DNO_OS_DEPENDENCE $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Release build, OS Independence
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, NO_OS_DEPENDENCE" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -DNO_OS_DEPENDENCE $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Debug build at -O3
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, -O3 optimizations" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O3 $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Release build at -O3
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, -O3 optimizations" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O3 $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Debug build at -Os
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, -Os optimizations" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -Os $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Release build at -Os
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, -Os optimizations" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -Os $ADD_CXXFLAGS"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
############################################
# Debug build, UBSan, c++03
if [ "$HAVE_CXX03" -ne "0" ] && [ "$HAVE_UBSAN" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, c++03, UBsan" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O1 -std=c++03 $ADD_CXXFLAGS"
"$MAKE" ubsan | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Release build, UBSan, c++03
if [ "$HAVE_CXX03" -ne "0" ] && [ "$HAVE_UBSAN" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, c++03, UBsan" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++03 $ADD_CXXFLAGS"
"$MAKE" ubsan | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Debug build, Asan, c++03
if [ "$HAVE_CXX03" -ne "0" ] && [ "$HAVE_ASAN" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: debug, c++03, Asan" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O1 -std=c++03 $ADD_CXXFLAGS"
"$MAKE" asan | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Release build, Asan, c++03
if [ "$HAVE_CXX03" -ne "0" ] && [ "$HAVE_ASAN" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: release, c++03, Asan" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++03 $ADD_CXXFLAGS"
"$MAKE" asan | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Release build, UBSan, c++11
if [ "$HAVE_CXX11" -ne "0" ] && [ "$HAVE_UBSAN" -ne "0" ]; then
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: c++11, UBsan" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++11 $ADD_CXXFLAGS"
"$MAKE" ubsan | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Release build, Asan, c++11
if [ "$HAVE_CXX11" -ne "0" ] && [ "$HAVE_ASAN" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: c++11, Asan" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++11 $ADD_CXXFLAGS"
"$MAKE" asan | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
# For Darwin, we need to test both -stdlib=libstdc++ (GNU) and
# -stdlib=libc++ (LLVM) crossed with -std=c++03 and -std=c++11.
############################################
# Darwin, c++03, libc++
if [ "$HAVE_CXX03" -ne "0" ] && [ "$IS_DARWIN" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: Darwin, c++03, libc++ (LLVM)" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++03 -stdlib=libc++ $ADD_CXXFLAGS"
"$MAKE" static cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Darwin, c++03, libstdc++
if [ "$HAVE_CXX03" -ne "0" ] && [ "$IS_DARWIN" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: Darwin, c++03, libstdc++ (GNU)" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++03 -stdlib=libstdc++ $ADD_CXXFLAGS"
"$MAKE" static cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Darwin, c++11, libc++
if [ "$IS_DARWIN" -ne "0" ] && [ "$HAVE_CXX11" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: Darwin, c++11, libc++ (LLVM)" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++11 -stdlib=libc++ $ADD_CXXFLAGS"
"$MAKE" static cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Darwin, c++11, libstdc++
if [ "$IS_DARWIN" -ne "0" ] && [ "$HAVE_CXX11" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: Darwin, c++11, libstdc++ (GNU)" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++11 -stdlib=libstdc++ $ADD_CXXFLAGS"
"$MAKE" static cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
# For Cygwin, we need to test both PREFER_BERKELEY_STYLE_SOCKETS
# and PREFER_WINDOWS_STYLE_SOCKETS
############################################
# MinGW and PREFER_BERKELEY_STYLE_SOCKETS
if [ "$IS_MINGW" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: MinGW, PREFER_BERKELEY_STYLE_SOCKETS" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -DPREFER_BERKELEY_STYLE_SOCKETS -DNO_WINDOWS_STYLE_SOCKETS $ADD_CXXFLAGS"
"$MAKE" static cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# MinGW and PREFER_WINDOWS_STYLE_SOCKETS
if [ "$IS_MINGW" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: MinGW, PREFER_WINDOWS_STYLE_SOCKETS" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -DPREFER_WINDOWS_STYLE_SOCKETS -DNO_BERKELEY_STYLE_SOCKETS $ADD_CXXFLAGS"
"$MAKE" static cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Valgrind, c++03. Requires -O1 for accurate results
if [ "$HAVE_CXX03" -ne "0" ] && [ "$HAVE_VALGRIND" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: Valgrind, c++03" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -std=c++03 -g3 -O1 $ADD_CXXFLAGS"
"$MAKE" static cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
valgrind --track-origins=yes ./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
valgrind --track-origins=yes ./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
# Valgrind, c++11. Requires -O1 for accurate results
if [ "$HAVE_VALGRIND" -ne "0" ] && [ "$HAVE_CXX11" -ne "0" ]; then
echo
echo "************************************" | tee -a "$TEST_RESULTS"
echo "Testing: Valgrind, c++11" | tee -a "$TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -std=c++11 -g3 -O1 $ADD_CXXFLAGS"
"$MAKE" static cryptest.exe 2>&1 | tee -a "$TEST_RESULTS"
valgrind --track-origins=yes ./cryptest.exe v 2>&1 | tee -a "$TEST_RESULTS"
valgrind --track-origins=yes ./cryptest.exe tv all 2>&1 | tee -a "$TEST_RESULTS"
fi
############################################
############################################
if [ "$CXX" == "g++" ] && [ "$HAVE_CXX11" -ne "0" ]; then
############################################
# Basic debug build
echo
echo "************************************" | tee -a "$WARN_TEST_RESULTS"
echo "Testing: debug, c++11, elevated warnings" | tee -a "$WARN_TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DDEBUG -g2 -O2 -std=c++11 -DCRYPTOPP_NO_BACKWARDS_COMPATIBILITY_562 -Wall -Wextra -Wno-unknown-pragmas"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$WARN_TEST_RESULTS"
############################################
# Basic release build
echo
echo "************************************" | tee -a "$WARN_TEST_RESULTS"
echo "Testing: release, c++11, elevated warnings" | tee -a "$WARN_TEST_RESULTS"
echo
unset CXXFLAGS
"$MAKE" clean > /dev/null 2>&1
export CXXFLAGS="-DNDEBUG -g2 -O2 -std=c++11 -DCRYPTOPP_NO_BACKWARDS_COMPATIBILITY_562 -Wall -Wextra -Wno-unknown-pragmas"
"$MAKE" static dynamic cryptest.exe 2>&1 | tee -a "$WARN_TEST_RESULTS"
fi
############################################
############################################
TEST_END=$(date)
echo "************************************************" | tee -a "$TEST_RESULTS"
echo "************************************************" | tee -a "$TEST_RESULTS"
echo | tee -a "$TEST_RESULTS"
echo "Testing started: $TEST_BEGIN" | tee -a "$TEST_RESULTS"
echo "Testing finished: $TEST_END" | tee -a "$TEST_RESULTS"
echo | tee -a "$TEST_RESULTS"
COUNT=$(grep -a "Testing: " cryptest-result.txt | wc -l)
if [ "$COUNT" -eq "0" ]; then
echo "No configurations tested" | tee -a "$TEST_RESULTS"
else
echo "$COUNT configurations tested" | tee -a "$TEST_RESULTS"
fi
echo | tee -a "$TEST_RESULTS"
# "FAILED" is from Crypto++
# "error" is from the sanitizers
# "Illegal", "0 errors" and "suppressed errors" are from Valgrind.
COUNT=$(egrep -a '(error|FAILED|Illegal)' cryptest-result.txt | egrep -v "( 0 errors|suppressed errors|memory error detector)" | wc -l)
if [ "$COUNT" -eq "0" ]; then
echo "No failures detected" | tee -a "$TEST_RESULTS"
else
echo "$COUNT errors detected" | tee -a "$TEST_RESULTS"
echo
egrep -an "(error|FAILED|Illegal)" cryptest-result.txt
fi
echo | tee -a "$TEST_RESULTS"
echo "************************************************" | tee -a "$TEST_RESULTS"
echo "************************************************" | tee -a "$TEST_RESULTS"

View File

@ -1,10 +1,5 @@
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cryptdll", "cryptdll.vcproj", "{EBD86293-69A9-456B-B814-916E12AA9BBF}"
ProjectSection(ProjectDependencies) = postProject
{9EAFA456-89B4-4879-AD4F-C2C341184CF5} = {9EAFA456-89B4-4879-AD4F-C2C341184CF5}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cryptest", "cryptest.vcproj", "{9EAFA456-89B4-4879-AD4F-C2C341184CF5}"
ProjectSection(ProjectDependencies) = postProject
{3423EC9A-52E4-4A4D-9753-EDEBC38785EF} = {3423EC9A-52E4-4A4D-9753-EDEBC38785EF}
@ -14,9 +9,16 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cryptlib", "cryptlib.vcproj
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dlltest", "dlltest.vcproj", "{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}"
ProjectSection(ProjectDependencies) = postProject
{9EAFA456-89B4-4879-AD4F-C2C341184CF5} = {9EAFA456-89B4-4879-AD4F-C2C341184CF5}
{EBD86293-69A9-456B-B814-916E12AA9BBF} = {EBD86293-69A9-456B-B814-916E12AA9BBF}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cryptdll", "cryptdll.vcproj", "{EBD86293-69A9-456B-B814-916E12AA9BBF}"
ProjectSection(ProjectDependencies) = postProject
{9EAFA456-89B4-4879-AD4F-C2C341184CF5} = {9EAFA456-89B4-4879-AD4F-C2C341184CF5}
{3423EC9A-52E4-4A4D-9753-EDEBC38785EF} = {3423EC9A-52E4-4A4D-9753-EDEBC38785EF}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
@ -29,22 +31,6 @@ Global
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Debug|Win32.ActiveCfg = Debug|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Debug|Win32.Build.0 = Debug|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Debug|x64.ActiveCfg = Debug|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Debug|x64.Build.0 = Debug|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Debug|Win32.ActiveCfg = Debug|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Debug|Win32.Build.0 = Debug|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Debug|x64.ActiveCfg = Debug|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Debug|x64.Build.0 = Debug|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Release|Win32.ActiveCfg = Release|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Release|Win32.Build.0 = Release|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Release|x64.ActiveCfg = Release|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Release|x64.Build.0 = Release|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Release|Win32.ActiveCfg = Release|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Release|Win32.Build.0 = Release|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Release|x64.ActiveCfg = Release|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Release|x64.Build.0 = Release|x64
{9EAFA456-89B4-4879-AD4F-C2C341184CF5}.Debug|Win32.ActiveCfg = Debug|Win32
{9EAFA456-89B4-4879-AD4F-C2C341184CF5}.Debug|Win32.Build.0 = Debug|Win32
{9EAFA456-89B4-4879-AD4F-C2C341184CF5}.Debug|x64.ActiveCfg = Debug|x64
@ -78,9 +64,7 @@ Global
{3423EC9A-52E4-4A4D-9753-EDEBC38785EF}.Release|x64.ActiveCfg = Release|x64
{3423EC9A-52E4-4A4D-9753-EDEBC38785EF}.Release|x64.Build.0 = Release|x64
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.Debug|Win32.ActiveCfg = Debug|Win32
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.Debug|Win32.Build.0 = Debug|Win32
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.Debug|x64.ActiveCfg = Debug|x64
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.Debug|x64.Build.0 = Debug|x64
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.DLL-Import Debug|Win32.ActiveCfg = Debug|Win32
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.DLL-Import Debug|Win32.Build.0 = Debug|Win32
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.DLL-Import Debug|x64.ActiveCfg = Debug|x64
@ -90,9 +74,19 @@ Global
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.DLL-Import Release|x64.ActiveCfg = Release|x64
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.DLL-Import Release|x64.Build.0 = Release|x64
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.Release|Win32.ActiveCfg = Release|Win32
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.Release|Win32.Build.0 = Release|Win32
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.Release|x64.ActiveCfg = Release|x64
{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}.Release|x64.Build.0 = Release|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Debug|Win32.ActiveCfg = Debug|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Debug|x64.ActiveCfg = Debug|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Debug|Win32.ActiveCfg = Debug|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Debug|Win32.Build.0 = Debug|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Debug|x64.ActiveCfg = Debug|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Debug|x64.Build.0 = Debug|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Release|Win32.ActiveCfg = Release|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Release|Win32.Build.0 = Release|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Release|x64.ActiveCfg = Release|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.DLL-Import Release|x64.Build.0 = Release|x64
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Release|Win32.ActiveCfg = Release|Win32
{EBD86293-69A9-456B-B814-916E12AA9BBF}.Release|x64.ActiveCfg = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

File diff suppressed because it is too large Load Diff

View File

@ -196,7 +196,6 @@
<FILE FILENAME="dlltest.cpp" CONTAINERID="CCompiler" LOCALCOMMAND="" UNITNAME="dlltest" FORMNAME="" DESIGNCLASS=""/>
<FILE FILENAME="regtest.cpp" CONTAINERID="CCompiler" LOCALCOMMAND="" UNITNAME="regtest" FORMNAME="" DESIGNCLASS=""/>
<FILE FILENAME="test.cpp" CONTAINERID="CCompiler" LOCALCOMMAND="" UNITNAME="test" FORMNAME="" DESIGNCLASS=""/>
<FILE FILENAME="validat0.cpp" CONTAINERID="CCompiler" LOCALCOMMAND="" UNITNAME="validat0" FORMNAME="" DESIGNCLASS=""/>
<FILE FILENAME="validat1.cpp" CONTAINERID="CCompiler" LOCALCOMMAND="" UNITNAME="validat1" FORMNAME="" DESIGNCLASS=""/>
<FILE FILENAME="validat2.cpp" CONTAINERID="CCompiler" LOCALCOMMAND="" UNITNAME="validat2" FORMNAME="" DESIGNCLASS=""/>
<FILE FILENAME="validat3.cpp" CONTAINERID="CCompiler" LOCALCOMMAND="" UNITNAME="validat3" FORMNAME="" DESIGNCLASS=""/>

View File

@ -1,13 +1,22 @@
// cryptlib.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4127 4189 4459)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic ignored "-Wunused-value"
# pragma GCC diagnostic ignored "-Wunused-variable"
# pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#ifndef CRYPTOPP_IMPORTS
#include "cryptlib.h"
#include "misc.h"
#include "stdcpp.h"
#include "smartptr.h"
#include "filters.h"
#include "algparam.h"
#include "fips140.h"
@ -15,13 +24,18 @@
#include "fltrimpl.h"
#include "trdlocal.h"
#include "osrng.h"
#include "trap.h"
#include "secblock.h"
#include "smartptr.h"
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic ignored "-Wunused-value"
# pragma GCC diagnostic ignored "-Wunused-variable"
// http://www.cygwin.com/faq.html#faq.api.winsock
#if (defined(__CYGWIN__) || defined(__CYGWIN32__)) && defined(PREFER_WINDOWS_STYLE_SOCKETS)
# error Cygwin does not support Windows style sockets. See http://www.cygwin.com/faq.html#faq.api.winsock
#endif
// MacPorts/GCC does not provide init_priority(priority). Apple/GCC and Fink/GCC do provide it.
#define HAVE_GCC_INIT_PRIORITY (__GNUC__ && (CRYPTOPP_INIT_PRIORITY > 0) && !(MACPORTS_GCC_COMPILER > 0))
#define HAVE_MSC_INIT_PRIORITY (_MSC_VER && (CRYPTOPP_INIT_PRIORITY > 0))
NAMESPACE_BEGIN(CryptoPP)
CRYPTOPP_COMPILE_ASSERT(sizeof(byte) == 1);
@ -32,17 +46,38 @@ CRYPTOPP_COMPILE_ASSERT(sizeof(word64) == 8);
CRYPTOPP_COMPILE_ASSERT(sizeof(dword) == 2*sizeof(word));
#endif
const std::string DEFAULT_CHANNEL = DefaultChannel();
const std::string AAD_CHANNEL = AadChannel();
#if HAVE_GCC_INIT_PRIORITY
CRYPTOPP_COMPILE_ASSERT(CRYPTOPP_INIT_PRIORITY >= 101);
const std::string DEFAULT_CHANNEL __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 25)));
const std::string AAD_CHANNEL __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 26))) = "AAD";
const std::string &BufferedTransformation::NULL_CHANNEL = DEFAULT_CHANNEL;
#elif HAVE_MSC_INIT_PRIORITY
#pragma warning(disable: 4073)
#pragma init_seg(lib)
const std::string DEFAULT_CHANNEL;
const std::string AAD_CHANNEL = "AAD";
const std::string &BufferedTransformation::NULL_CHANNEL = DEFAULT_CHANNEL;
#pragma warning(default: 4073)
#else
const std::string DEFAULT_CHANNEL;
const std::string AAD_CHANNEL = "AAD";
const std::string &BufferedTransformation::NULL_CHANNEL = DEFAULT_CHANNEL;
#endif
class NullNameValuePairs : public NameValuePairs
{
public:
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const {return false;}
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{CRYPTOPP_UNUSED(name); CRYPTOPP_UNUSED(valueType); CRYPTOPP_UNUSED(pValue); return false;}
};
simple_ptr<NullNameValuePairs> s_pNullNameValuePairs(new NullNameValuePairs);
#if HAVE_GCC_INIT_PRIORITY
const simple_ptr<NullNameValuePairs> s_pNullNameValuePairs __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 30))) = new NullNameValuePairs;
const NameValuePairs &g_nullNameValuePairs = *s_pNullNameValuePairs.m_p;
#else
const simple_ptr<NullNameValuePairs> s_pNullNameValuePairs(new NullNameValuePairs);
const NameValuePairs &g_nullNameValuePairs = *s_pNullNameValuePairs.m_p;
#endif
BufferedTransformation & TheBitBucket()
{
@ -152,7 +187,7 @@ size_t BlockTransformation::AdvancedProcessBlocks(const byte *inBlocks, const by
if (flags & BT_ReverseDirection)
{
CRYPTOPP_ASSERT(length % blockSize == 0);
assert(length % blockSize == 0);
inBlocks += length - blockSize;
xorBlocks += length - blockSize;
outBlocks += length - blockSize;
@ -198,7 +233,7 @@ unsigned int HashTransformation::OptimalDataAlignment() const
void StreamTransformation::ProcessLastBlock(byte *outString, const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(MinLastBlockSize() == 0); // this function should be overriden otherwise
assert(MinLastBlockSize() == 0); // this function should be overriden otherwise
if (length == MandatoryBlockSize())
ProcessData(outString, inString, length);
@ -252,7 +287,7 @@ byte RandomNumberGenerator::GenerateByte()
word32 RandomNumberGenerator::GenerateWord32(word32 min, word32 max)
{
word32 range = max-min;
const word32 range = max-min;
const int maxBits = BitPrecision(range);
word32 value;
@ -266,8 +301,27 @@ word32 RandomNumberGenerator::GenerateWord32(word32 min, word32 max)
return value+min;
}
// Stack recursion below... GenerateIntoBufferedTransformation calls GenerateBlock,
// and GenerateBlock calls GenerateIntoBufferedTransformation. Ad infinitum. Also
// see https://github.com/weidai11/cryptopp/issues/38.
//
// According to Wei, RandomNumberGenerator is an interface, and it should not
// be instantiable. Its now spilt milk, and we are going to assert it in Debug
// builds to alert the programmer and throw in Release builds. Developers have
// a reference implementation in case its needed. If a programmer
// unintentionally lands here, then they should ensure use of a
// RandomNumberGenerator pointer or reference so polymorphism can provide the
// proper runtime dispatching.
void RandomNumberGenerator::GenerateBlock(byte *output, size_t size)
{
CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
#if 0
// This breaks AutoSeededX917RNG<T> generators.
throw NotImplemented("RandomNumberGenerator: GenerateBlock not implemented");
#endif
ArraySink s(output, size);
GenerateIntoBufferedTransformation(s, DEFAULT_CHANNEL, size);
}
@ -284,7 +338,8 @@ void RandomNumberGenerator::GenerateIntoBufferedTransformation(BufferedTransform
{
size_t len = UnsignedMin(buffer.size(), length);
GenerateBlock(buffer, len);
target.ChannelPut(channel, buffer, len);
size_t rem = target.ChannelPut(channel, buffer, len);
CRYPTOPP_UNUSED(rem); assert(rem == 0);
length -= len;
}
}
@ -294,7 +349,11 @@ class ClassNullRNG : public RandomNumberGenerator
{
public:
std::string AlgorithmName() const {return "NullRNG";}
void GenerateBlock(byte *output, size_t size) {throw NotImplemented("NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");}
void GenerateBlock(byte *output, size_t size)
{
CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size);
throw NotImplemented("NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");
}
};
RandomNumberGenerator & NullRNG()
@ -332,19 +391,22 @@ void BufferedTransformation::GetWaitObjects(WaitObjectContainer &container, Call
void BufferedTransformation::Initialize(const NameValuePairs &parameters, int propagation)
{
CRYPTOPP_ASSERT(!AttachedTransformation());
CRYPTOPP_UNUSED(propagation);
assert(!AttachedTransformation());
IsolatedInitialize(parameters);
}
bool BufferedTransformation::Flush(bool hardFlush, int propagation, bool blocking)
{
CRYPTOPP_ASSERT(!AttachedTransformation());
CRYPTOPP_UNUSED(propagation);
assert(!AttachedTransformation());
return IsolatedFlush(hardFlush, blocking);
}
bool BufferedTransformation::MessageSeriesEnd(int propagation, bool blocking)
{
CRYPTOPP_ASSERT(!AttachedTransformation());
CRYPTOPP_UNUSED(propagation);
assert(!AttachedTransformation());
return IsolatedMessageSeriesEnd(blocking);
}
@ -483,7 +545,7 @@ bool BufferedTransformation::GetNextMessage()
return AttachedTransformation()->GetNextMessage();
else
{
CRYPTOPP_ASSERT(!AnyMessages());
assert(!AnyMessages());
return false;
}
}
@ -520,7 +582,7 @@ size_t BufferedTransformation::TransferMessagesTo2(BufferedTransformation &targe
return 1;
bool result = GetNextMessage();
CRYPTOPP_ASSERT(result);
CRYPTOPP_UNUSED(result); assert(result);
}
return 0;
}
@ -551,7 +613,7 @@ size_t BufferedTransformation::TransferAllTo2(BufferedTransformation &target, co
return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
else
{
CRYPTOPP_ASSERT(!NumberOfMessageSeries());
assert(!NumberOfMessageSeries());
unsigned int messageCount;
do
@ -583,7 +645,7 @@ void BufferedTransformation::CopyAllTo(BufferedTransformation &target, const std
AttachedTransformation()->CopyAllTo(target, channel);
else
{
CRYPTOPP_ASSERT(!NumberOfMessageSeries());
assert(!NumberOfMessageSeries());
while (CopyMessagesTo(target, UINT_MAX, channel)) {}
}
}
@ -760,15 +822,13 @@ BufferedTransformation * PK_Decryptor::CreateDecryptionFilter(RandomNumberGenera
size_t PK_Signer::Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
{
using CryptoPP::auto_ptr;
auto_ptr<PK_MessageAccumulator> m(messageAccumulator);
member_ptr<PK_MessageAccumulator> m(messageAccumulator);
return SignAndRestart(rng, *m, signature, false);
}
size_t PK_Signer::SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
{
using CryptoPP::auto_ptr;
auto_ptr<PK_MessageAccumulator> m(NewSignatureAccumulator(rng));
member_ptr<PK_MessageAccumulator> m(NewSignatureAccumulator(rng));
m->Update(message, messageLen);
return SignAndRestart(rng, *m, signature, false);
}
@ -776,8 +836,7 @@ size_t PK_Signer::SignMessage(RandomNumberGenerator &rng, const byte *message, s
size_t PK_Signer::SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const
{
using CryptoPP::auto_ptr;
auto_ptr<PK_MessageAccumulator> m(NewSignatureAccumulator(rng));
member_ptr<PK_MessageAccumulator> m(NewSignatureAccumulator(rng));
InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
return SignAndRestart(rng, *m, signature, false);
@ -785,15 +844,13 @@ size_t PK_Signer::SignMessageWithRecovery(RandomNumberGenerator &rng, const byte
bool PK_Verifier::Verify(PK_MessageAccumulator *messageAccumulator) const
{
using CryptoPP::auto_ptr;
auto_ptr<PK_MessageAccumulator> m(messageAccumulator);
member_ptr<PK_MessageAccumulator> m(messageAccumulator);
return VerifyAndRestart(*m);
}
bool PK_Verifier::VerifyMessage(const byte *message, size_t messageLen, const byte *signature, size_t signatureLength) const
{
using CryptoPP::auto_ptr;
auto_ptr<PK_MessageAccumulator> m(NewVerificationAccumulator());
member_ptr<PK_MessageAccumulator> m(NewVerificationAccumulator());
InputSignature(*m, signature, signatureLength);
m->Update(message, messageLen);
return VerifyAndRestart(*m);
@ -801,8 +858,7 @@ bool PK_Verifier::VerifyMessage(const byte *message, size_t messageLen, const by
DecodingResult PK_Verifier::Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
{
using CryptoPP::auto_ptr;
auto_ptr<PK_MessageAccumulator> m(messageAccumulator);
member_ptr<PK_MessageAccumulator> m(messageAccumulator);
return RecoverAndRestart(recoveredMessage, *m);
}
@ -810,8 +866,7 @@ DecodingResult PK_Verifier::RecoverMessage(byte *recoveredMessage,
const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
const byte *signature, size_t signatureLength) const
{
using CryptoPP::auto_ptr;
auto_ptr<PK_MessageAccumulator> m(NewVerificationAccumulator());
member_ptr<PK_MessageAccumulator> m(NewVerificationAccumulator());
InputSignature(*m, signature, signatureLength);
m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
return RecoverAndRestart(recoveredMessage, *m);

View File

@ -1137,10 +1137,6 @@ SOURCE=.\tiger.h
# End Source File
# Begin Source File
SOURCE=.\trap.h
# End Source File
# Begin Source File
SOURCE=.\trdlocal.h
# End Source File
# Begin Source File

1502
cryptlib.h

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,6 @@
Name="cryptlib"
ProjectGUID="{3423EC9A-52E4-4A4D-9753-EDEBC38785EF}"
RootNamespace="cryptlib"
SccLocalPath="."
>
<Platforms>
<Platform
@ -15,17 +14,15 @@
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Release|Win32"
OutputDirectory="$(PlatformName)\Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
@ -34,15 +31,6 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
@ -56,7 +44,7 @@
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="pch.h"
ProgramDataBaseFileName="$(OutDir)\vc80.pdb"
WarningLevel="3"
WarningLevel="4"
SuppressStartupBanner="true"
DebugInformationFormat="3"
/>
@ -77,9 +65,6 @@
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -95,9 +80,9 @@
OutputDirectory="$(PlatformName)\Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
@ -106,16 +91,6 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
@ -129,7 +104,7 @@
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="pch.h"
ProgramDataBaseFileName="$(OutDir)\vc80.pdb"
WarningLevel="3"
WarningLevel="4"
SuppressStartupBanner="true"
DebugInformationFormat="3"
/>
@ -150,9 +125,6 @@
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -168,9 +140,9 @@
OutputDirectory="$(PlatformName)\DLL_Output\Release"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
@ -179,22 +151,12 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
OmitFramePointers="true"
WholeProgramOptimization="true"
PreprocessorDefinitions="NDEBUG;_WINDOWS;USE_PRECOMPILED_HEADERS;WIN32;CRYPTOPP_IMPORTS"
StringPooling="true"
RuntimeLibrary="0"
@ -202,7 +164,7 @@
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="pch.h"
ProgramDataBaseFileName="$(OutDir)\vc80.pdb"
WarningLevel="3"
WarningLevel="4"
SuppressStartupBanner="true"
DebugInformationFormat="3"
/>
@ -223,9 +185,6 @@
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -241,9 +200,9 @@
OutputDirectory="$(PlatformName)\DLL_Output\Release"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
@ -252,23 +211,12 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
OmitFramePointers="true"
WholeProgramOptimization="true"
PreprocessorDefinitions="NDEBUG;_WINDOWS;USE_PRECOMPILED_HEADERS;WIN32;CRYPTOPP_IMPORTS"
StringPooling="true"
RuntimeLibrary="0"
@ -276,7 +224,7 @@
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="pch.h"
ProgramDataBaseFileName="$(OutDir)\vc80.pdb"
WarningLevel="3"
WarningLevel="4"
SuppressStartupBanner="true"
DebugInformationFormat="3"
/>
@ -297,9 +245,6 @@
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -315,9 +260,10 @@
OutputDirectory="$(PlatformName)\Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
@ -325,15 +271,6 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
@ -344,9 +281,9 @@
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="pch.h"
ProgramDataBaseFileName="$(OutDir)\vc80.pdb"
WarningLevel="3"
WarningLevel="4"
SuppressStartupBanner="true"
DebugInformationFormat="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
@ -365,9 +302,6 @@
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -383,9 +317,10 @@
OutputDirectory="$(PlatformName)\Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
@ -393,16 +328,6 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
@ -412,7 +337,7 @@
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="pch.h"
ProgramDataBaseFileName="$(OutDir)\vc80.pdb"
WarningLevel="3"
WarningLevel="4"
SuppressStartupBanner="true"
DebugInformationFormat="3"
/>
@ -433,9 +358,6 @@
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -451,9 +373,10 @@
OutputDirectory="$(PlatformName)\DLL_Output\Debug"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
@ -461,15 +384,6 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
@ -479,75 +393,7 @@
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="pch.h"
ProgramDataBaseFileName="$(OutDir)\vc80.pdb"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1033"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="DLL-Import Debug|x64"
OutputDirectory="$(PlatformName)\DLL_Output\Debug"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="4"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
EnableIntrinsicFunctions="true"
PreprocessorDefinitions="_DEBUG;_WINDOWS;USE_PRECOMPILED_HEADERS;WIN32;CRYPTOPP_IMPORTS"
RuntimeLibrary="1"
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="pch.h"
ProgramDataBaseFileName="$(OutDir)\vc80.pdb"
WarningLevel="3"
WarningLevel="4"
SuppressStartupBanner="true"
DebugInformationFormat="3"
/>
@ -569,7 +415,60 @@
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="DLL-Import Debug|x64"
OutputDirectory="$(PlatformName)\DLL_Output\Debug"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="4"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
EnableIntrinsicFunctions="true"
PreprocessorDefinitions="_DEBUG;_WINDOWS;USE_PRECOMPILED_HEADERS;WIN32;CRYPTOPP_IMPORTS"
RuntimeLibrary="1"
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="pch.h"
ProgramDataBaseFileName="$(OutDir)\vc80.pdb"
WarningLevel="4"
SuppressStartupBanner="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1033"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCBscMakeTool"
@ -6284,6 +6183,164 @@
/>
</FileConfiguration>
</File>
<File
RelativePath="rdrand.asm"
>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description="Building and assembling rdrand.asm"
CommandLine="ml.exe /c /nologo /D_M_X86 /W3 /Cx /Zi /safeseh /Fo&quot;$(IntDir)\rdrand-x86.obj&quot; &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\rdrand-x86.obj"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|x64"
>
<Tool
Name="VCCustomBuildTool"
Description="Building and assembling rdrand.asm"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Cx /Zi /Fo&quot;$(IntDir)\rdrand-x64.obj&quot; &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\rdrand-x64.obj"
/>
</FileConfiguration>
<FileConfiguration
Name="DLL-Import Release|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description="Building and assembling rdrand.asm"
CommandLine="ml.exe /c /nologo /D_M_X86 /W3 /Cx /Zi /safeseh /Fo&quot;$(IntDir)\rdrand-x86.obj&quot; &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\rdrand-x86.obj"
/>
</FileConfiguration>
<FileConfiguration
Name="DLL-Import Release|x64"
>
<Tool
Name="VCCustomBuildTool"
Description="Building and assembling rdrand.asm"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Cx /Zi /Fo&quot;$(IntDir)\rdrand-x64.obj&quot; &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\rdrand-x64.obj"
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description="Building and assembling rdrand.asm"
CommandLine="ml.exe /c /nologo /D_M_X86 /W3 /Cx /Zi /safeseh /Fo&quot;$(IntDir)\rdrand-x86.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\rdrand-x86.obj"
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|x64"
>
<Tool
Name="VCCustomBuildTool"
Description="Building and assembling rdrand.asm"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Cx /Zi /Fo&quot;$(IntDir)\rdrand-x64.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\rdrand-x64.obj"
/>
</FileConfiguration>
<FileConfiguration
Name="DLL-Import Debug|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description="Building and assembling rdrand.asm"
CommandLine="ml.exe /c /nologo /D_M_X86 /W3 /Cx /Zi /safeseh /Fo&quot;$(IntDir)\rdrand-x86.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\rdrand-x86.obj"
/>
</FileConfiguration>
<FileConfiguration
Name="DLL-Import Debug|x64"
>
<Tool
Name="VCCustomBuildTool"
Description="Building and assembling rdrand.asm"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Cx /Zi /Fo&quot;$(IntDir)\rdrand-x64.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\rdrand-x64.obj"
/>
</FileConfiguration>
</File>
<File
RelativePath="rdrand.cpp"
>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Release|x64"
>
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="DLL-Import Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="DLL-Import Release|x64"
>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|x64"
>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="DLL-Import Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="DLL-Import Debug|x64"
>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions=""
/>
</FileConfiguration>
</File>
<File
RelativePath="rdtables.cpp"
>
@ -8540,7 +8597,7 @@
>
<Tool
Name="VCCustomBuildTool"
CommandLine="ml64.exe /c /nologo /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\x64dll.obj"
/>
</FileConfiguration>
@ -8558,7 +8615,7 @@
>
<Tool
Name="VCCustomBuildTool"
CommandLine="ml64.exe /c /nologo /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\x64dll.obj"
/>
</FileConfiguration>
@ -8575,7 +8632,7 @@
>
<Tool
Name="VCCustomBuildTool"
CommandLine="ml64.exe /c /nologo /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\x64dll.obj"
/>
</FileConfiguration>
@ -8593,7 +8650,7 @@
>
<Tool
Name="VCCustomBuildTool"
CommandLine="ml64.exe /c /nologo /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Fo&quot;$(IntDir)\x64dll.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\x64dll.obj"
/>
</FileConfiguration>
@ -8614,7 +8671,7 @@
>
<Tool
Name="VCCustomBuildTool"
CommandLine="ml64.exe /c /nologo /Fo&quot;$(IntDir)\x64masm.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Fo&quot;$(IntDir)\x64masm.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\x64masm.obj"
/>
</FileConfiguration>
@ -8631,7 +8688,7 @@
>
<Tool
Name="VCCustomBuildTool"
CommandLine="ml64.exe /c /nologo /Fo&quot;$(IntDir)\x64masm.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Fo&quot;$(IntDir)\x64masm.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\x64masm.obj"
/>
</FileConfiguration>
@ -8648,7 +8705,7 @@
>
<Tool
Name="VCCustomBuildTool"
CommandLine="ml64.exe /c /nologo /Fo&quot;$(IntDir)\x64masm.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Fo&quot;$(IntDir)\x64masm.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\x64masm.obj"
/>
</FileConfiguration>
@ -8665,7 +8722,7 @@
>
<Tool
Name="VCCustomBuildTool"
CommandLine="ml64.exe /c /nologo /Fo&quot;$(IntDir)\x64masm.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
CommandLine="ml64.exe /c /nologo /D_M_X64 /W3 /Fo&quot;$(IntDir)\x64masm.obj&quot; /Zi &quot;$(InputPath)&quot;&#x0D;&#x0A;"
Outputs="$(IntDir)\x64masm.obj"
/>
</FileConfiguration>
@ -9245,6 +9302,10 @@
RelativePath="hex.h"
>
</File>
<File
RelativePath="hkdf.h"
>
</File>
<File
RelativePath="hmac.h"
>
@ -9397,6 +9458,10 @@
RelativePath="rc6.h"
>
</File>
<File
RelativePath="rdrand.h"
>
</File>
<File
RelativePath="rijndael.h"
>
@ -9501,10 +9566,6 @@
RelativePath="tiger.h"
>
</File>
<File
RelativePath="trap.h"
>
</File>
<File
RelativePath="trdlocal.h"
>

View File

@ -27,8 +27,8 @@ LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 5,6,2,0
PRODUCTVERSION 5,6,2,0
FILEVERSION 5,6,3,0
PRODUCTVERSION 5,6,3,0
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
@ -46,13 +46,13 @@ BEGIN
VALUE "Comments", "free crypto library, more information available at www.cryptopp.com"
VALUE "CompanyName", "Wei Dai"
VALUE "FileDescription", "Crypto++® Library DLL"
VALUE "FileVersion", "5, 6, 2, 0"
VALUE "FileVersion", "5, 6, 3, 0"
VALUE "InternalName", "cryptopp"
VALUE "LegalCopyright", "Copyright © 1995-2013 by Wei Dai"
VALUE "LegalCopyright", "Copyright © 1995-2015 by Wei Dai"
VALUE "LegalTrademarks", "Crypto++®"
VALUE "OriginalFilename", "cryptopp.dll"
VALUE "ProductName", "Crypto++® Library"
VALUE "ProductVersion", "5, 6, 2, 0"
VALUE "ProductVersion", "5, 6, 3, 0"
END
END
BLOCK "VarFileInfo"

View File

@ -1,25 +1,33 @@
// datatest.cpp - written and placed in public domain by Wei Dai
// datatest.cpp - written and placed in the public domain by Wei Dai
#include "config.h"
#include "stdcpp.h"
#include "smartptr.h"
#include "integer.h"
#define CRYPTOPP_DEFAULT_NO_DLL
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include "cryptlib.h"
#include "factory.h"
#include "integer.h"
#include "filters.h"
#include "hex.h"
#include "randpool.h"
#include "files.h"
#include "trunhash.h"
#include "queue.h"
#include "smartptr.h"
#include "validate.h"
#include "trap.h"
#include "hkdf.h"
#include "stdcpp.h"
#include <iostream>
// Aggressive stack checking with VS2005 SP1 and above.
#if (CRYPTOPP_MSC_VERSION >= 1410)
# pragma strict_gs_check (on)
#endif
USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)
typedef std::map<std::string, std::string> TestData;
static bool s_thorough;
static bool s_thorough = false;
class TestFailure : public Exception
{
@ -33,7 +41,7 @@ static void OutputTestData(const TestData &v)
{
for (TestData::const_iterator i = v.begin(); i != v.end(); ++i)
{
std::cerr << i->first << ": " << i->second << std::endl;
cerr << i->first << ": " << i->second << endl;
}
}
@ -63,7 +71,7 @@ const std::string & GetRequiredDatum(const TestData &data, const char *name)
return i->second;
}
void RandomizedTransfer(BufferedTransformation &source, BufferedTransformation &target, bool finish, const std::string &channel=DefaultChannel())
void RandomizedTransfer(BufferedTransformation &source, BufferedTransformation &target, bool finish, const std::string &channel=DEFAULT_CHANNEL)
{
while (source.MaxRetrievable() > (finish ? 0 : 4096))
{
@ -192,9 +200,10 @@ private:
void TestKeyPairValidAndConsistent(CryptoMaterial &pub, const CryptoMaterial &priv)
{
if (!pub.Validate(GlobalRNG(), 2+s_thorough))
// "!!" converts between bool <-> integral.
if (!pub.Validate(GlobalRNG(), 2U+!!s_thorough))
SignalTestFailure();
if (!priv.Validate(GlobalRNG(), 2+s_thorough))
if (!priv.Validate(GlobalRNG(), 2U+!!s_thorough))
SignalTestFailure();
ByteQueue bq1, bq2;
@ -210,8 +219,8 @@ void TestSignatureScheme(TestData &v)
std::string name = GetRequiredDatum(v, "Name");
std::string test = GetRequiredDatum(v, "Test");
auto_ptr<PK_Signer> signer(ObjectFactoryRegistry<PK_Signer>::Registry().CreateObject(name.c_str()));
auto_ptr<PK_Verifier> verifier(ObjectFactoryRegistry<PK_Verifier>::Registry().CreateObject(name.c_str()));
member_ptr<PK_Signer> signer(ObjectFactoryRegistry<PK_Signer>::Registry().CreateObject(name.c_str()));
member_ptr<PK_Verifier> verifier(ObjectFactoryRegistry<PK_Verifier>::Registry().CreateObject(name.c_str()));
TestDataNameValuePairs pairs(v);
@ -261,24 +270,24 @@ void TestSignatureScheme(TestData &v)
}
else if (test == "Sign")
{
SignerFilter f(GlobalRNG(), *signer, new HexEncoder(new FileSink(std::cout)));
SignerFilter f(GlobalRNG(), *signer, new HexEncoder(new FileSink(cout)));
StringSource ss(GetDecodedDatum(v, "Message"), true, new Redirector(f));
SignalTestFailure();
}
else if (test == "DeterministicSign")
{
SignalTestError();
CRYPTOPP_ASSERT(false); // TODO: implement
assert(false); // TODO: implement
}
else if (test == "RandomSign")
{
SignalTestError();
CRYPTOPP_ASSERT(false); // TODO: implement
assert(false); // TODO: implement
}
else
{
SignalTestError();
CRYPTOPP_ASSERT(false);
assert(false);
}
}
@ -287,8 +296,8 @@ void TestAsymmetricCipher(TestData &v)
std::string name = GetRequiredDatum(v, "Name");
std::string test = GetRequiredDatum(v, "Test");
auto_ptr<PK_Encryptor> encryptor(ObjectFactoryRegistry<PK_Encryptor>::Registry().CreateObject(name.c_str()));
auto_ptr<PK_Decryptor> decryptor(ObjectFactoryRegistry<PK_Decryptor>::Registry().CreateObject(name.c_str()));
member_ptr<PK_Encryptor> encryptor(ObjectFactoryRegistry<PK_Encryptor>::Registry().CreateObject(name.c_str()));
member_ptr<PK_Decryptor> decryptor(ObjectFactoryRegistry<PK_Decryptor>::Registry().CreateObject(name.c_str()));
std::string keyFormat = GetRequiredDatum(v, "KeyFormat");
@ -318,7 +327,7 @@ void TestAsymmetricCipher(TestData &v)
else
{
SignalTestError();
CRYPTOPP_ASSERT(false);
assert(false);
}
}
@ -416,7 +425,7 @@ void TestSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters)
while (ss.Pump(64)) {}
ss.PumpAll();
for (int i=0; i<z.length(); i++)
CRYPTOPP_ASSERT(encrypted[i] == z[i]);
assert(encrypted[i] == z[i]);
}*/
if (test != "EncryptXorDigest")
ciphertext = GetDecodedDatum(v, "Ciphertext");
@ -494,16 +503,16 @@ void TestAuthenticatedSymmetricCipher(TestData &v, const NameValuePairs &overrid
if (macAtBegin)
RandomizedTransfer(sm, df, true);
sh.CopyTo(df, LWORD_MAX, AadChannel());
sh.CopyTo(df, LWORD_MAX, AAD_CHANNEL);
RandomizedTransfer(sc, df, true);
sf.CopyTo(df, LWORD_MAX, AadChannel());
sf.CopyTo(df, LWORD_MAX, AAD_CHANNEL);
if (!macAtBegin)
RandomizedTransfer(sm, df, true);
df.MessageEnd();
RandomizedTransfer(sh, ef, true, AadChannel());
RandomizedTransfer(sh, ef, true, AAD_CHANNEL);
RandomizedTransfer(sp, ef, true);
RandomizedTransfer(sf, ef, true, AadChannel());
RandomizedTransfer(sf, ef, true, AAD_CHANNEL);
ef.MessageEnd();
if (test == "Encrypt" && encrypted != ciphertext+mac)
@ -581,10 +590,40 @@ void TestDigestOrMAC(TestData &v, bool testDigest)
else
{
SignalTestError();
CRYPTOPP_ASSERT(false);
assert(false);
}
}
void TestKeyDerivationFunction(TestData &v)
{
std::string name = GetRequiredDatum(v, "Name");
std::string test = GetRequiredDatum(v, "Test");
if(test == "Skip") return;
assert(test == "Verify");
std::string key = GetDecodedDatum(v, "Key");
std::string salt = GetDecodedDatum(v, "Salt");
std::string info = GetDecodedDatum(v, "Info");
std::string derived = GetDecodedDatum(v, "DerivedKey");
std::string t = GetDecodedDatum(v, "DerivedLength");
TestDataNameValuePairs pairs(v);
unsigned int length = pairs.GetIntValueWithDefault(Name::DerivedLength(), (int)derived.size());
member_ptr<KeyDerivationFunction> kdf;
kdf.reset(ObjectFactoryRegistry<KeyDerivationFunction>::Registry().CreateObject(name.c_str()));
std::string calc; calc.resize(length);
unsigned int ret = kdf->DeriveKey(reinterpret_cast<byte*>(&calc[0]), calc.size(),
reinterpret_cast<const byte*>(key.data()), key.size(),
reinterpret_cast<const byte*>(salt.data()), salt.size(),
reinterpret_cast<const byte*>(info.data()), info.size());
if(calc != derived || ret != length)
SignalTestFailure();
}
bool GetField(std::istream &is, std::string &name, std::string &value)
{
name.resize(0); // GCC workaround: 2.95.3 doesn't have clear()
@ -595,7 +634,7 @@ bool GetField(std::istream &is, std::string &name, std::string &value)
if (name[name.size()-1] != ':')
{
char c;
is >> std::skipws >> c;
is >> skipws >> c;
if (c != ':')
SignalTestError();
}
@ -645,26 +684,26 @@ void OutputPair(const NameValuePairs &v, const char *name)
{
Integer x;
bool b = v.GetValue(name, x);
CRYPTOPP_ASSERT(b); CRYPTOPP_UNUSED(b);
std::cout << name << ": \\\n ";
x.Encode(HexEncoder(new FileSink(std::cout), false, 64, "\\\n ").Ref(), x.MinEncodedSize());
std::cout << std::endl;
CRYPTOPP_UNUSED(b); assert(b);
cout << name << ": \\\n ";
x.Encode(HexEncoder(new FileSink(cout), false, 64, "\\\n ").Ref(), x.MinEncodedSize());
cout << endl;
}
void OutputNameValuePairs(const NameValuePairs &v)
{
std::string names = v.GetValueNames();
std::string::size_type i = 0;
string::size_type i = 0;
while (i < names.size())
{
std::string::size_type j = names.find_first_of (';', i);
string::size_type j = names.find_first_of (';', i);
if (j == std::string::npos)
if (j == string::npos)
return;
else
{
std::string name = names.substr(i, j-i);
if (name.find(':') == std::string::npos)
if (name.find(':') == string::npos)
OutputPair(v, name.c_str());
}
@ -684,7 +723,7 @@ void TestDataFile(const std::string &filename, const NameValuePairs &overridePar
while (file)
{
while (file.peek() == '#')
file.ignore(INT_MAX, '\n');
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if (file.peek() == '\n' || file.peek() == '\r')
v.clear();
@ -701,7 +740,7 @@ void TestDataFile(const std::string &filename, const NameValuePairs &overridePar
if (lastAlgName != GetRequiredDatum(v, "Name"))
{
lastAlgName = GetRequiredDatum(v, "Name");
std::cout << "\nTesting " << algType.c_str() << " algorithm " << lastAlgName.c_str() << ".\n";
cout << "\nTesting " << algType.c_str() << " algorithm " << lastAlgName.c_str() << ".\n";
}
try
@ -718,6 +757,8 @@ void TestDataFile(const std::string &filename, const NameValuePairs &overridePar
TestDigestOrMAC(v, true);
else if (algType == "MAC")
TestDigestOrMAC(v, false);
else if (algType == "KDF")
TestKeyDerivationFunction(v);
else if (algType == "FileList")
TestDataFile(GetRequiredDatum(v, "Test"), g_nullNameValuePairs, totalTests, failedTests);
else
@ -726,24 +767,24 @@ void TestDataFile(const std::string &filename, const NameValuePairs &overridePar
}
catch (TestFailure &)
{
std::cout << "\nTest failed.\n";
cout << "\nTest failed.\n";
}
catch (CryptoPP::Exception &e)
{
std::cout << "\nCryptoPP::Exception caught: " << e.what() << std::endl;
cout << "\nCryptoPP::Exception caught: " << e.what() << endl;
}
catch (std::exception &e)
{
std::cout << "\nstd::exception caught: " << e.what() << std::endl;
cout << "\nstd::exception caught: " << e.what() << endl;
}
if (failed)
{
std::cout << "Skipping to next test.\n";
cout << "Skipping to next test.\n";
failedTests++;
}
else
std::cout << "." << std::flush;
cout << "." << flush;
totalTests++;
}
@ -755,8 +796,8 @@ bool RunTestDataFile(const char *filename, const NameValuePairs &overrideParamet
s_thorough = thorough;
unsigned int totalTests = 0, failedTests = 0;
TestDataFile(filename, overrideParameters, totalTests, failedTests);
std::cout << std::dec << "\nTests complete. Total tests = " << totalTests << ". Failed tests = " << failedTests << ".\n";
cout << dec << "\nTests complete. Total tests = " << totalTests << ". Failed tests = " << failedTests << ".\n";
if (failedTests != 0)
std::cout << "SOME TESTS FAILED!\n";
cout << "SOME TESTS FAILED!\n";
return failedTests == 0;
}

View File

@ -1,46 +1,47 @@
// default.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
#include "default.h"
#include "stdcpp.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4127 4189)
#endif
#include "cryptlib.h"
#include "filters.h"
#include "smartptr.h"
#include "default.h"
#include "queue.h"
#include <time.h>
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic ignored "-Wunused-value"
# pragma GCC diagnostic ignored "-Wunused-variable"
#endif
#include <memory>
NAMESPACE_BEGIN(CryptoPP)
static const unsigned int MASH_ITERATIONS = 200;
static const unsigned int SALTLENGTH = 8;
static const unsigned int DIGESTSIZE = DefaultHashModule::DIGESTSIZE;
static const unsigned int BLOCKSIZE = Default_BlockCipher::Encryption::BLOCKSIZE;
static const unsigned int KEYLENGTH = Default_BlockCipher::Encryption::DEFAULT_KEYLENGTH;
// The purpose of this function Mash() is to take an arbitrary length input
// std::string and *deterministicly* produce an arbitrary length output std::string such
// string and *deterministicly* produce an arbitrary length output string such
// that (1) it looks random, (2) no information about the input is
// deducible from it, and (3) it contains as much entropy as it can hold, or
// the amount of entropy in the input std::string, whichever is smaller.
// the amount of entropy in the input string, whichever is smaller.
static void Mash(const byte *in, size_t inLen, byte *out, size_t outLen, int iterations)
{
if (BytePrecision(outLen) > 2)
throw InvalidArgument("Mash: output legnth too large");
size_t bufSize = RoundUpToMultipleOf(outLen, (size_t)DIGESTSIZE);
size_t bufSize = RoundUpToMultipleOf(outLen, (size_t)DefaultHashModule::DIGESTSIZE);
byte b[2];
SecByteBlock buf(bufSize);
SecByteBlock outBuf(bufSize);
DefaultHashModule hash;
unsigned int i;
for(i=0; i<outLen; i+=DIGESTSIZE)
for(i=0; i<outLen; i+=DefaultHashModule::DIGESTSIZE)
{
b[0] = (byte) (i >> 8);
b[1] = (byte) i;
@ -52,7 +53,7 @@ static void Mash(const byte *in, size_t inLen, byte *out, size_t outLen, int ite
while (iterations-- > 1)
{
memcpy(buf, outBuf, bufSize);
for (i=0; i<bufSize; i+=DIGESTSIZE)
for (i=0; i<bufSize; i+=DefaultHashModule::DIGESTSIZE)
{
b[0] = (byte) (i >> 8);
b[1] = (byte) i;
@ -92,10 +93,10 @@ DefaultEncryptor::DefaultEncryptor(const byte *passphrase, size_t passphraseLeng
void DefaultEncryptor::FirstPut(const byte *)
{
// VC60 workaround: __LINE__ expansion bug
CRYPTOPP_COMPILE_ASSERT_INSTANCE(SALTLENGTH <= DIGESTSIZE, 1);
CRYPTOPP_COMPILE_ASSERT_INSTANCE(BLOCKSIZE <= DIGESTSIZE, 2);
CRYPTOPP_COMPILE_ASSERT_INSTANCE(SALTLENGTH <= DefaultHashModule::DIGESTSIZE, 1);
CRYPTOPP_COMPILE_ASSERT_INSTANCE(BLOCKSIZE <= DefaultHashModule::DIGESTSIZE, 2);
SecByteBlock salt(DIGESTSIZE), keyCheck(DIGESTSIZE);
SecByteBlock salt(DefaultHashModule::DIGESTSIZE), keyCheck(DefaultHashModule::DIGESTSIZE);
DefaultHashModule hash;
// use hash(passphrase | time | clock) as salt
@ -126,6 +127,7 @@ void DefaultEncryptor::FirstPut(const byte *)
void DefaultEncryptor::LastPut(const byte *inString, size_t length)
{
CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
m_filter->MessageEnd();
}
@ -154,6 +156,7 @@ void DefaultDecryptor::FirstPut(const byte *inString)
void DefaultDecryptor::LastPut(const byte *inString, size_t length)
{
CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
if (m_filter.get() == NULL)
{
m_state = KEY_BAD;
@ -169,7 +172,7 @@ void DefaultDecryptor::LastPut(const byte *inString, size_t length)
void DefaultDecryptor::CheckKey(const byte *salt, const byte *keyCheck)
{
SecByteBlock check(STDMAX((unsigned int)2*BLOCKSIZE, (unsigned int)DIGESTSIZE));
SecByteBlock check(STDMAX((unsigned int)2*BLOCKSIZE, (unsigned int)DefaultHashModule::DIGESTSIZE));
DefaultHashModule hash;
hash.Update(m_passphrase, m_passphrase.size());
@ -181,7 +184,7 @@ void DefaultDecryptor::CheckKey(const byte *salt, const byte *keyCheck)
GenerateKeyIV(m_passphrase, m_passphrase.size(), salt, SALTLENGTH, key, IV);
m_cipher.SetKeyWithIV(key, key.size(), IV);
auto_ptr<StreamTransformationFilter> decryptor(new StreamTransformationFilter(m_cipher));
member_ptr<StreamTransformationFilter> decryptor(new StreamTransformationFilter(m_cipher));
decryptor->Put(keyCheck, BLOCKSIZE);
decryptor->ForceNextPut();
@ -226,6 +229,7 @@ DefaultEncryptorWithMAC::DefaultEncryptorWithMAC(const byte *passphrase, size_t
void DefaultEncryptorWithMAC::LastPut(const byte *inString, size_t length)
{
CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
m_filter->MessageEnd();
}
@ -259,6 +263,7 @@ bool DefaultDecryptorWithMAC::CheckLastMAC() const
void DefaultDecryptorWithMAC::LastPut(const byte *inString, size_t length)
{
CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
m_filter->MessageEnd();
if (m_throwException && !CheckLastMAC())
throw MACBadErr();

View File

@ -4,8 +4,9 @@
#include "sha.h"
#include "hmac.h"
#include "des.h"
#include "filters.h"
#include "modes.h"
#include "filters.h"
#include "smartptr.h"
NAMESPACE_BEGIN(CryptoPP)
@ -70,7 +71,7 @@ public:
DefaultEncryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULL);
protected:
void FirstPut(const byte *inString) {}
void FirstPut(const byte *inString) {CRYPTOPP_UNUSED(inString);}
void LastPut(const byte *inString, size_t length);
private:
@ -90,7 +91,7 @@ public:
bool CheckLastMAC() const;
protected:
void FirstPut(const byte *inString) {}
void FirstPut(const byte *inString) {CRYPTOPP_UNUSED(inString);}
void LastPut(const byte *inString, size_t length);
private:

14
des.cpp
View File

@ -15,7 +15,6 @@
*/
#include "pch.h"
#include "config.h"
#include "misc.h"
#include "des.h"
@ -274,20 +273,15 @@ static const int bytebit[] = {
/* Set key (initialize key schedule array) */
void RawDES::RawSetKey(CipherDir dir, const byte *key)
{
#if (_MSC_VER >= 1600) || (__cplusplus >= 201103L)
# define register /* Define to nothing for C++11 and above */
#endif
SecByteBlock buffer(56+56+8);
byte *const pc1m=buffer; /* place to modify pc1 into */
byte *const pcr=pc1m+56; /* place to rotate pc1 into */
byte *const ks=pcr+56;
// C++11 deprecated register. Don't pivot on CRYPTOPP_CXX11 because
// configure.h unsets the macro on some Apple platforms if it
// detects an ancient version of the C++ runtime library.
#if (__cplusplus < 201103L)
register int i,j,l;
#else
int i,j,l;
#endif
int m;
for (j=0; j<56; j++) { /* convert pc1 to bits of key */

5
dh.h
View File

@ -4,6 +4,7 @@
/** \file
*/
#include "cryptlib.h"
#include "gfpcrypt.h"
NAMESPACE_BEGIN(CryptoPP)
@ -80,6 +81,10 @@ public:
{return GroupParameters::StaticAlgorithmNamePrefix() + DH_Algorithm::StaticAlgorithmName();}
std::string AlgorithmName() const {return StaticAlgorithmName();}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DH_Domain() {}
#endif
private:
const DL_KeyAgreementAlgorithm<Element> & GetKeyAgreementAlgorithm() const
{return Singleton<DH_Algorithm>().Ref();}

4
dh2.h
View File

@ -49,6 +49,10 @@ public:
const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
bool validateStaticOtherPublicKey=true) const;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DH2() {}
#endif
protected:
SimpleKeyAgreementDomain &d1, &d2;
};

17
dll.cpp
View File

@ -4,8 +4,14 @@
#define CRYPTOPP_DEFAULT_NO_DLL
#include "dll.h"
#include "config.h"
#ifdef _MSC_VER
// TODO: fix the C4589 warnings
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4589)
#endif
#if CRYPTOPP_MSC_VERSION
# pragma warning(default: 4660)
#endif
@ -56,12 +62,15 @@ static PDelete s_pDelete = NULL;
static void * New (size_t size)
{
void *p;
while (!(p = malloc(size)))
while ((p = malloc(size)) == NULL)
CallNewHandler();
return p;
}
// Cast from FARPROC to funcptr with args, http://stackoverflow.com/q/4192058/608639
#pragma warning(disable: 4191)
static void SetNewAndDeleteFunctionPointers()
{
void *p = NULL;
@ -81,7 +90,6 @@ static void SetNewAndDeleteFunctionPointers()
continue;
hModule = HMODULE(mbi.AllocationBase);
PGetNewAndDelete pGetNewAndDelete = (PGetNewAndDelete)GetProcAddress(hModule, "GetNewAndDeleteForCryptoPP");
if (pGetNewAndDelete)
{
@ -123,6 +131,9 @@ static void SetNewAndDeleteFunctionPointers()
throw 0;
}
// Cast from FARPROC to funcptr with args
#pragma warning(default: 4191)
void * operator new (size_t size)
{
if (!s_pNew)

18
dll.h
View File

@ -39,18 +39,16 @@
#ifdef CRYPTOPP_IMPORTS
#if defined(_MSC_VER) && defined(_DLL)
#ifdef _DLL
// cause CRT DLL to be initialized before Crypto++ so that we can use malloc and free during DllMain()
# ifdef NDEBUG
# pragma comment(lib, "msvcrt")
# else
# pragma comment(lib, "msvcrtd")
# endif // NDEBUG
#endif // _MSC_VER and _DLL
#if defined(_MSC_VER)
# pragma comment(lib, "cryptopp")
#ifdef NDEBUG
#pragma comment(lib, "msvcrt")
#else
#pragma comment(lib, "msvcrtd")
#endif
#endif
#pragma comment(lib, "cryptopp")
#endif // #ifdef CRYPTOPP_IMPORTS

View File

@ -1,27 +1,29 @@
#ifndef CRYPTOPP_DLL_ONLY
#define CRYPTOPP_DEFAULT_NO_DLL
# define CRYPTOPP_DEFAULT_NO_DLL
#endif
#include "dll.h"
#include "trap.h"
#include "cryptlib.h"
#include "filters.h"
USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)
void FIPS140_SampleApplication()
{
if (!FIPS_140_2_ComplianceEnabled())
{
std::cerr << "FIPS 140-2 compliance was turned off at compile time.\n";
cerr << "FIPS 140-2 compliance was turned off at compile time.\n";
abort();
}
// check self test status
if (GetPowerUpSelfTestStatus() != POWER_UP_SELF_TEST_PASSED)
{
std::cerr << "Automatic power-up self test failed.\n";
cerr << "Automatic power-up self test failed.\n";
abort();
}
std::cout << "0. Automatic power-up self test passed.\n";
cout << "0. Automatic power-up self test passed.\n";
// simulate a power-up self test error
SimulatePowerUpSelfTestFailure();
@ -31,23 +33,23 @@ void FIPS140_SampleApplication()
AES::Encryption aes;
// should not be here
std::cerr << "Use of AES failed to cause an exception after power-up self test error.\n";
cerr << "Use of AES failed to cause an exception after power-up self test error.\n";
abort();
}
catch (SelfTestFailure &e)
{
std::cout << "1. Caught expected exception when simulating self test failure. Exception message follows: ";
std::cout << e.what() << std::endl;
cout << "1. Caught expected exception when simulating self test failure. Exception message follows: ";
cout << e.what() << endl;
}
// clear the self test error state and redo power-up self test
DoDllPowerUpSelfTest();
if (GetPowerUpSelfTestStatus() != POWER_UP_SELF_TEST_PASSED)
{
std::cerr << "Re-do power-up self test failed.\n";
cerr << "Re-do power-up self test failed.\n";
abort();
}
std::cout << "2. Re-do power-up self test passed.\n";
cout << "2. Re-do power-up self test passed.\n";
// encrypt and decrypt
const byte key[] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef, 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef, 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};
@ -69,10 +71,10 @@ void FIPS140_SampleApplication()
if (memcmp(plaintext, decrypted, 24) != 0)
{
std::cerr << "DES-EDE3-CFB Encryption/decryption failed.\n";
cerr << "DES-EDE3-CFB Encryption/decryption failed.\n";
abort();
}
std::cout << "3. DES-EDE3-CFB Encryption/decryption succeeded.\n";
cout << "3. DES-EDE3-CFB Encryption/decryption succeeded.\n";
// hash
const byte message[] = {'a', 'b', 'c'};
@ -85,10 +87,10 @@ void FIPS140_SampleApplication()
if (memcmp(digest, expectedDigest, 20) != 0)
{
std::cerr << "SHA-1 hash failed.\n";
cerr << "SHA-1 hash failed.\n";
abort();
}
std::cout << "4. SHA-1 hash succeeded.\n";
cout << "4. SHA-1 hash succeeded.\n";
// create auto-seeded X9.17 RNG object, if available
#ifdef OS_RNG_AVAILABLE
@ -105,10 +107,10 @@ void FIPS140_SampleApplication()
dsaPublicKey.AssignFrom(dsaPrivateKey);
if (!dsaPrivateKey.Validate(rng, 3) || !dsaPublicKey.Validate(rng, 3))
{
std::cerr << "DSA key generation failed.\n";
cerr << "DSA key generation failed.\n";
abort();
}
std::cout << "5. DSA key generation succeeded.\n";
cout << "5. DSA key generation succeeded.\n";
// encode DSA key
std::string encodedDsaPublicKey, encodedDsaPrivateKey;
@ -123,34 +125,34 @@ void FIPS140_SampleApplication()
if (!decodedDsaPrivateKey.Validate(rng, 3) || !decodedDsaPublicKey.Validate(rng, 3))
{
std::cerr << "DSA key encode/decode failed.\n";
cerr << "DSA key encode/decode failed.\n";
abort();
}
std::cout << "6. DSA key encode/decode succeeded.\n";
cout << "6. DSA key encode/decode succeeded.\n";
// sign and verify
byte signature[40];
DSA::Signer signer(dsaPrivateKey);
CRYPTOPP_ASSERT(signer.SignatureLength() == 40);
assert(signer.SignatureLength() == 40);
signer.SignMessage(rng, message, 3, signature);
DSA::Verifier verifier(dsaPublicKey);
if (!verifier.VerifyMessage(message, 3, signature, sizeof(signature)))
{
std::cerr << "DSA signature and verification failed.\n";
cerr << "DSA signature and verification failed.\n";
abort();
}
std::cout << "7. DSA signature and verification succeeded.\n";
cout << "7. DSA signature and verification succeeded.\n";
// try to verify an invalid signature
signature[0] ^= 1;
if (verifier.VerifyMessage(message, 3, signature, sizeof(signature)))
{
std::cerr << "DSA signature verification failed to detect bad signature.\n";
cerr << "DSA signature verification failed to detect bad signature.\n";
abort();
}
std::cout << "8. DSA signature verification successfully detected bad signature.\n";
cout << "8. DSA signature verification successfully detected bad signature.\n";
// try to use an invalid key length
try
@ -159,16 +161,16 @@ void FIPS140_SampleApplication()
encryption_DES_EDE3_ECB.SetKey(key, 5);
// should not be here
std::cerr << "DES-EDE3 implementation did not detect use of invalid key length.\n";
cerr << "DES-EDE3 implementation did not detect use of invalid key length.\n";
abort();
}
catch (InvalidArgument &e)
{
std::cout << "9. Caught expected exception when using invalid key length. Exception message follows: ";
std::cout << e.what() << std::endl;
cout << "9. Caught expected exception when using invalid key length. Exception message follows: ";
cout << e.what() << endl;
}
std::cout << "\nFIPS 140-2 Sample Application completed normally.\n";
cout << "\nFIPS 140-2 Sample Application completed normally.\n";
}
#ifdef CRYPTOPP_IMPORTS

View File

@ -49,7 +49,7 @@ BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
# ADD BASE LINK32 kernel32.lib user32.lib advapi32.lib /nologo /subsystem:console /machine:I386
# ADD LINK32 /nologo /subsystem:console /map /debug /machine:I386 /out:"DLL_Release/dlltest.exe" /libpath:"DLL_Release"
!ELSEIF "$(CFG)" == "dlltest - Win32 Debug"
@ -73,7 +73,7 @@ BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
# ADD BASE LINK32 kernel32.lib user32.lib advapi32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
# ADD LINK32 /nologo /subsystem:console /debug /machine:I386 /out:"DLL_Debug/dlltest.exe" /pdbtype:sept /libpath:"DLL_Debug"
!ENDIF

View File

@ -4,7 +4,6 @@
Version="8.00"
Name="dlltest"
ProjectGUID="{A7483CE8-2784-46CE-8CB8-8C0C1D27E232}"
SccLocalPath="."
>
<Platforms>
<Platform
@ -22,7 +21,6 @@
OutputDirectory="$(PlatformName)\DLL_Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="1"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
@ -34,14 +32,6 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TypeLibraryName=".\dlltest___Win32_Release/dlltest.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="1"
@ -72,9 +62,9 @@
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies=""
AdditionalDependencies="cryptopp.lib Ws2_32.lib $(NOINHERIT)"
SuppressStartupBanner="true"
AdditionalLibraryDirectories=""
AdditionalLibraryDirectories="$(PlatformName)\DLL_Output\$(ConfigurationName)"
GenerateDebugInformation="true"
SubSystem="1"
/>
@ -84,9 +74,6 @@
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -105,7 +92,6 @@
OutputDirectory="$(PlatformName)\DLL_Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="1"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
@ -117,15 +103,6 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
TypeLibraryName=".\dlltest___Win32_Release/dlltest.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="1"
@ -155,9 +132,9 @@
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies=""
AdditionalDependencies="cryptopp.lib Ws2_32.lib $(NOINHERIT)"
SuppressStartupBanner="true"
AdditionalLibraryDirectories=""
AdditionalLibraryDirectories="$(PlatformName)\DLL_Output\$(ConfigurationName)"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="17"
@ -168,9 +145,6 @@
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -189,10 +163,10 @@
OutputDirectory="$(PlatformName)\DLL_Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="1"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
@ -200,14 +174,6 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TypeLibraryName=".\dlltest___Win32_Debug/dlltest.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
@ -219,7 +185,7 @@
UsePrecompiledHeader="0"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="4"
DebugInformationFormat="3"
CallingConvention="2"
/>
<Tool
@ -235,9 +201,9 @@
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies=""
AdditionalDependencies="cryptopp.lib Ws2_32.lib $(NOINHERIT)"
SuppressStartupBanner="true"
AdditionalLibraryDirectories=""
AdditionalLibraryDirectories="$(PlatformName)\DLL_Output\$(ConfigurationName)"
GenerateDebugInformation="true"
SubSystem="1"
/>
@ -247,9 +213,6 @@
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
@ -268,10 +231,10 @@
OutputDirectory="$(PlatformName)\DLL_Output\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ProjectName)\$(ConfigurationName)"
ConfigurationType="1"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
@ -279,15 +242,6 @@
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
TypeLibraryName=".\dlltest___Win32_Debug/dlltest.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
@ -314,9 +268,9 @@
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies=""
AdditionalDependencies="cryptopp.lib Ws2_32.lib $(NOINHERIT)"
SuppressStartupBanner="true"
AdditionalLibraryDirectories=""
AdditionalLibraryDirectories="$(PlatformName)\DLL_Output\$(ConfigurationName)"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="17"
@ -327,9 +281,6 @@
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>

View File

@ -5,6 +5,9 @@
#ifndef CRYPTOPP_IMPORTS
#include "dsa.h"
#include "asn.h"
#include "integer.h"
#include "filters.h"
#include "nbtheory.h"
NAMESPACE_BEGIN(CryptoPP)

18
dsa.h
View File

@ -4,9 +4,7 @@
/** \file
*/
#include "config.h"
#include "integer.h"
#include "gfpcrypt.h"
#include "cryptlib.h"
NAMESPACE_BEGIN(CryptoPP)
@ -18,20 +16,6 @@ enum DSASignatureFormat {DSA_P1363, DSA_DER, DSA_OPENPGP};
size_t DSAConvertSignatureFormat(byte *buffer, size_t bufferSize, DSASignatureFormat toFormat,
const byte *signature, size_t signatureLen, DSASignatureFormat fromFormat);
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
typedef DSA::Signer DSAPrivateKey;
typedef DSA::Verifier DSAPublicKey;
const int MIN_DSA_PRIME_LENGTH = DSA::MIN_PRIME_LENGTH;
const int MAX_DSA_PRIME_LENGTH = DSA::MAX_PRIME_LENGTH;
const int DSA_PRIME_LENGTH_MULTIPLE = DSA::PRIME_LENGTH_MULTIPLE;
inline bool GenerateDSAPrimes(const byte *seed, size_t seedLength, int &counter, Integer &p, unsigned int primeLength, Integer &q)
{return DSA::GeneratePrimes(seed, seedLength, counter, p, primeLength, q);}
#endif
NAMESPACE_END
#endif

View File

@ -2,7 +2,6 @@
#include "pch.h"
#include "eax.h"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
@ -35,7 +34,7 @@ size_t EAX_Base::AuthenticateBlocks(const byte *data, size_t len)
void EAX_Base::AuthenticateLastHeaderBlock()
{
CRYPTOPP_ASSERT(m_bufferedDataLength == 0);
assert(m_bufferedDataLength == 0);
MessageAuthenticationCode &mac = AccessMAC();
unsigned int blockSize = mac.TagSize();
@ -49,7 +48,7 @@ void EAX_Base::AuthenticateLastHeaderBlock()
void EAX_Base::AuthenticateLastFooterBlock(byte *tag, size_t macSize)
{
CRYPTOPP_ASSERT(m_bufferedDataLength == 0);
assert(m_bufferedDataLength == 0);
MessageAuthenticationCode &mac = AccessMAC();
unsigned int blockSize = mac.TagSize();

View File

@ -6,10 +6,10 @@
#include "ec2n.h"
#include "asn.h"
#include "integer.h"
#include "filters.h"
#include "algebra.cpp"
#include "eprecomp.cpp"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
@ -71,11 +71,11 @@ bool EC2N::DecodePoint(EC2N::Point &P, BufferedTransformation &bt, size_t encode
}
FieldElement z = m_field->Square(P.x);
CRYPTOPP_ASSERT(P.x == m_field->SquareRoot(z));
assert(P.x == m_field->SquareRoot(z));
P.y = m_field->Divide(m_field->Add(m_field->Multiply(z, m_field->Add(P.x, m_a)), m_b), z);
CRYPTOPP_ASSERT(P.x == m_field->Subtract(m_field->Divide(m_field->Subtract(m_field->Multiply(P.y, z), m_b), z), m_a));
assert(P.x == m_field->Subtract(m_field->Divide(m_field->Subtract(m_field->Multiply(P.y, z), m_b), z), m_a));
z = m_field->SolveQuadraticEquation(P.y);
CRYPTOPP_ASSERT(m_field->Add(m_field->Square(z), z) == P.y);
assert(m_field->Add(m_field->Square(z), z) == P.y);
z.SetCoefficient(0, type & 1);
P.y = m_field->Multiply(z, P.x);
@ -119,7 +119,7 @@ void EC2N::EncodePoint(byte *encodedPoint, const Point &P, bool compressed) cons
{
ArraySink sink(encodedPoint, EncodedPointSize(compressed));
EncodePoint(sink, P, compressed);
CRYPTOPP_ASSERT(sink.TotalPutLength() == EncodedPointSize(compressed));
assert(sink.TotalPutLength() == EncodedPointSize(compressed));
}
EC2N::Point EC2N::BERDecodePoint(BufferedTransformation &bt) const
@ -141,6 +141,7 @@ void EC2N::DEREncodePoint(BufferedTransformation &bt, const Point &P, bool compr
bool EC2N::ValidateParameters(RandomNumberGenerator &rng, unsigned int level) const
{
CRYPTOPP_UNUSED(rng);
bool pass = !!m_b;
pass = pass && m_a.CoefficientCount() <= m_field->MaxElementBitLength();
pass = pass && m_b.CoefficientCount() <= m_field->MaxElementBitLength();
@ -237,11 +238,9 @@ const EC2N::Point& EC2N::Double(const Point &P) const
/*
EcPrecomputation<EC2N>& EcPrecomputation<EC2N>::operator=(const EcPrecomputation<EC2N> &rhs)
{
if (this != &rhs)
{
DL_GroupPrecomputation::operator=(rhs);
m_ec = rhs.m_ec;
}
m_ep = rhs.m_ep;
m_ep.m_group = m_ec.get();
return *this;
}

18
ec2n.h
View File

@ -1,9 +1,9 @@
#ifndef CRYPTOPP_EC2N_H
#define CRYPTOPP_EC2N_H
#include "config.h"
#include "integer.h"
#include "cryptlib.h"
#include "gf2n.h"
#include "integer.h"
#include "eprecomp.h"
#include "smartptr.h"
#include "pubkey.h"
@ -22,6 +22,10 @@ struct CRYPTOPP_DLL EC2NPoint
bool operator< (const EC2NPoint &t) const
{return identity ? !t.identity : (!t.identity && (x<t.x || (x==t.x && y<t.y)));}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~EC2NPoint() {}
#endif
bool identity;
PolynomialMod2 x, y;
};
@ -80,6 +84,10 @@ public:
bool operator==(const EC2N &rhs) const
{return GetField() == rhs.GetField() && m_a == rhs.m_a && m_b == rhs.m_b;}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~EC2N() {}
#endif
private:
clonable_ptr<Field> m_field;
FieldElement m_a, m_b;
@ -102,12 +110,14 @@ public:
Element BERDecodeElement(BufferedTransformation &bt) const {return m_ec.BERDecodePoint(bt);}
void DEREncodeElement(BufferedTransformation &bt, const Element &v) const {m_ec.DEREncodePoint(bt, v, false);}
virtual ~EcPrecomputation() { }
// non-inherited
void SetCurve(const EC2N &ec) {m_ec = ec;}
const EC2N & GetCurve() const {return m_ec;}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~EcPrecomputation() {}
#endif
private:
EC2N m_ec;
};

View File

@ -2,22 +2,31 @@
#include "pch.h"
#include "config.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4127 4189)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#ifndef CRYPTOPP_IMPORTS
#include "eccrypto.h"
#include "stdcpp.h"
#include "smartptr.h"
#include "integer.h"
#include "nbtheory.h"
#include "oids.h"
#include "hex.h"
#include "filters.h"
#include "argnames.h"
#include "smartptr.h"
#include "oids.h"
#include "asn.h"
#include "hex.h"
#include "ec2n.h"
#include "misc.h"
#include "trap.h"
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
NAMESPACE_BEGIN(CryptoPP)
@ -35,7 +44,8 @@ static void ECDSA_TestInstantiations()
}
#endif
static inline Integer ConvertToInteger(const PolynomialMod2 &x)
// VC60 workaround: complains when these functions are put into an anonymous namespace
static Integer ConvertToInteger(const PolynomialMod2 &x)
{
unsigned int l = x.ByteCount();
SecByteBlock temp(l);
@ -120,10 +130,7 @@ struct OIDLessThan
inline bool operator()(const EcRecommendedParameters<T>& a, const EcRecommendedParameters<T>& b) {return a.oid < b.oid;}
};
// Declare it so we can attach the attribute
static void GetRecommendedParameters(const EcRecommendedParameters<EC2N> *&begin, const EcRecommendedParameters<EC2N> *&end) CRYPTOPP_UNUSED_FUNCTION;
void GetRecommendedParameters(const EcRecommendedParameters<EC2N> *&begin, const EcRecommendedParameters<EC2N> *&end)
static void GetRecommendedParameters(const EcRecommendedParameters<EC2N> *&begin, const EcRecommendedParameters<EC2N> *&end)
{
// this array must be sorted by OID
static const EcRecommendedParameters<EC2N> rec[] = {
@ -255,13 +262,10 @@ void GetRecommendedParameters(const EcRecommendedParameters<EC2N> *&begin, const
2),
};
begin = rec;
end = rec + COUNTOF(rec);
end = rec + sizeof(rec)/sizeof(rec[0]);
}
// Declare it so we can attach the unused attribute
static void GetRecommendedParameters(const EcRecommendedParameters<ECP> *&begin, const EcRecommendedParameters<ECP> *&end) CRYPTOPP_UNUSED_FUNCTION;
void GetRecommendedParameters(const EcRecommendedParameters<ECP> *&begin, const EcRecommendedParameters<ECP> *&end)
static void GetRecommendedParameters(const EcRecommendedParameters<ECP> *&begin, const EcRecommendedParameters<ECP> *&end)
{
// this array must be sorted by OID
static const EcRecommendedParameters<ECP> rec[] = {
@ -421,7 +425,7 @@ void GetRecommendedParameters(const EcRecommendedParameters<ECP> *&begin, const
1),
};
begin = rec;
end = rec + COUNTOF(rec);
end = rec + sizeof(rec)/sizeof(rec[0]);
}
template <class EC> OID DL_GroupParameters_EC<EC>::GetNextRecommendedParametersOID(const OID &oid)
@ -442,14 +446,16 @@ template <class EC> void DL_GroupParameters_EC<EC>::Initialize(const OID &oid)
const EcRecommendedParameters<EllipticCurve> &param = *it;
m_oid = oid;
auto_ptr<EllipticCurve> ec(param.NewEC());
member_ptr<EllipticCurve> ec(param.NewEC());
this->m_groupPrecomputation.SetCurve(*ec);
StringSource ssG(param.g, true, new HexDecoder);
Element G;
bool result = GetCurve().DecodePoint(G, ssG, (size_t)ssG.MaxRetrievable());
this->SetSubgroupGenerator(G);
CRYPTOPP_ASSERT(result); CRYPTOPP_UNUSED(result);
// TODO: this fails in practice. Should it throw?
CRYPTOPP_UNUSED(result); assert(result);
StringSource ssN(param.n, true, new HexDecoder);
m_n.Decode(ssN, (size_t)ssN.MaxRetrievable());
@ -499,6 +505,7 @@ void DL_GroupParameters_EC<EC>::GenerateRandom(RandomNumberGenerator &rng, const
{
try
{
CRYPTOPP_UNUSED(rng);
AssignFrom(alg);
}
catch (InvalidArgument &)
@ -639,6 +646,8 @@ OID DL_GroupParameters_EC<EC>::GetAlgorithmID() const
template <class EC>
void DL_PublicKey_EC<EC>::BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size)
{
CRYPTOPP_UNUSED(parametersPresent);
typename EC::Point P;
if (!this->GetGroupParameters().GetCurve().DecodePoint(P, bt, size))
BERDecodeError();
@ -656,6 +665,7 @@ void DL_PublicKey_EC<EC>::DEREncodePublicKey(BufferedTransformation &bt) const
template <class EC>
void DL_PrivateKey_EC<EC>::BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size)
{
CRYPTOPP_UNUSED(size);
BERSequenceDecoder seq(bt);
word32 version;
BERDecodeUnsigned<word32>(seq, version, INTEGER, 1, 1); // check version
@ -696,8 +706,8 @@ void DL_PrivateKey_EC<EC>::DEREncodePrivateKey(BufferedTransformation &bt) const
{
DERSequenceEncoder privateKey(bt);
DEREncodeUnsigned<word32>(privateKey, 1); // version
// TODO: SEC 1 ver 1.0 says privateKey (m_d) has the same length as order of
// the curve this will be changed to order of base point in a future version
// SEC 1 ver 1.0 says privateKey (m_d) has the same length as order of the curve
// this will be changed to order of base point in a future version
this->GetPrivateExponent().DEREncodeAsOctetString(privateKey, this->GetGroupParameters().GetSubgroupOrder().ByteCount());
privateKey.MessageEnd();
}

View File

@ -5,8 +5,9 @@
*/
#include "config.h"
#include "integer.h"
#include "cryptlib.h"
#include "pubkey.h"
#include "integer.h"
#include "asn.h"
#include "hmac.h"
#include "sha.h"
@ -74,7 +75,7 @@ public:
else
element.x.Encode(encoded, GetEncodedElementSize(false));
}
unsigned int GetEncodedElementSize(bool reversible) const
virtual unsigned int GetEncodedElementSize(bool reversible) const
{
if (reversible)
return GetCurve().EncodedPointSize(m_compress);
@ -123,18 +124,22 @@ public:
{return this->m_groupPrecomputation.GetCurve() == rhs.m_groupPrecomputation.GetCurve() && this->m_gpc.GetBase(this->m_groupPrecomputation) == rhs.m_gpc.GetBase(rhs.m_groupPrecomputation);}
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
const Point& GetBasePoint() const {return GetSubgroupGenerator();}
const Integer& GetBasePointOrder() const {return GetSubgroupOrder();}
const Point& GetBasePoint() const {return this->GetSubgroupGenerator();}
const Integer& GetBasePointOrder() const {return this->GetSubgroupOrder();}
void LoadRecommendedParameters(const OID &oid) {Initialize(oid);}
#endif
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_GroupParameters_EC() {}
#endif
protected:
unsigned int FieldElementLength() const {return GetCurve().GetField().MaxElementByteLength();}
unsigned int ExponentLength() const {return m_n.ByteCount();}
OID m_oid; // set if parameters loaded from a recommended curve
Integer m_n; // order of base point
mutable bool m_compress, m_encodeAsOID;
bool m_compress, m_encodeAsOID;
mutable Integer m_k; // cofactor
};
@ -153,6 +158,10 @@ public:
// X509PublicKey
void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
void DEREncodePublicKey(BufferedTransformation &bt) const;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_PublicKey_EC() {}
#endif
};
//! EC private key
@ -174,6 +183,10 @@ public:
// PKCS8PrivateKey
void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
void DEREncodePrivateKey(BufferedTransformation &bt) const;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_PrivateKey_EC() {}
#endif
};
//! Elliptic Curve Diffie-Hellman, AKA <a href="http://www.weidai.com/scan-mirror/ka.html#ECDH">ECDH</a>
@ -181,6 +194,10 @@ template <class EC, class COFACTOR_OPTION = CPP_TYPENAME DL_GroupParameters_EC<E
struct ECDH
{
typedef DH_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECDH() {}
#endif
};
/// Elliptic Curve Menezes-Qu-Vanstone, AKA <a href="http://www.weidai.com/scan-mirror/ka.html#ECMQV">ECMQV</a>
@ -188,6 +205,10 @@ template <class EC, class COFACTOR_OPTION = CPP_TYPENAME DL_GroupParameters_EC<E
struct ECMQV
{
typedef MQV_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECMQV() {}
#endif
};
//! EC keys
@ -196,6 +217,10 @@ struct DL_Keys_EC
{
typedef DL_PublicKey_EC<EC> PublicKey;
typedef DL_PrivateKey_EC<EC> PrivateKey;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Keys_EC() {}
#endif
};
template <class EC, class H>
@ -207,6 +232,10 @@ struct DL_Keys_ECDSA
{
typedef DL_PublicKey_EC<EC> PublicKey;
typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC>, ECDSA<EC, SHA256> > PrivateKey;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Keys_ECDSA() {}
#endif
};
//! ECDSA algorithm
@ -214,8 +243,11 @@ template <class EC>
class DL_Algorithm_ECDSA : public DL_Algorithm_GDSA<typename EC::Point>
{
public:
virtual ~DL_Algorithm_ECDSA() { }
static const char * CRYPTOPP_API StaticAlgorithmName() {return "ECDSA";}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Algorithm_ECDSA() {}
#endif
};
//! ECNR algorithm
@ -223,20 +255,29 @@ template <class EC>
class DL_Algorithm_ECNR : public DL_Algorithm_NR<typename EC::Point>
{
public:
virtual ~DL_Algorithm_ECNR() { }
static const char * CRYPTOPP_API StaticAlgorithmName() {return "ECNR";}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Algorithm_ECNR() {}
#endif
};
//! <a href="http://www.weidai.com/scan-mirror/sig.html#ECDSA">ECDSA</a>
template <class EC, class H>
struct ECDSA : public DL_SS<DL_Keys_ECDSA<EC>, DL_Algorithm_ECDSA<EC>, DL_SignatureMessageEncodingMethod_DSA, H>
{
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECDSA() {}
#endif
};
//! ECNR
template <class EC, class H = SHA>
struct ECNR : public DL_SS<DL_Keys_EC<EC>, DL_Algorithm_ECNR<EC>, DL_SignatureMessageEncodingMethod_NR, H>
{
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECNR() {}
#endif
};
//! Elliptic Curve Integrated Encryption Scheme, AKA <a href="http://www.weidai.com/scan-mirror/ca.html#ECIES">ECIES</a>
@ -253,7 +294,352 @@ struct ECIES
ECIES<EC> >
{
static std::string CRYPTOPP_API StaticAlgorithmName() {return "ECIES";} // TODO: fix this after name is standardized
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECIES() {}
#endif
#if (CRYPTOPP_GCC_VERSION >= 40300) || (CRYPTOPP_CLANG_VERSION >= 20800)
} __attribute__((deprecated ("ECIES will be changing in the near future due to (1) an implementation bug and (2) an interop issue.")));
#elif (CRYPTOPP_GCC_VERSION )
} __attribute__((deprecated));
#else
};
#endif
NAMESPACE_END
#ifdef CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES
#include "eccrypto.cpp"
#endif
NAMESPACE_BEGIN(CryptoPP)
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_EC<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_EC<EC2N>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKeyImpl<DL_GroupParameters_EC<ECP> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKeyImpl<DL_GroupParameters_EC<EC2N> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_EC<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_EC<EC2N>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKeyImpl<DL_GroupParameters_EC<ECP> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKeyImpl<DL_GroupParameters_EC<EC2N> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_EC<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_EC<EC2N>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA<ECP::Point>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA<EC2N::Point>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<ECP>, ECDSA<ECP, SHA256> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC2N>, ECDSA<EC2N, SHA256> >;
NAMESPACE_END
#endif
#ifndef CRYPTOPP_ECCRYPTO_H
#define CRYPTOPP_ECCRYPTO_H
/*! \file
*/
#include "cryptlib.h"
#include "pubkey.h"
#include "integer.h"
#include "asn.h"
#include "hmac.h"
#include "sha.h"
#include "gfpcrypt.h"
#include "dh.h"
#include "mqv.h"
#include "ecp.h"
#include "ec2n.h"
NAMESPACE_BEGIN(CryptoPP)
//! Elliptic Curve Parameters
/*! This class corresponds to the ASN.1 sequence of the same name
in ANSI X9.62 (also SEC 1).
*/
template <class EC>
class DL_GroupParameters_EC : public DL_GroupParametersImpl<EcPrecomputation<EC> >
{
typedef DL_GroupParameters_EC<EC> ThisClass;
public:
typedef EC EllipticCurve;
typedef typename EllipticCurve::Point Point;
typedef Point Element;
typedef IncompatibleCofactorMultiplication DefaultCofactorOption;
DL_GroupParameters_EC() : m_compress(false), m_encodeAsOID(false) {}
DL_GroupParameters_EC(const OID &oid)
: m_compress(false), m_encodeAsOID(false) {Initialize(oid);}
DL_GroupParameters_EC(const EllipticCurve &ec, const Point &G, const Integer &n, const Integer &k = Integer::Zero())
: m_compress(false), m_encodeAsOID(false) {Initialize(ec, G, n, k);}
DL_GroupParameters_EC(BufferedTransformation &bt)
: m_compress(false), m_encodeAsOID(false) {BERDecode(bt);}
void Initialize(const EllipticCurve &ec, const Point &G, const Integer &n, const Integer &k = Integer::Zero())
{
this->m_groupPrecomputation.SetCurve(ec);
this->SetSubgroupGenerator(G);
m_n = n;
m_k = k;
}
void Initialize(const OID &oid);
// NameValuePairs
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
void AssignFrom(const NameValuePairs &source);
// GeneratibleCryptoMaterial interface
//! this implementation doesn't actually generate a curve, it just initializes the parameters with existing values
/*! parameters: (Curve, SubgroupGenerator, SubgroupOrder, Cofactor (optional)), or (GroupOID) */
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg);
// DL_GroupParameters
const DL_FixedBasePrecomputation<Element> & GetBasePrecomputation() const {return this->m_gpc;}
DL_FixedBasePrecomputation<Element> & AccessBasePrecomputation() {return this->m_gpc;}
const Integer & GetSubgroupOrder() const {return m_n;}
Integer GetCofactor() const;
bool ValidateGroup(RandomNumberGenerator &rng, unsigned int level) const;
bool ValidateElement(unsigned int level, const Element &element, const DL_FixedBasePrecomputation<Element> *precomp) const;
bool FastSubgroupCheckAvailable() const {return false;}
void EncodeElement(bool reversible, const Element &element, byte *encoded) const
{
if (reversible)
GetCurve().EncodePoint(encoded, element, m_compress);
else
element.x.Encode(encoded, GetEncodedElementSize(false));
}
virtual unsigned int GetEncodedElementSize(bool reversible) const
{
if (reversible)
return GetCurve().EncodedPointSize(m_compress);
else
return GetCurve().GetField().MaxElementByteLength();
}
Element DecodeElement(const byte *encoded, bool checkForGroupMembership) const
{
Point result;
if (!GetCurve().DecodePoint(result, encoded, GetEncodedElementSize(true)))
throw DL_BadElement();
if (checkForGroupMembership && !ValidateElement(1, result, NULL))
throw DL_BadElement();
return result;
}
Integer ConvertElementToInteger(const Element &element) const;
Integer GetMaxExponent() const {return GetSubgroupOrder()-1;}
bool IsIdentity(const Element &element) const {return element.identity;}
void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
static std::string CRYPTOPP_API StaticAlgorithmNamePrefix() {return "EC";}
// ASN1Key
OID GetAlgorithmID() const;
// used by MQV
Element MultiplyElements(const Element &a, const Element &b) const;
Element CascadeExponentiate(const Element &element1, const Integer &exponent1, const Element &element2, const Integer &exponent2) const;
// non-inherited
// enumerate OIDs for recommended parameters, use OID() to get first one
static OID CRYPTOPP_API GetNextRecommendedParametersOID(const OID &oid);
void BERDecode(BufferedTransformation &bt);
void DEREncode(BufferedTransformation &bt) const;
void SetPointCompression(bool compress) {m_compress = compress;}
bool GetPointCompression() const {return m_compress;}
void SetEncodeAsOID(bool encodeAsOID) {m_encodeAsOID = encodeAsOID;}
bool GetEncodeAsOID() const {return m_encodeAsOID;}
const EllipticCurve& GetCurve() const {return this->m_groupPrecomputation.GetCurve();}
bool operator==(const ThisClass &rhs) const
{return this->m_groupPrecomputation.GetCurve() == rhs.m_groupPrecomputation.GetCurve() && this->m_gpc.GetBase(this->m_groupPrecomputation) == rhs.m_gpc.GetBase(rhs.m_groupPrecomputation);}
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
const Point& GetBasePoint() const {return this->GetSubgroupGenerator();}
const Integer& GetBasePointOrder() const {return this->GetSubgroupOrder();}
void LoadRecommendedParameters(const OID &oid) {Initialize(oid);}
#endif
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_GroupParameters_EC() {}
#endif
protected:
unsigned int FieldElementLength() const {return GetCurve().GetField().MaxElementByteLength();}
unsigned int ExponentLength() const {return m_n.ByteCount();}
OID m_oid; // set if parameters loaded from a recommended curve
Integer m_n; // order of base point
bool m_compress, m_encodeAsOID;
mutable Integer m_k; // cofactor
};
//! EC public key
template <class EC>
class DL_PublicKey_EC : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> >
{
public:
typedef typename EC::Point Element;
void Initialize(const DL_GroupParameters_EC<EC> &params, const Element &Q)
{this->AccessGroupParameters() = params; this->SetPublicElement(Q);}
void Initialize(const EC &ec, const Element &G, const Integer &n, const Element &Q)
{this->AccessGroupParameters().Initialize(ec, G, n); this->SetPublicElement(Q);}
// X509PublicKey
void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
void DEREncodePublicKey(BufferedTransformation &bt) const;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_PublicKey_EC() {}
#endif
};
//! EC private key
template <class EC>
class DL_PrivateKey_EC : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> >
{
public:
typedef typename EC::Point Element;
void Initialize(const DL_GroupParameters_EC<EC> &params, const Integer &x)
{this->AccessGroupParameters() = params; this->SetPrivateExponent(x);}
void Initialize(const EC &ec, const Element &G, const Integer &n, const Integer &x)
{this->AccessGroupParameters().Initialize(ec, G, n); this->SetPrivateExponent(x);}
void Initialize(RandomNumberGenerator &rng, const DL_GroupParameters_EC<EC> &params)
{this->GenerateRandom(rng, params);}
void Initialize(RandomNumberGenerator &rng, const EC &ec, const Element &G, const Integer &n)
{this->GenerateRandom(rng, DL_GroupParameters_EC<EC>(ec, G, n));}
// PKCS8PrivateKey
void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
void DEREncodePrivateKey(BufferedTransformation &bt) const;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_PrivateKey_EC() {}
#endif
};
//! Elliptic Curve Diffie-Hellman, AKA <a href="http://www.weidai.com/scan-mirror/ka.html#ECDH">ECDH</a>
template <class EC, class COFACTOR_OPTION = CPP_TYPENAME DL_GroupParameters_EC<EC>::DefaultCofactorOption>
struct ECDH
{
typedef DH_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECDH() {}
#endif
};
/// Elliptic Curve Menezes-Qu-Vanstone, AKA <a href="http://www.weidai.com/scan-mirror/ka.html#ECMQV">ECMQV</a>
template <class EC, class COFACTOR_OPTION = CPP_TYPENAME DL_GroupParameters_EC<EC>::DefaultCofactorOption>
struct ECMQV
{
typedef MQV_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECMQV() {}
#endif
};
//! EC keys
template <class EC>
struct DL_Keys_EC
{
typedef DL_PublicKey_EC<EC> PublicKey;
typedef DL_PrivateKey_EC<EC> PrivateKey;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Keys_EC() {}
#endif
};
template <class EC, class H>
struct ECDSA;
//! ECDSA keys
template <class EC>
struct DL_Keys_ECDSA
{
typedef DL_PublicKey_EC<EC> PublicKey;
typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC>, ECDSA<EC, SHA256> > PrivateKey;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Keys_ECDSA() {}
#endif
};
//! ECDSA algorithm
template <class EC>
class DL_Algorithm_ECDSA : public DL_Algorithm_GDSA<typename EC::Point>
{
public:
static const char * CRYPTOPP_API StaticAlgorithmName() {return "ECDSA";}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Algorithm_ECDSA() {}
#endif
};
//! ECNR algorithm
template <class EC>
class DL_Algorithm_ECNR : public DL_Algorithm_NR<typename EC::Point>
{
public:
static const char * CRYPTOPP_API StaticAlgorithmName() {return "ECNR";}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Algorithm_ECNR() {}
#endif
};
//! <a href="http://www.weidai.com/scan-mirror/sig.html#ECDSA">ECDSA</a>
template <class EC, class H>
struct ECDSA : public DL_SS<DL_Keys_ECDSA<EC>, DL_Algorithm_ECDSA<EC>, DL_SignatureMessageEncodingMethod_DSA, H>
{
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECDSA() {}
#endif
};
//! ECNR
template <class EC, class H = SHA>
struct ECNR : public DL_SS<DL_Keys_EC<EC>, DL_Algorithm_ECNR<EC>, DL_SignatureMessageEncodingMethod_NR, H>
{
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECNR() {}
#endif
};
//! Elliptic Curve Integrated Encryption Scheme, AKA <a href="http://www.weidai.com/scan-mirror/ca.html#ECIES">ECIES</a>
/*! Default to (NoCofactorMultiplication and DHAES_MODE = false) for compatibilty with SEC1 and Crypto++ 4.2.
The combination of (IncompatibleCofactorMultiplication and DHAES_MODE = true) is recommended for best
efficiency and security. */
template <class EC, class COFACTOR_OPTION = NoCofactorMultiplication, bool DHAES_MODE = false>
struct ECIES
: public DL_ES<
DL_Keys_EC<EC>,
DL_KeyAgreementAlgorithm_DH<typename EC::Point, COFACTOR_OPTION>,
DL_KeyDerivationAlgorithm_P1363<typename EC::Point, DHAES_MODE, P1363_KDF2<SHA1> >,
DL_EncryptionAlgorithm_Xor<HMAC<SHA1>, DHAES_MODE>,
ECIES<EC> >
{
static std::string CRYPTOPP_API StaticAlgorithmName() {return "ECIES";} // TODO: fix this after name is standardized
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECIES() {}
#endif
#if (CRYPTOPP_GCC_VERSION >= 40300) || (CRYPTOPP_CLANG_VERSION >= 20800)
} __attribute__((deprecated ("ECIES will be changing in the near future due to (1) an implementation bug and (2) an interop issue")));
#elif (CRYPTOPP_GCC_VERSION)
} __attribute__((deprecated));
#else
};
#endif
NAMESPACE_END

17
ecp.cpp
View File

@ -6,10 +6,10 @@
#include "ecp.h"
#include "asn.h"
#include "integer.h"
#include "nbtheory.h"
#include "filters.h"
#include "algebra.cpp"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
@ -139,7 +139,7 @@ void ECP::EncodePoint(byte *encodedPoint, const Point &P, bool compressed) const
{
ArraySink sink(encodedPoint, EncodedPointSize(compressed));
EncodePoint(sink, P, compressed);
CRYPTOPP_ASSERT(sink.TotalPutLength() == EncodedPointSize(compressed));
assert(sink.TotalPutLength() == EncodedPointSize(compressed));
}
ECP::Point ECP::BERDecodePoint(BufferedTransformation &bt) const
@ -300,6 +300,7 @@ public:
ProjectiveDoubling(const ModularArithmetic &mr, const Integer &m_a, const Integer &m_b, const ECPPoint &Q)
: mr(mr), firstDoubling(true), negated(false)
{
CRYPTOPP_UNUSED(m_b);
if (Q.identity)
{
sixteenY4 = P.x = P.y = mr.MultiplicativeIdentity();
@ -382,7 +383,7 @@ void ECP::SimultaneousMultiply(ECP::Point *results, const ECP::Point &P, const I
for (i=0; i<expCount; i++)
{
CRYPTOPP_ASSERT(expBegin->NotNegative());
assert(expBegin->NotNegative());
exponents.push_back(WindowSlider(*expBegin++, InversionIsFast(), 5));
exponents[i].FindNextWindow();
}
@ -396,7 +397,7 @@ void ECP::SimultaneousMultiply(ECP::Point *results, const ECP::Point &P, const I
bool baseAdded = false;
for (i=0; i<expCount; i++)
{
if (!exponents[i].m_finished && expBitPosition == exponents[i].m_windowBegin)
if (!exponents[i].finished && expBitPosition == exponents[i].windowBegin)
{
if (!baseAdded)
{
@ -404,13 +405,13 @@ void ECP::SimultaneousMultiply(ECP::Point *results, const ECP::Point &P, const I
baseAdded =true;
}
exponentWindows[i].push_back(exponents[i].m_expWindow);
exponentWindows[i].push_back(exponents[i].expWindow);
baseIndices[i].push_back((word32)bases.size()-1);
negateBase[i].push_back(exponents[i].m_negateNext);
negateBase[i].push_back(exponents[i].negateNext);
exponents[i].FindNextWindow();
}
notDone = notDone || !exponents[i].m_finished;
notDone = notDone || !exponents[i].finished;
}
if (notDone)

16
ecp.h
View File

@ -1,7 +1,7 @@
#ifndef CRYPTOPP_ECP_H
#define CRYPTOPP_ECP_H
#include "config.h"
#include "cryptlib.h"
#include "integer.h"
#include "modarith.h"
#include "eprecomp.h"
@ -22,6 +22,10 @@ struct CRYPTOPP_DLL ECPPoint
bool operator< (const ECPPoint &t) const
{return identity ? !t.identity : (!t.identity && (x<t.x || (x==t.x && y<t.y)));}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECPPoint() {}
#endif
bool identity;
Integer x, y;
};
@ -84,6 +88,10 @@ public:
bool operator==(const ECP &rhs) const
{return GetField() == rhs.GetField() && m_a == rhs.m_a && m_b == rhs.m_b;}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ECP() {}
#endif
private:
clonable_ptr<Field> m_fieldPtr;
FieldElement m_a, m_b;
@ -111,8 +119,6 @@ public:
Element BERDecodeElement(BufferedTransformation &bt) const {return m_ec->BERDecodePoint(bt);}
void DEREncodeElement(BufferedTransformation &bt, const Element &v) const {m_ec->DEREncodePoint(bt, v, false);}
virtual ~EcPrecomputation() { }
// non-inherited
void SetCurve(const ECP &ec)
{
@ -121,6 +127,10 @@ public:
}
const ECP & GetCurve() const {return *m_ecOriginal;}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~EcPrecomputation() {}
#endif
private:
value_ptr<ECP> m_ec, m_ecOriginal;
};

View File

@ -1,10 +1,13 @@
#ifndef CRYPTOPP_ELGAMAL_H
#define CRYPTOPP_ELGAMAL_H
#include "config.h"
#include "integer.h"
#include "cryptlib.h"
#include "modexppc.h"
#include "integer.h"
#include "gfpcrypt.h"
#include "pubkey.h"
#include "dsa.h"
#include "misc.h"
NAMESPACE_BEGIN(CryptoPP)
@ -15,11 +18,13 @@ class CRYPTOPP_NO_VTABLE ElGamalBase : public DL_KeyAgreementAlgorithm_DH<Intege
public:
void Derive(const DL_GroupParameters<Integer> &groupParams, byte *derivedKey, size_t derivedLength, const Integer &agreedElement, const Integer &ephemeralPublicKey, const NameValuePairs &derivationParams) const
{
CRYPTOPP_UNUSED(groupParams), CRYPTOPP_UNUSED(ephemeralPublicKey), CRYPTOPP_UNUSED(derivationParams);
agreedElement.Encode(derivedKey, derivedLength);
}
size_t GetSymmetricKeyLength(size_t plainTextLength) const
{
CRYPTOPP_UNUSED(plainTextLength);
return GetGroupParameters().GetModulus().ByteCount();
}
@ -43,6 +48,7 @@ public:
void SymmetricEncrypt(RandomNumberGenerator &rng, const byte *key, const byte *plainText, size_t plainTextLength, byte *cipherText, const NameValuePairs &parameters) const
{
CRYPTOPP_UNUSED(parameters);
const Integer &p = GetGroupParameters().GetModulus();
unsigned int modulusLen = p.ByteCount();
@ -56,6 +62,7 @@ public:
DecodingResult SymmetricDecrypt(const byte *key, const byte *cipherText, size_t cipherTextLength, byte *plainText, const NameValuePairs &parameters) const
{
CRYPTOPP_UNUSED(parameters);
const Integer &p = GetGroupParameters().GetModulus();
unsigned int modulusLen = p.ByteCount();
@ -74,6 +81,10 @@ public:
}
virtual const DL_GroupParameters_GFP & GetGroupParameters() const =0;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ElGamalBase() {}
#endif
};
template <class BASE, class SCHEME_OPTIONS, class KEY>
@ -88,6 +99,10 @@ public:
DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *cipherText, byte *plainText) const
{return Decrypt(rng, cipherText, FixedCiphertextLength(), plainText);}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~ElGamalObjectImpl() {}
#endif
protected:
const DL_KeyAgreementAlgorithm<Integer> & GetKeyAgreementAlgorithm() const {return *this;}
const DL_KeyDerivationAlgorithm<Integer> & GetKeyDerivationAlgorithm() const {return *this;}

View File

@ -2,18 +2,18 @@
#include "pch.h"
#include "emsa2.h"
#include "trap.h"
#ifndef CRYPTOPP_IMPORTS
NAMESPACE_BEGIN(CryptoPP)
void EMSA2Pad::ComputeMessageRepresentative(RandomNumberGenerator &rng,
const byte *recoverableMessage, size_t recoverableMessageLength,
void EMSA2Pad::ComputeMessageRepresentative(RandomNumberGenerator& /*rng*/,
const byte* recoverableMessage, size_t recoverableMessageLength,
HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
byte *representative, size_t representativeBitLength) const
{
CRYPTOPP_ASSERT(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize()));
CRYPTOPP_UNUSED(recoverableMessage), CRYPTOPP_UNUSED(recoverableMessageLength), CRYPTOPP_UNUSED(representativeBitLength);
assert(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize()));
if (representativeBitLength % 8 != 7)
throw PK_SignatureScheme::InvalidKeyLength("EMSA2: EMSA2 requires a key length that is a multiple of 8");

View File

@ -7,6 +7,7 @@
#include "cryptlib.h"
#include "pubkey.h"
#include "misc.h"
#ifdef CRYPTOPP_IS_DLL
#include "sha.h"
@ -62,7 +63,7 @@ public:
static const char * CRYPTOPP_API StaticAlgorithmName() {return "EMSA2";}
size_t MinRepresentativeBitLength(size_t hashIdentifierLength, size_t digestLength) const
{return 8*digestLength + 31;}
{CRYPTOPP_UNUSED(hashIdentifierLength); return 8*digestLength + 31;}
void ComputeMessageRepresentative(RandomNumberGenerator &rng,
const byte *recoverableMessage, size_t recoverableMessageLength,

View File

@ -5,8 +5,8 @@
#ifndef CRYPTOPP_IMPORTS
#include "eprecomp.h"
#include "integer.h"
#include "asn.h"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
@ -26,8 +26,8 @@ template <class T> void DL_FixedBasePrecomputationImpl<T>::SetBase(const DL_Grou
template <class T> void DL_FixedBasePrecomputationImpl<T>::Precompute(const DL_GroupPrecomputation<Element> &group, unsigned int maxExpBits, unsigned int storage)
{
CRYPTOPP_ASSERT(m_bases.size() > 0);
CRYPTOPP_ASSERT(storage <= maxExpBits);
assert(m_bases.size() > 0);
assert(storage <= maxExpBits);
if (storage > 1)
{

View File

@ -1,7 +1,7 @@
#ifndef CRYPTOPP_EPRECOMP_H
#define CRYPTOPP_EPRECOMP_H
#include "config.h"
#include "cryptlib.h"
#include "integer.h"
#include "algebra.h"
#include <vector>
@ -20,6 +20,10 @@ public:
virtual const AbstractGroup<Element> & GetGroup() const =0;
virtual Element BERDecodeElement(BufferedTransformation &bt) const =0;
virtual void DEREncodeElement(BufferedTransformation &bt, const Element &P) const =0;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_GroupPrecomputation() {}
#endif
};
template <class T>
@ -36,6 +40,10 @@ public:
virtual void Save(const DL_GroupPrecomputation<Element> &group, BufferedTransformation &storedPrecomputation) const =0;
virtual Element Exponentiate(const DL_GroupPrecomputation<Element> &group, const Integer &exponent) const =0;
virtual Element CascadeExponentiate(const DL_GroupPrecomputation<Element> &group, const Integer &exponent, const DL_FixedBasePrecomputation<Element> &pc2, const Integer &exponent2) const =0;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_FixedBasePrecomputation() {}
#endif
};
template <class T>
@ -45,7 +53,6 @@ public:
typedef T Element;
DL_FixedBasePrecomputationImpl() : m_windowSize(0) {}
virtual ~DL_FixedBasePrecomputationImpl() { }
// DL_FixedBasePrecomputation
bool IsInitialized() const
@ -59,6 +66,10 @@ public:
Element Exponentiate(const DL_GroupPrecomputation<Element> &group, const Integer &exponent) const;
Element CascadeExponentiate(const DL_GroupPrecomputation<Element> &group, const Integer &exponent, const DL_FixedBasePrecomputation<Element> &pc2, const Integer &exponent2) const;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_FixedBasePrecomputationImpl() {}
#endif
private:
void PrepareCascade(const DL_GroupPrecomputation<Element> &group, std::vector<BaseAndExponent<Element> > &eb, const Integer &exponent) const;

View File

@ -1,13 +1,20 @@
// esign.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
// TODO: fix the C4589 warnings
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4589)
#endif
#include "esign.h"
#include "asn.h"
#include "modarith.h"
#include "integer.h"
#include "nbtheory.h"
#include "sha.h"
#include "algparam.h"
#include "trap.h"
#include "sha.h"
#include "asn.h"
NAMESPACE_BEGIN(CryptoPP)
@ -47,8 +54,9 @@ Integer ESIGNFunction::ApplyFunction(const Integer &x) const
return STDMIN(a_exp_b_mod_c(x, m_e, m_n) >> (2*GetK()+2), MaxImage());
}
bool ESIGNFunction::Validate(RandomNumberGenerator &rng, unsigned int level) const
bool ESIGNFunction::Validate(RandomNumberGenerator& rng, unsigned int level) const
{
CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(level);
bool pass = true;
pass = pass && m_n > Integer::One() && m_n.IsOdd();
pass = pass && m_e >= 8 && m_e < m_n;
@ -75,8 +83,8 @@ void ESIGNFunction::AssignFrom(const NameValuePairs &source)
void InvertibleESIGNFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &param)
{
unsigned int modulusSize = 1023*2;
param.GetAsUIntValue("ModulusSize", modulusSize) || param.GetAsUIntValue("KeySize", modulusSize);
int modulusSize = 1023*2;
param.GetIntValue("ModulusSize", modulusSize) || param.GetIntValue("KeySize", modulusSize);
if (modulusSize < 24)
throw InvalidArgument("InvertibleESIGNFunction: specified modulus size is too small");
@ -115,7 +123,7 @@ void InvertibleESIGNFunction::GenerateRandom(RandomNumberGenerator &rng, const N
m_n = m_p * m_p * m_q;
CRYPTOPP_ASSERT(m_n.BitCount() == modulusSize);
assert(m_n.BitCount() == (unsigned int)modulusSize);
}
void InvertibleESIGNFunction::BERDecode(BufferedTransformation &bt)
@ -164,18 +172,18 @@ Integer InvertibleESIGNFunction::CalculateRandomizedInverse(RandomNumberGenerato
ModularArithmetic modp(m_p);
Integer t = modp.Divide(w0 * r % m_p, m_e * re % m_p);
Integer s = r + t*pq;
CRYPTOPP_ASSERT(s < m_n);
/*
assert(s < m_n);
#if 0
using namespace std;
std::cout << "f = " << x << std::endl;
std::cout << "r = " << r << std::endl;
std::cout << "z = " << z << std::endl;
std::cout << "a = " << a << std::endl;
std::cout << "w0 = " << w0 << std::endl;
std::cout << "w1 = " << w1 << std::endl;
std::cout << "t = " << t << std::endl;
std::cout << "s = " << s << std::endl;
*/
cout << "f = " << x << endl;
cout << "r = " << r << endl;
cout << "z = " << z << endl;
cout << "a = " << a << endl;
cout << "w0 = " << w0 << endl;
cout << "w1 = " << w1 << endl;
cout << "t = " << t << endl;
cout << "s = " << s << endl;
#endif
return s;
}

View File

@ -6,10 +6,11 @@
ESIGN signature schemes as defined in IEEE P1363a.
*/
#include "config.h"
#include "integer.h"
#include "cryptlib.h"
#include "pubkey.h"
#include "integer.h"
#include "asn.h"
#include "misc.h"
NAMESPACE_BEGIN(CryptoPP)
@ -95,6 +96,8 @@ public:
HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
byte *representative, size_t representativeBitLength) const
{
CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(recoverableMessage), CRYPTOPP_UNUSED(recoverableMessageLength);
CRYPTOPP_UNUSED(messageEmpty), CRYPTOPP_UNUSED(hashIdentifier);
SecByteBlock digest(hash.DigestSize());
hash.Final(digest);
size_t representativeByteLength = BitsToBytes(representativeBitLength);

View File

@ -3,15 +3,7 @@
#include "cryptlib.h"
#include "misc.h"
#include <map>
#include <vector>
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-value"
# pragma GCC diagnostic ignored "-Wunused-variable"
# pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#include "stdcpp.h"
NAMESPACE_BEGIN(CryptoPP)
@ -33,7 +25,6 @@ public:
{
return new ConcreteClass;
}
};
//! _
@ -114,6 +105,7 @@ RegisterDefaultFactoryFor(const char *name=NULL)
template <class SchemeClass>
void RegisterAsymmetricCipherDefaultFactories(const char *name=NULL, SchemeClass *dummy=NULL)
{
CRYPTOPP_UNUSED(dummy);
RegisterDefaultFactoryFor<PK_Encryptor, CPP_TYPENAME SchemeClass::Encryptor>((const char *)name);
RegisterDefaultFactoryFor<PK_Decryptor, CPP_TYPENAME SchemeClass::Decryptor>((const char *)name);
}
@ -121,6 +113,7 @@ void RegisterAsymmetricCipherDefaultFactories(const char *name=NULL, SchemeClass
template <class SchemeClass>
void RegisterSignatureSchemeDefaultFactories(const char *name=NULL, SchemeClass *dummy=NULL)
{
CRYPTOPP_UNUSED(dummy);
RegisterDefaultFactoryFor<PK_Signer, CPP_TYPENAME SchemeClass::Signer>((const char *)name);
RegisterDefaultFactoryFor<PK_Verifier, CPP_TYPENAME SchemeClass::Verifier>((const char *)name);
}
@ -128,6 +121,7 @@ void RegisterSignatureSchemeDefaultFactories(const char *name=NULL, SchemeClass
template <class SchemeClass>
void RegisterSymmetricCipherDefaultFactories(const char *name=NULL, SchemeClass *dummy=NULL)
{
CRYPTOPP_UNUSED(dummy);
RegisterDefaultFactoryFor<SymmetricCipher, CPP_TYPENAME SchemeClass::Encryption, ENCRYPTION>((const char *)name);
RegisterDefaultFactoryFor<SymmetricCipher, CPP_TYPENAME SchemeClass::Decryption, DECRYPTION>((const char *)name);
}
@ -135,14 +129,11 @@ void RegisterSymmetricCipherDefaultFactories(const char *name=NULL, SchemeClass
template <class SchemeClass>
void RegisterAuthenticatedSymmetricCipherDefaultFactories(const char *name=NULL, SchemeClass *dummy=NULL)
{
CRYPTOPP_UNUSED(dummy);
RegisterDefaultFactoryFor<AuthenticatedSymmetricCipher, CPP_TYPENAME SchemeClass::Encryption, ENCRYPTION>((const char *)name);
RegisterDefaultFactoryFor<AuthenticatedSymmetricCipher, CPP_TYPENAME SchemeClass::Decryption, DECRYPTION>((const char *)name);
}
NAMESPACE_END
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic push
#endif
#endif

View File

@ -5,13 +5,11 @@
#ifndef CRYPTOPP_IMPORTS
#include "files.h"
#include "stdcpp.h"
#include "trap.h"
#include <limits>
NAMESPACE_BEGIN(CryptoPP)
using namespace std;
#ifndef NDEBUG
void Files_TestInstantiations()
{
@ -67,8 +65,8 @@ lword FileStore::MaxRetrievable() const
if (!m_stream)
return 0;
streampos current = m_stream->tellg();
streampos end = m_stream->seekg(0, std::ios::end).tellg();
std::streampos current = m_stream->tellg();
std::streampos end = m_stream->seekg(0, std::ios::end).tellg();
m_stream->seekg(current);
return end-current;
}
@ -91,7 +89,7 @@ size_t FileStore::TransferTo2(BufferedTransformation &target, lword &transferByt
{
{
size_t spaceSize = 1024;
m_space = HelpCreatePutSpace(target, channel, 1, UnsignedMin(size_t(0)-1, size), spaceSize);
m_space = HelpCreatePutSpace(target, channel, 1, UnsignedMin(size_t(SIZE_MAX), size), spaceSize);
m_stream->read((char *)m_space, (unsigned int)STDMIN(size, (lword)spaceSize));
}
@ -120,7 +118,7 @@ size_t FileStore::CopyRangeTo2(BufferedTransformation &target, lword &begin, lwo
if (begin == 0 && end == 1)
{
int result = m_stream->peek();
if (result == char_traits<char>::eof())
if (result == std::char_traits<char>::eof())
return 0;
else
{
@ -131,9 +129,9 @@ size_t FileStore::CopyRangeTo2(BufferedTransformation &target, lword &begin, lwo
}
// TODO: figure out what happens on cin
streampos current = m_stream->tellg();
streampos endPosition = m_stream->seekg(0, std::ios::end).tellg();
streampos newPosition = current + (streamoff)begin;
std::streampos current = m_stream->tellg();
std::streampos endPosition = m_stream->seekg(0, std::ios::end).tellg();
std::streampos newPosition = current + static_cast<std::streamoff>(begin);
if (newPosition >= endPosition)
{
@ -143,7 +141,7 @@ size_t FileStore::CopyRangeTo2(BufferedTransformation &target, lword &begin, lwo
m_stream->seekg(newPosition);
try
{
CRYPTOPP_ASSERT(!m_waiting);
assert(!m_waiting);
lword copyMax = end-begin;
size_t blockedBytes = const_cast<FileStore *>(this)->TransferTo2(target, copyMax, channel, blocking);
begin += copyMax;
@ -200,8 +198,7 @@ void FileSink::IsolatedInitialize(const NameValuePairs &parameters)
std::string narrowed;
if (fileNameWide)
fileName = (narrowed = StringNarrow(fileNameWide)).c_str();
#endif
#if _MSC_VER >= 1400
#elif (CRYPTOPP_MSC_VERSION >= 1400)
if (fileNameWide)
{
m_file->open(fileNameWide, std::ios::out | std::ios::trunc | binary);
@ -220,6 +217,7 @@ void FileSink::IsolatedInitialize(const NameValuePairs &parameters)
bool FileSink::IsolatedFlush(bool hardFlush, bool blocking)
{
CRYPTOPP_UNUSED(hardFlush), CRYPTOPP_UNUSED(blocking);
if (!m_stream)
throw Err("FileSink: output stream not opened");
@ -232,16 +230,15 @@ bool FileSink::IsolatedFlush(bool hardFlush, bool blocking)
size_t FileSink::Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
{
CRYPTOPP_UNUSED(blocking);
if (!m_stream)
throw Err("FileSink: output stream not opened");
while (length > 0)
{
std::streamsize size;
bool safe = SafeConvert(length, size);
CRYPTOPP_ASSERT(safe);
if (!safe)
size = numeric_limits<std::streamsize>::max();
if (!SafeConvert(length, size))
size = ((std::numeric_limits<std::streamsize>::max)());
m_stream->write((const char *)inString, size);
inString += size;
length -= (size_t)size;

View File

@ -4,6 +4,7 @@
#include "cryptlib.h"
#include "filters.h"
#include "argnames.h"
#include "smartptr.h"
#include <iostream>
#include <fstream>

View File

@ -1,27 +1,31 @@
// filters.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4100 4189)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic ignored "-Wunused-value"
#endif
#ifndef CRYPTOPP_IMPORTS
#include "filters.h"
#include "stdcpp.h"
#include "smartptr.h"
#include "mqueue.h"
#include "fltrimpl.h"
#include "argnames.h"
#include "stdcpp.h"
#include "trap.h"
#include "smartptr.h"
#include "misc.h"
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic ignored "-Wunused-value"
# pragma GCC diagnostic ignored "-Wunused-variable"
#endif
#include <functional>
NAMESPACE_BEGIN(CryptoPP)
Filter::Filter(BufferedTransformation *attachment)
: m_attachment(attachment), m_continueAt(0)
: m_attachment(attachment), m_inputPosition(0), m_continueAt(0)
{
}
@ -67,7 +71,7 @@ size_t Filter::TransferTo2(BufferedTransformation &target, lword &transferBytes,
void Filter::Initialize(const NameValuePairs &parameters, int propagation)
{
m_continueAt = 0;
m_inputPosition = m_continueAt = 0;
IsolatedInitialize(parameters);
PropagateInitialize(parameters, propagation);
}
@ -108,9 +112,6 @@ void Filter::PropagateInitialize(const NameValuePairs &parameters, int propagati
size_t Filter::OutputModifiable(int outputSite, byte *inString, size_t length, int messageEnd, bool blocking, const std::string &channel)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
if (messageEnd)
messageEnd--;
size_t result = AttachedTransformation()->ChannelPutModifiable2(channel, inString, length, messageEnd, blocking);
@ -120,10 +121,6 @@ size_t Filter::OutputModifiable(int outputSite, byte *inString, size_t length, i
size_t Filter::Output(int outputSite, const byte *inString, size_t length, int messageEnd, bool blocking, const std::string &channel)
{
// Formerly fired because inString was not NULL, but length was 0.
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
if (messageEnd)
messageEnd--;
size_t result = AttachedTransformation()->ChannelPut2(channel, inString, length, messageEnd, blocking);
@ -186,7 +183,7 @@ size_t MeterFilter::PutMaybeModifiable(byte *begin, size_t length, int messageEn
{
FILTER_OUTPUT_MAYBE_MODIFIABLE(1, m_begin, t = (size_t)SaturatingSubtract(m_rangesToSkip.front().position, m_currentMessageBytes), false, modifiable);
CRYPTOPP_ASSERT(t < m_length);
assert(t < m_length);
m_begin += t;
m_length -= t;
m_currentMessageBytes += t;
@ -197,7 +194,7 @@ size_t MeterFilter::PutMaybeModifiable(byte *begin, size_t length, int messageEn
else
{
t = (size_t)SaturatingSubtract(m_rangesToSkip.front().position + m_rangesToSkip.front().size, m_currentMessageBytes);
CRYPTOPP_ASSERT(t <= m_length);
assert(t <= m_length);
m_rangesToSkip.pop_front();
}
@ -239,6 +236,7 @@ size_t MeterFilter::PutModifiable2(byte *begin, size_t length, int messageEnd, b
bool MeterFilter::IsolatedMessageSeriesEnd(bool blocking)
{
CRYPTOPP_UNUSED(blocking);
m_currentMessageBytes = 0;
m_currentSeriesMessages = 0;
m_totalMessageSeries++;
@ -283,6 +281,7 @@ byte *FilterWithBufferedInput::BlockQueue::GetContigousBlocks(size_t &numberOfBy
size_t FilterWithBufferedInput::BlockQueue::GetAll(byte *outString)
{
// Avoid passing NULL pointer to memcpy
if (!outString) return 0;
size_t size = m_size;
@ -294,31 +293,36 @@ size_t FilterWithBufferedInput::BlockQueue::GetAll(byte *outString)
return size;
}
size_t FilterWithBufferedInput::BlockQueue::Put(const byte *inString, size_t length)
void FilterWithBufferedInput::BlockQueue::Put(const byte *inString, size_t length)
{
if (!inString || !length) return length;
if (!m_buffer.data()) return length;
// Avoid passing NULL pointer to memcpy
if (!inString || !length) return;
CRYPTOPP_ASSERT(m_size + length <= m_buffer.size());
assert(m_size + length <= m_buffer.size());
byte *end = (m_size < size_t(m_buffer.end()-m_begin)) ? m_begin + m_size : m_begin + m_size - m_buffer.size();
size_t len = STDMIN(length, size_t(m_buffer.end()-end));
memcpy(end, inString, len);
if (len < length)
memcpy(m_buffer, inString+len, length-len);
m_size += length;
return 0;
}
#if !defined(CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562)
FilterWithBufferedInput::FilterWithBufferedInput()
: Filter(), m_firstSize(SIZE_MAX), m_blockSize(0), m_lastSize(SIZE_MAX), m_firstInputDone(false)
{
}
#endif
FilterWithBufferedInput::FilterWithBufferedInput(BufferedTransformation *attachment)
: Filter(attachment)
: Filter(attachment), m_firstSize(SIZE_MAX), m_blockSize(0), m_lastSize(SIZE_MAX), m_firstInputDone(false)
{
}
FilterWithBufferedInput::FilterWithBufferedInput(size_t firstSize, size_t blockSize, size_t lastSize, BufferedTransformation *attachment)
: Filter(attachment), m_firstSize(firstSize), m_blockSize(blockSize), m_lastSize(lastSize)
, m_firstInputDone(false)
: Filter(attachment), m_firstSize(firstSize), m_blockSize(blockSize), m_lastSize(lastSize), m_firstInputDone(false)
{
if (m_firstSize < 0 || m_blockSize < 1 || m_lastSize < 0)
if (m_firstSize == SIZE_MAX || m_blockSize < 1 || m_lastSize == SIZE_MAX)
throw InvalidArgument("FilterWithBufferedInput: invalid buffer size");
m_queue.ResetQueue(1, m_firstSize);
@ -327,7 +331,7 @@ FilterWithBufferedInput::FilterWithBufferedInput(size_t firstSize, size_t blockS
void FilterWithBufferedInput::IsolatedInitialize(const NameValuePairs &parameters)
{
InitializeDerivedAndReturnNewSizes(parameters, m_firstSize, m_blockSize, m_lastSize);
if (m_firstSize < 0 || m_blockSize < 1 || m_lastSize < 0)
if (m_firstSize == SIZE_MAX || m_blockSize < 1 || m_lastSize == SIZE_MAX)
throw InvalidArgument("FilterWithBufferedInput: invalid buffer size");
m_queue.ResetQueue(1, m_firstSize);
m_firstInputDone = false;
@ -347,9 +351,6 @@ bool FilterWithBufferedInput::IsolatedFlush(bool hardFlush, bool blocking)
size_t FilterWithBufferedInput::PutMaybeModifiable(byte *inString, size_t length, int messageEnd, bool blocking, bool modifiable)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
if (!blocking)
throw BlockingInputOnly("FilterWithBufferedInput");
@ -362,7 +363,7 @@ size_t FilterWithBufferedInput::PutMaybeModifiable(byte *inString, size_t length
size_t len = m_firstSize - m_queue.CurrentSize();
m_queue.Put(inString, len);
FirstPut(m_queue.GetContigousBlocks(m_firstSize));
CRYPTOPP_ASSERT(m_queue.CurrentSize() == 0);
assert(m_queue.CurrentSize() == 0);
m_queue.ResetQueue(m_blockSize, (2*m_blockSize+m_lastSize-2)/m_blockSize);
inString += len;
@ -400,7 +401,7 @@ size_t FilterWithBufferedInput::PutMaybeModifiable(byte *inString, size_t length
if (newLength >= m_blockSize + m_lastSize && m_queue.CurrentSize() > 0)
{
CRYPTOPP_ASSERT(m_queue.CurrentSize() < m_blockSize);
assert(m_queue.CurrentSize() < m_blockSize);
size_t len = m_blockSize - m_queue.CurrentSize();
m_queue.Put(inString, len);
inString += len;
@ -458,13 +459,10 @@ void FilterWithBufferedInput::ForceNextPut()
void FilterWithBufferedInput::NextPutMultiple(const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
CRYPTOPP_ASSERT(m_blockSize > 1); // m_blockSize = 1 should always override this function
assert(m_blockSize > 1); // m_blockSize = 1 should always override this function
while (length > 0)
{
CRYPTOPP_ASSERT(length >= m_blockSize);
assert(length >= m_blockSize);
NextPutSingle(inString);
inString += m_blockSize;
length -= m_blockSize;
@ -502,7 +500,7 @@ void ProxyFilter::SetFilter(Filter *filter)
if (filter)
{
OutputProxy *proxy;
auto_ptr<OutputProxy> temp(proxy = new OutputProxy(*this, false));
member_ptr<OutputProxy> temp(proxy = new OutputProxy(*this, false));
m_filter->TransferAllTo(*proxy);
m_filter->Attach(temp.release());
}
@ -529,20 +527,25 @@ void RandomNumberSink::IsolatedInitialize(const NameValuePairs &parameters)
size_t RandomNumberSink::Put2(const byte *begin, size_t length, int messageEnd, bool blocking)
{
CRYPTOPP_UNUSED(messageEnd); CRYPTOPP_UNUSED(blocking);
m_rng->IncorporateEntropy(begin, length);
return 0;
}
size_t ArraySink::Put2(const byte *begin, size_t length, int messageEnd, bool blocking)
{
if (!begin || !length) return length;
if (!m_buf) return length;
CRYPTOPP_UNUSED(messageEnd); CRYPTOPP_UNUSED(blocking);
if (m_buf+m_total != begin)
memcpy(m_buf+m_total, begin, STDMIN(length, SaturatingSubtract(m_size, m_total)));
m_total += length;
return 0;
// Avoid passing NULL pointer to memcpy. Using memmove due to
// Valgrind finding on overlapping buffers.
size_t copied = 0;
if (m_buf && begin)
{
copied = STDMIN(length, SaturatingSubtract(m_size, m_total));
memmove(m_buf+m_total, begin, copied);
}
m_total += copied;
return length - copied;
}
byte * ArraySink::CreatePutSpace(size_t &size)
@ -558,17 +561,21 @@ void ArraySink::IsolatedInitialize(const NameValuePairs &parameters)
throw InvalidArgument("ArraySink: missing OutputBuffer argument");
m_buf = array.begin();
m_size = array.size();
m_total = 0;
}
size_t ArrayXorSink::Put2(const byte *begin, size_t length, int messageEnd, bool blocking)
{
if (!begin || !length) return length;
if (!m_buf) return length;
CRYPTOPP_UNUSED(messageEnd); CRYPTOPP_UNUSED(blocking);
xorbuf(m_buf+m_total, begin, STDMIN(length, SaturatingSubtract(m_size, m_total)));
m_total += length;
return 0;
// Avoid passing NULL pointer to xorbuf
size_t copied = 0;
if (m_buf && begin)
{
copied = STDMIN(length, SaturatingSubtract(m_size, m_total));
xorbuf(m_buf+m_total, begin, copied);
}
m_total += copied;
return length - copied;
}
// *************************************************************
@ -577,7 +584,7 @@ StreamTransformationFilter::StreamTransformationFilter(StreamTransformation &c,
: FilterWithBufferedInput(attachment)
, m_cipher(c)
{
CRYPTOPP_ASSERT(c.MinLastBlockSize() == 0 || c.MinLastBlockSize() > c.MandatoryBlockSize());
assert(c.MinLastBlockSize() == 0 || c.MinLastBlockSize() > c.MandatoryBlockSize());
if (!allowAuthenticatedSymmetricCipher && dynamic_cast<AuthenticatedSymmetricCipher *>(&c) != 0)
throw InvalidArgument("StreamTransformationFilter: please use AuthenticatedEncryptionFilter and AuthenticatedDecryptionFilter for AuthenticatedSymmetricCipher");
@ -613,18 +620,17 @@ void StreamTransformationFilter::InitializeDerivedAndReturnNewSizes(const NameVa
lastSize = LastBlockSize(m_cipher, m_padding);
}
void StreamTransformationFilter::FirstPut(const byte *inString)
void StreamTransformationFilter::FirstPut(const byte* inString)
{
// FilterWithBufferedInput::PutMaybeModifiable causes this to fire.
// CRYPTOPP_ASSERT(inString);
CRYPTOPP_UNUSED(inString);
m_optimalBufferSize = m_cipher.OptimalBlockSize();
m_optimalBufferSize = (unsigned int)STDMAX(m_optimalBufferSize, RoundDownToMultipleOf(4096U, m_optimalBufferSize));
}
void StreamTransformationFilter::NextPutMultiple(const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
if (!length)
return;
size_t s = m_cipher.MandatoryBlockSize();
@ -639,9 +645,7 @@ void StreamTransformationFilter::NextPutMultiple(const byte *inString, size_t le
len = RoundDownToMultipleOf(len, s);
}
else
{
len = length;
}
m_cipher.ProcessString(space, inString, len);
AttachedTransformation()->PutModifiable(space, len);
inString += len;
@ -652,18 +656,12 @@ void StreamTransformationFilter::NextPutMultiple(const byte *inString, size_t le
void StreamTransformationFilter::NextPutModifiable(byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
m_cipher.ProcessString(inString, length);
AttachedTransformation()->PutModifiable(inString, length);
}
void StreamTransformationFilter::LastPut(const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
byte *space = NULL;
switch (m_padding)
@ -680,8 +678,7 @@ void StreamTransformationFilter::LastPut(const byte *inString, size_t length)
// do padding
size_t blockSize = STDMAX(minLastBlockSize, (size_t)m_cipher.MandatoryBlockSize());
space = HelpCreatePutSpace(*AttachedTransformation(), DEFAULT_CHANNEL, blockSize);
if (inString && length)
memcpy(space, inString, length);
if (inString) {memcpy(space, inString, length);}
memset(space + length, 0, blockSize - length);
m_cipher.ProcessLastBlock(space, space, blockSize);
AttachedTransformation()->Put(space, blockSize);
@ -707,16 +704,15 @@ void StreamTransformationFilter::LastPut(const byte *inString, size_t length)
case ONE_AND_ZEROS_PADDING:
unsigned int s;
s = m_cipher.MandatoryBlockSize();
CRYPTOPP_ASSERT(s > 1);
assert(s > 1);
space = HelpCreatePutSpace(*AttachedTransformation(), DEFAULT_CHANNEL, s, m_optimalBufferSize);
if (m_cipher.IsForwardTransformation())
{
CRYPTOPP_ASSERT(length < s);
if (inString && length)
memcpy(space, inString, length);
assert(length < s);
if (inString) {memcpy(space, inString, length);}
if (m_padding == PKCS_PADDING)
{
CRYPTOPP_ASSERT(s < 256);
assert(s < 256);
byte pad = byte(s-length);
memset(space+length, pad, s-length);
}
@ -736,7 +732,7 @@ void StreamTransformationFilter::LastPut(const byte *inString, size_t length)
if (m_padding == PKCS_PADDING)
{
byte pad = space[s-1];
if (pad < 1 || pad > s || std::find_if (space+s-pad, space+s, std::bind2nd(std::not_equal_to<byte>(), pad)) != space+s)
if (pad < 1 || pad > s || std::find_if(space+s-pad, space+s, std::bind2nd(std::not_equal_to<byte>(), pad)) != space+s)
throw InvalidCiphertext("StreamTransformationFilter: invalid PKCS #7 block padding found");
length = s-pad;
}
@ -752,7 +748,7 @@ void StreamTransformationFilter::LastPut(const byte *inString, size_t length)
break;
default:
CRYPTOPP_ASSERT(false);
assert(false);
}
}
@ -774,9 +770,6 @@ void HashFilter::IsolatedInitialize(const NameValuePairs &parameters)
size_t HashFilter::Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
FILTER_BEGIN;
if (m_putMessage)
FILTER_OUTPUT3(1, 0, inString, length, 0, m_messagePutChannel);
@ -815,15 +808,10 @@ void HashVerificationFilter::InitializeDerivedAndReturnNewSizes(const NameValueP
void HashVerificationFilter::FirstPut(const byte *inString)
{
// FilterWithBufferedInput::PutMaybeModifiable causes this to fire.
// CRYPTOPP_ASSERT(inString);
if (m_flags & HASH_AT_BEGIN)
{
m_expectedHash.New(m_digestSize);
if (inString)
memcpy(m_expectedHash, inString, m_expectedHash.size());
if (inString) {memcpy(m_expectedHash, inString, m_expectedHash.size());}
if (m_flags & PUT_HASH)
AttachedTransformation()->Put(inString, m_expectedHash.size());
}
@ -831,9 +819,6 @@ void HashVerificationFilter::FirstPut(const byte *inString)
void HashVerificationFilter::NextPutMultiple(const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
m_hashModule.Update(inString, length);
if (m_flags & PUT_MESSAGE)
AttachedTransformation()->Put(inString, length);
@ -841,12 +826,9 @@ void HashVerificationFilter::NextPutMultiple(const byte *inString, size_t length
void HashVerificationFilter::LastPut(const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
if (m_flags & HASH_AT_BEGIN)
{
CRYPTOPP_ASSERT(length == 0);
assert(length == 0);
m_verified = m_hashModule.TruncatedVerify(m_expectedHash, m_digestSize);
}
else
@ -870,7 +852,7 @@ AuthenticatedEncryptionFilter::AuthenticatedEncryptionFilter(AuthenticatedSymmet
: StreamTransformationFilter(c, attachment, padding, true)
, m_hf(c, new OutputProxy(*this, false), putAAD, truncatedDigestSize, AAD_CHANNEL, macChannel)
{
CRYPTOPP_ASSERT(c.IsForwardTransformation());
assert(c.IsForwardTransformation());
}
void AuthenticatedEncryptionFilter::IsolatedInitialize(const NameValuePairs &parameters)
@ -903,9 +885,6 @@ size_t AuthenticatedEncryptionFilter::ChannelPut2(const std::string &channel, co
void AuthenticatedEncryptionFilter::LastPut(const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
StreamTransformationFilter::LastPut(inString, length);
m_hf.MessageEnd();
}
@ -917,7 +896,7 @@ AuthenticatedDecryptionFilter::AuthenticatedDecryptionFilter(AuthenticatedSymmet
, m_hashVerifier(c, new OutputProxy(*this, false))
, m_streamFilter(c, new OutputProxy(*this, false), padding, true)
{
CRYPTOPP_ASSERT(!c.IsForwardTransformation() || c.IsSelfInverting());
assert(!c.IsForwardTransformation() || c.IsSelfInverting());
IsolatedInitialize(MakeParameters(Name::BlockPaddingScheme(), padding)(Name::AuthenticatedDecryptionFilterFlags(), flags)(Name::TruncatedDigestSize(), truncatedDigestSize));
}
@ -961,24 +940,16 @@ size_t AuthenticatedDecryptionFilter::ChannelPut2(const std::string &channel, co
void AuthenticatedDecryptionFilter::FirstPut(const byte *inString)
{
// FilterWithBufferedInput::PutMaybeModifiable causes this to fire.
// CRYPTOPP_ASSERT(inString);
m_hashVerifier.Put(inString, m_firstSize);
}
void AuthenticatedDecryptionFilter::NextPutMultiple(const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
m_streamFilter.Put(inString, length);
}
void AuthenticatedDecryptionFilter::LastPut(const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
m_streamFilter.MessageEnd();
m_hashVerifier.PutMessageEnd(inString, length);
}
@ -993,9 +964,6 @@ void SignerFilter::IsolatedInitialize(const NameValuePairs &parameters)
size_t SignerFilter::Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
FILTER_BEGIN;
m_messageAccumulator->Update(inString, length);
if (m_putMessage)
@ -1022,7 +990,7 @@ void SignatureVerificationFilter::InitializeDerivedAndReturnNewSizes(const NameV
m_flags = parameters.GetValueWithDefault(Name::SignatureVerificationFilterFlags(), (word32)DEFAULT_FLAGS);
m_messageAccumulator.reset(m_verifier.NewVerificationAccumulator());
size_t size = m_verifier.SignatureLength();
CRYPTOPP_ASSERT(size != 0); // TODO: handle recoverable signature scheme
assert(size != 0); // TODO: handle recoverable signature scheme
m_verified = false;
firstSize = m_flags & SIGNATURE_AT_BEGIN ? size : 0;
blockSize = 1;
@ -1031,9 +999,6 @@ void SignatureVerificationFilter::InitializeDerivedAndReturnNewSizes(const NameV
void SignatureVerificationFilter::FirstPut(const byte *inString)
{
// FilterWithBufferedInput::PutMaybeModifiable causes this to fire.
// CRYPTOPP_ASSERT(inString);
if (m_flags & SIGNATURE_AT_BEGIN)
{
if (m_verifier.SignatureUpfront())
@ -1041,7 +1006,7 @@ void SignatureVerificationFilter::FirstPut(const byte *inString)
else
{
m_signature.New(m_verifier.SignatureLength());
memcpy(m_signature, inString, m_signature.size());
if (inString) {memcpy(m_signature, inString, m_signature.size());}
}
if (m_flags & PUT_SIGNATURE)
@ -1049,15 +1014,12 @@ void SignatureVerificationFilter::FirstPut(const byte *inString)
}
else
{
CRYPTOPP_ASSERT(!m_verifier.SignatureUpfront());
assert(!m_verifier.SignatureUpfront());
}
}
void SignatureVerificationFilter::NextPutMultiple(const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
m_messageAccumulator->Update(inString, length);
if (m_flags & PUT_MESSAGE)
AttachedTransformation()->Put(inString, length);
@ -1065,12 +1027,9 @@ void SignatureVerificationFilter::NextPutMultiple(const byte *inString, size_t l
void SignatureVerificationFilter::LastPut(const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(inString || (!inString && !length));
if (inString == NULL) { length = 0; }
if (m_flags & SIGNATURE_AT_BEGIN)
{
CRYPTOPP_ASSERT(length == 0);
assert(length == 0);
m_verifier.InputSignature(*m_messageAccumulator, m_signature, m_signature.size());
m_verified = m_verifier.VerifyAndRestart(*m_messageAccumulator);
}

View File

@ -3,15 +3,21 @@
//! \file
#include "cryptlib.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4127 4189)
#endif
#include "cryptlib.h"
#include "simple.h"
#include "secblock.h"
#include "misc.h"
#include "smartptr.h"
#include "queue.h"
#include "algparam.h"
#include "trap.h"
#include <deque>
#include "stdcpp.h"
NAMESPACE_BEGIN(CryptoPP)
@ -61,7 +67,7 @@ struct CRYPTOPP_DLL FilterPutSpaceHelper
// desiredSize is how much to ask target, bufferSize is how much to allocate in m_tempSpace
byte *HelpCreatePutSpace(BufferedTransformation &target, const std::string &channel, size_t minSize, size_t desiredSize, size_t &bufferSize)
{
CRYPTOPP_ASSERT(desiredSize >= minSize && bufferSize >= minSize);
assert(desiredSize >= minSize && bufferSize >= minSize);
if (m_tempSpace.size() < minSize)
{
byte *result = target.ChannelCreatePutSpace(channel, desiredSize);
@ -88,12 +94,15 @@ class CRYPTOPP_DLL MeterFilter : public Bufferless<Filter>
{
public:
MeterFilter(BufferedTransformation *attachment=NULL, bool transparent=true)
: m_transparent(transparent) {Detach(attachment); ResetMeter();}
: m_transparent(transparent), m_currentMessageBytes(0), m_totalBytes(0)
, m_currentSeriesMessages(0), m_totalMessages(0), m_totalMessageSeries(0)
, m_begin(NULL), m_length(0) {Detach(attachment); ResetMeter();}
void SetTransparent(bool transparent) {m_transparent = transparent;}
void AddRangeToSkip(unsigned int message, lword position, lword size, bool sortNow = true);
void ResetMeter();
void IsolatedInitialize(const NameValuePairs &parameters) {ResetMeter();}
void IsolatedInitialize(const NameValuePairs &parameters)
{CRYPTOPP_UNUSED(parameters); ResetMeter();}
lword GetCurrentMessageBytes() const {return m_currentMessageBytes;}
lword GetTotalBytes() {return m_totalBytes;}
@ -149,6 +158,13 @@ public:
class CRYPTOPP_DLL FilterWithBufferedInput : public Filter
{
public:
#if !defined(CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562)
//! default FilterWithBufferedInput for temporaries
FilterWithBufferedInput();
#endif
//! construct a FilterWithBufferedInput with an attached transformation
FilterWithBufferedInput(BufferedTransformation *attachment);
//! firstSize and lastSize may be 0, blockSize must be at least 1
FilterWithBufferedInput(size_t firstSize, size_t blockSize, size_t lastSize, BufferedTransformation *attachment);
@ -174,13 +190,15 @@ protected:
bool DidFirstPut() {return m_firstInputDone;}
virtual void InitializeDerivedAndReturnNewSizes(const NameValuePairs &parameters, size_t &firstSize, size_t &blockSize, size_t &lastSize)
{InitializeDerived(parameters);}
virtual void InitializeDerived(const NameValuePairs &parameters) {}
{CRYPTOPP_UNUSED(parameters); CRYPTOPP_UNUSED(firstSize); CRYPTOPP_UNUSED(blockSize); CRYPTOPP_UNUSED(lastSize); InitializeDerived(parameters);}
virtual void InitializeDerived(const NameValuePairs &parameters)
{CRYPTOPP_UNUSED(parameters);}
// FirstPut() is called if (firstSize != 0 and totalLength >= firstSize)
// or (firstSize == 0 and (totalLength > 0 or a MessageEnd() is received))
virtual void FirstPut(const byte *inString) =0;
// NextPut() is called if totalLength >= firstSize+blockSize+lastSize
virtual void NextPutSingle(const byte *inString) {CRYPTOPP_ASSERT(false);}
virtual void NextPutSingle(const byte *inString)
{CRYPTOPP_UNUSED(inString); assert(false);}
// Same as NextPut() except length can be a multiple of blockSize
// Either NextPut() or NextPutMultiple() must be overriden
virtual void NextPutMultiple(const byte *inString, size_t length);
@ -204,7 +222,8 @@ protected:
// This function should no longer be used, put this here to cause a compiler error
// if someone tries to override NextPut().
virtual int NextPut(const byte *inString, size_t length) {CRYPTOPP_ASSERT(false); return 0;}
virtual int NextPut(const byte *inString, size_t length)
{CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length); assert(false); return 0;}
class BlockQueue
{
@ -213,7 +232,7 @@ protected:
byte *GetBlock();
byte *GetContigousBlocks(size_t &numberOfBytes);
size_t GetAll(byte *outString);
size_t Put(const byte *inString, size_t length);
void Put(const byte *inString, size_t length);
size_t CurrentSize() const {return m_size;}
size_t MaxSize() const {return m_buffer.size();}
@ -250,7 +269,8 @@ public:
protected:
virtual bool IsolatedMessageEnd(bool blocking) =0;
void IsolatedInitialize(const NameValuePairs &parameters) {m_inQueue.Clear();}
void IsolatedInitialize(const NameValuePairs &parameters)
{CRYPTOPP_UNUSED(parameters); m_inQueue.Clear();}
ByteQueue m_inQueue;
};
@ -582,7 +602,7 @@ public:
: SimpleProxyFilter(decryptor.CreateDecryptionFilter(rng), attachment) {}
};
//! Append input to a std::string object
//! Append input to a string object
template <class T>
class StringSinkTemplate : public Bufferless<Sink>
{
@ -591,13 +611,14 @@ public:
typedef typename T::traits_type::char_type char_type;
StringSinkTemplate(T &output)
: m_output(&output) {CRYPTOPP_ASSERT(sizeof(output[0])==1);}
: m_output(&output) {assert(sizeof(output[0])==1);}
void IsolatedInitialize(const NameValuePairs &parameters)
{if (!parameters.GetValue("OutputStringPointer", m_output)) throw InvalidArgument("StringSink: OutputStringPointer not specified");}
size_t Put2(const byte *begin, size_t length, int messageEnd, bool blocking)
{
CRYPTOPP_UNUSED(messageEnd); CRYPTOPP_UNUSED(blocking);
if (length > 0)
{
typename T::size_type size = m_output->size();
@ -637,8 +658,10 @@ private:
class CRYPTOPP_DLL ArraySink : public Bufferless<Sink>
{
public:
ArraySink(const NameValuePairs &parameters = g_nullNameValuePairs) {IsolatedInitialize(parameters);}
ArraySink(byte *buf, size_t size) : m_buf(buf), m_size(size), m_total(0) {}
ArraySink(const NameValuePairs &parameters = g_nullNameValuePairs)
: m_buf(NULL), m_size(0), m_total(0) {IsolatedInitialize(parameters);}
ArraySink(byte *buf, size_t size)
: m_buf(buf), m_size(size), m_total(0) {}
size_t AvailableSize() {return SaturatingSubtract(m_size, m_total);}
lword TotalPutLength() {return m_total;}
@ -664,7 +687,7 @@ public:
byte * CreatePutSpace(size_t &size) {return BufferedTransformation::CreatePutSpace(size);}
};
//! std::string-based implementation of Store interface
//! string-based implementation of Store interface
class StringStore : public Store
{
public:
@ -701,6 +724,7 @@ public:
size_t TransferTo2(BufferedTransformation &target, lword &transferBytes, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const
{
CRYPTOPP_UNUSED(target); CRYPTOPP_UNUSED(begin); CRYPTOPP_UNUSED(end); CRYPTOPP_UNUSED(channel); CRYPTOPP_UNUSED(blocking);
throw NotImplemented("RandomNumberStore: CopyRangeTo2() is not supported by this store");
}
@ -716,7 +740,8 @@ class CRYPTOPP_DLL NullStore : public Store
{
public:
NullStore(lword size = ULONG_MAX) : m_size(size) {}
void StoreInitialize(const NameValuePairs &parameters) {}
void StoreInitialize(const NameValuePairs &parameters)
{CRYPTOPP_UNUSED(parameters);}
lword MaxRetrievable() const {return m_size;}
size_t TransferTo2(BufferedTransformation &target, lword &transferBytes, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const;
@ -732,7 +757,7 @@ public:
Source(BufferedTransformation *attachment = NULL)
{Source::Detach(attachment);}
lword Pump(lword pumpMax=size_t(0)-1)
lword Pump(lword pumpMax=size_t(SIZE_MAX))
{Pump2(pumpMax); return pumpMax;}
unsigned int PumpMessages(unsigned int count=UINT_MAX)
{PumpMessages2(count); return count;}
@ -778,13 +803,13 @@ protected:
T m_store;
};
//! std::string-based implementation of Source interface
//! string-based implementation of Source interface
class CRYPTOPP_DLL StringSource : public SourceTemplate<StringStore>
{
public:
StringSource(BufferedTransformation *attachment = NULL)
: SourceTemplate<StringStore>(attachment) {}
//! zero terminated std::string as source
//! zero terminated string as source
StringSource(const char *string, bool pumpAll, BufferedTransformation *attachment = NULL)
: SourceTemplate<StringStore>(attachment) {SourceInitialize(pumpAll, MakeParameters("InputBuffer", ConstByteArrayParameter(string)));}
//! binary byte array as source
@ -809,4 +834,8 @@ public:
NAMESPACE_END
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif
#endif

View File

@ -6,15 +6,8 @@
#include "fips140.h"
#include "misc.h"
#include "trap.h"
#include "trdlocal.h" // needs to be included last for cygwin
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic ignored "-Wunused-value"
# pragma GCC diagnostic ignored "-Wunused-variable"
# pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
NAMESPACE_BEGIN(CryptoPP)
// Define this to 1 to turn on FIPS 140-2 compliance features, including additional tests during
@ -61,13 +54,14 @@ bool PowerUpSelfTestInProgressOnThisThread()
#if CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2
return AccessPowerUpSelfTestInProgress().GetValue() != NULL;
#else
CRYPTOPP_ASSERT(false); // should not be called
assert(false); // should not be called
return false;
#endif
}
void SetPowerUpSelfTestInProgressOnThisThread(bool inProgress)
{
CRYPTOPP_UNUSED(inProgress);
#if CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2
AccessPowerUpSelfTestInProgress().SetValue((void *)inProgress);
#endif
@ -75,6 +69,7 @@ void SetPowerUpSelfTestInProgressOnThisThread(bool inProgress)
void EncryptionPairwiseConsistencyTest_FIPS_140_Only(const PK_Encryptor &encryptor, const PK_Decryptor &decryptor)
{
CRYPTOPP_UNUSED(encryptor), CRYPTOPP_UNUSED(decryptor);
#if CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2
EncryptionPairwiseConsistencyTest(encryptor, decryptor);
#endif
@ -82,6 +77,7 @@ void EncryptionPairwiseConsistencyTest_FIPS_140_Only(const PK_Encryptor &encrypt
void SignaturePairwiseConsistencyTest_FIPS_140_Only(const PK_Signer &signer, const PK_Verifier &verifier)
{
CRYPTOPP_UNUSED(signer), CRYPTOPP_UNUSED(verifier);
#if CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2
SignaturePairwiseConsistencyTest(signer, verifier);
#endif

View File

@ -8,13 +8,14 @@
#define CRYPTOPP_DEFAULT_NO_DLL
#endif
#include "config.h"
#include "integer.h"
#include "dll.h"
#include "cryptlib.h"
#include "smartptr.h"
#include "filters.h"
#include "oids.h"
#include "trap.h"
USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)
class LineBreakParser : public AutoSignaling<Bufferless<Filter> >
{
@ -261,7 +262,7 @@ protected:
static inline void Xor(SecByteBlock &z, const SecByteBlock &x, const SecByteBlock &y)
{
CRYPTOPP_ASSERT(x.size() == y.size());
assert(x.size() == y.size());
z.resize(x.size());
xorbuf(z, x, y, x.size());
}
@ -636,7 +637,7 @@ protected:
}
else
{
CRYPTOPP_ASSERT(m_test == "Gen");
assert(m_test == "Gen");
int modLen = atol(m_bracketString.substr(6).c_str());
std::string &encodedKey = m_data["PrivKey"];
RSA::PrivateKey priv;
@ -786,7 +787,7 @@ protected:
else if (m_bracketString == "L=64")
pMAC.reset(new HMAC<SHA512>);
else
throw Exception(Exception::OTHER_ERROR, "TestDataParser: unexpected HMAC bracket std::string: " + m_bracketString);
throw Exception(Exception::OTHER_ERROR, "TestDataParser: unexpected HMAC bracket string: " + m_bracketString);
pMAC->SetKey(key, key.size());
int Tlen = atol(m_data["Tlen"].c_str());
@ -1033,7 +1034,7 @@ protected:
}
else
{
CRYPTOPP_ASSERT(m_test == "KAT");
assert(m_test == "KAT");
SecByteBlock &input = m_data2[INPUT];
SecByteBlock result(input.size());
@ -1096,7 +1097,7 @@ protected:
if (m_line.substr(0, 2) == "H>")
{
CRYPTOPP_ASSERT(m_test == "sha");
assert(m_test == "sha");
m_bracketString = m_line.substr(2, m_line.size()-4);
m_line = m_line.substr(0, 13) + "Hashes<H";
copyLine = true;
@ -1220,8 +1221,8 @@ int FIPS_140_AlgorithmTest(int argc, char **argv)
if (algorithm == "auto")
{
std::string algTable[] = {"AES", "ECDSA", "DSA", "HMAC", "RNG", "RSA", "TDES", "SKIPJACK", "SHA"}; // order is important here
for (i=0; i<COUNTOF(algTable); i++)
string algTable[] = {"AES", "ECDSA", "DSA", "HMAC", "RNG", "RSA", "TDES", "SKIPJACK", "SHA"}; // order is important here
for (i=0; i<sizeof(algTable)/sizeof(algTable[0]); i++)
{
if (dirname.find(algTable[i]) != std::string::npos)
{
@ -1276,13 +1277,13 @@ int FIPS_140_AlgorithmTest(int argc, char **argv)
pSink = new FileSink(outPathname.c_str(), false);
}
else
pSink = new FileSink(std::cout);
pSink = new FileSink(cout);
FileSource(pathname.c_str(), true, new LineBreakParser(new TestDataParser(algorithm, test, mode, feedbackSize, encrypt, pSink)), false);
}
catch (...)
{
std::cout << "file: " << filename << std::endl;
cout << "file: " << filename << endl;
throw;
}
return 0;

View File

@ -2,15 +2,16 @@
#include "pch.h"
#include "misc.h"
#ifndef CRYPTOPP_IMPORTS
#define CRYPTOPP_DEFAULT_NO_DLL
#include "dll.h"
#include "cryptlib.h"
#include "filters.h"
#include "smartptr.h"
#include "misc.h"
#ifdef CRYPTOPP_WIN32_AVAILABLE
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0400
#include <windows.h>
@ -19,23 +20,16 @@
#define _CRT_DEBUGGER_HOOK _crt_debugger_hook
#else
#define _CRT_DEBUGGER_HOOK __crt_debugger_hook
#endif // _M_IX86
#endif
extern "C" {_CRTIMP void __cdecl _CRT_DEBUGGER_HOOK(int);}
#endif // _MSC_VER
#endif // CRYPTOPP_WIN32_AVAILABLE
#include "stdcpp.h"
#include "smartptr.h"
#include "trap.h"
#endif
#endif
#include <iostream>
#if GCC_DIAGNOSTIC_AWARE
# pragma GCC diagnostic ignored "-Wunused-value"
# pragma GCC diagnostic ignored "-Wunused-variable"
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# pragma GCC diagnostic ignored "-Wunneeded-internal-declaration"
#endif // GCC Diagnostics
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4100)
#endif
NAMESPACE_BEGIN(CryptoPP)
@ -43,7 +37,7 @@ extern PowerUpSelfTestStatus g_powerUpSelfTestStatus;
SecByteBlock g_actualMac;
unsigned long g_macFileLocation = 0;
// use a random dummy std::string here, to be searched/replaced later with the real MAC
// use a random dummy string here, to be searched/replaced later with the real MAC
static const byte s_moduleMac[CryptoPP::HMAC<CryptoPP::SHA1>::DIGESTSIZE] = CRYPTOPP_DUMMY_DLL_MAC;
CRYPTOPP_COMPILE_ASSERT(sizeof(s_moduleMac) == CryptoPP::SHA1::DIGESTSIZE);
@ -77,6 +71,7 @@ void X917RNG_KnownAnswerTest(
const char *output,
CIPHER *dummy = NULL)
{
CRYPTOPP_UNUSED(dummy);
#ifdef OS_RNG_AVAILABLE
std::string decodedKey, decodedSeed, decodedDeterministicTimeVector;
StringSource(key, true, new HexDecoder(new StringSink(decodedKey)));
@ -117,6 +112,7 @@ void SymmetricEncryptionKnownAnswerTest(
const char *ctr,
CIPHER *dummy = NULL)
{
CRYPTOPP_UNUSED(dummy);
std::string decodedKey;
StringSource(key, true, new HexDecoder(new StringSink(decodedKey)));
@ -151,6 +147,7 @@ void KnownAnswerTest(HashTransformation &hash, const char *message, const char *
template <class HASH>
void SecureHashKnownAnswerTest(const char *message, const char *digest, HASH *dummy = NULL)
{
CRYPTOPP_UNUSED(dummy);
HASH hash;
KnownAnswerTest(hash, message, digest);
}
@ -158,6 +155,7 @@ void SecureHashKnownAnswerTest(const char *message, const char *digest, HASH *du
template <class MAC>
void MAC_KnownAnswerTest(const char *key, const char *message, const char *digest, MAC *dummy = NULL)
{
CRYPTOPP_UNUSED(dummy);
std::string decodedKey;
StringSource(key, true, new HexDecoder(new StringSink(decodedKey)));
@ -171,6 +169,7 @@ void SignatureKnownAnswerTest(const char *key, const char *message, const char *
typename SCHEME::Signer signer(StringSource(key, true, new HexDecoder).Ref());
typename SCHEME::Verifier verifier(signer);
CRYPTOPP_UNUSED(dummy);
RandomPool rng;
EqualityComparisonFilter comparison;
@ -248,6 +247,7 @@ void SignaturePairwiseConsistencyTest(const char *key, SCHEME *dummy = NULL)
typename SCHEME::Signer signer(StringSource(key, true, new HexDecoder).Ref());
typename SCHEME::Verifier verifier(signer);
CRYPTOPP_UNUSED(dummy);
SignaturePairwiseConsistencyTest(signer, verifier);
}
@ -259,14 +259,14 @@ MessageAuthenticationCode * NewIntegrityCheckingMAC()
bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation)
{
auto_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC());
member_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC());
unsigned int macSize = mac->DigestSize();
SecByteBlock tempMac;
SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac;
actualMac.resize(macSize);
unsigned long tempLocation;
unsigned long tempLocation = 0;
unsigned long &macFileLocation = pMacFileLocation ? *pMacFileLocation : tempLocation;
macFileLocation = 0;
@ -275,7 +275,7 @@ bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModule
std::ifstream moduleStream;
#ifdef CRYPTOPP_WIN32_AVAILABLE
HMODULE h;
HMODULE h = NULL;
{
char moduleFilenameBuf[MAX_PATH] = "";
if (moduleFilename == NULL)
@ -355,7 +355,7 @@ bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModule
nextSubSectionStart = 0;
unsigned int entriesToReadFromDisk[] = {IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_DIRECTORY_ENTRY_IAT};
for (unsigned int i=0; i<COUNTOF(entriesToReadFromDisk); i++)
for (unsigned int i=0; i<sizeof(entriesToReadFromDisk)/sizeof(entriesToReadFromDisk[0]); i++)
{
const IMAGE_DATA_DIRECTORY &entry = phnt->OptionalHeader.DataDirectory[entriesToReadFromDisk[i]];
const byte *entryMemStart = memBase + entry.VirtualAddress;
@ -599,10 +599,10 @@ NAMESPACE_END
// DllMain needs to be in the global namespace
BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
DWORD dwReason,
LPVOID /*lpReserved*/)
{
if (ul_reason_for_call == DLL_PROCESS_ATTACH)
if (dwReason == DLL_PROCESS_ATTACH)
{
CryptoPP::s_hModule = (HMODULE)hModule;
CryptoPP::DoDllPowerUpSelfTest();

View File

@ -1,7 +1,15 @@
#ifndef CRYPTOPP_FLTRIMPL_H
#define CRYPTOPP_FLTRIMPL_H
#include "trap.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4100)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-value"
#endif
#define FILTER_BEGIN \
switch (m_continueAt) \
@ -12,7 +20,7 @@
#define FILTER_END_NO_MESSAGE_END_NO_RETURN \
break; \
default: \
CRYPTOPP_ASSERT(false); \
assert(false); \
}
#define FILTER_END_NO_MESSAGE_END \
@ -66,4 +74,12 @@
#define FILTER_OUTPUT_MAYBE_MODIFIABLE(site, output, length, messageEnd, modifiable) \
FILTER_OUTPUT2_MAYBE_MODIFIABLE(site, 0, output, length, messageEnd, modifiable)
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic pop
#endif
#endif

47
gcm.cpp
View File

@ -3,6 +3,11 @@
// use "cl /EP /P /DCRYPTOPP_GENERATE_X64_MASM gcm.cpp" to generate MASM code
#include "pch.h"
#include "config.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4189)
#endif
#ifndef CRYPTOPP_IMPORTS
#ifndef CRYPTOPP_GENERATE_X64_MASM
@ -222,12 +227,12 @@ void GCM_Base::SetKeyWithoutResync(const byte *userKey, size_t keylength, const
s_reductionTable[0] = 0;
word16 x = 0x01c2;
s_reductionTable[1] = ByteReverse(x);
for (int i=2; i<=0x80; i*=2)
for (unsigned int ii=2; ii<=0x80; ii*=2)
{
x <<= 1;
s_reductionTable[i] = ByteReverse(x);
for (int j=1; j<i; j++)
s_reductionTable[i+j] = s_reductionTable[i] ^ s_reductionTable[j];
s_reductionTable[ii] = ByteReverse(x);
for (unsigned int jj=1; jj<ii; jj++)
s_reductionTable[ii+jj] = s_reductionTable[ii] ^ s_reductionTable[jj];
}
s_reductionTableInitialized = true;
}
@ -334,7 +339,7 @@ unsigned int GCM_Base::OptimalDataAlignment() const
GetBlockCipher().OptimalDataAlignment();
}
#ifdef _MSC_VER
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4731) // frame pointer register 'ebp' modified by inline assembly code
#endif
@ -574,7 +579,7 @@ size_t GCM_Base::AuthenticateBlocks(const byte *data, size_t len)
#ifdef __GNUC__
__asm__ __volatile__
(
GNU_AS_INTEL_SYNTAX
".intel_syntax noprefix;"
#elif defined(CRYPTOPP_GENERATE_X64_MASM)
ALIGN 8
GCM_AuthenticateBlocks_2K PROC FRAME
@ -591,8 +596,13 @@ size_t GCM_Base::AuthenticateBlocks(const byte *data, size_t len)
AS2( shr WORD_REG(dx), 4 )
#endif
#if CRYPTOPP_BOOL_X32
AS1(push rbx)
AS1(push rbp)
#else
AS_PUSH_IF86( bx)
AS_PUSH_IF86( bp)
#endif
#ifdef __GNUC__
AS2( mov AS_REG_7, WORD_REG(di))
@ -671,12 +681,9 @@ size_t GCM_Base::AuthenticateBlocks(const byte *data, size_t len)
AS2( movdqa xmm1, xmm2 )
AS2( pslldq xmm2, 1 )
AS2( pxor xmm5, xmm2 )
AS2( psrldq xmm0, 15 )
#if defined(CRYPTOPP_CLANG_INTEGRATED_ASSEMBLER)
AS2( movd WORD_REG32(di), xmm0 )
#else
AS2( movd WORD_REG(di), xmm0 )
#endif
AS2( movzx eax, WORD PTR [RED_TABLE + WORD_REG(di)*2] )
AS2( shl eax, 8 )
@ -685,21 +692,12 @@ size_t GCM_Base::AuthenticateBlocks(const byte *data, size_t len)
AS2( pxor xmm4, xmm5 )
AS2( psrldq xmm1, 15 )
#if defined(CRYPTOPP_CLANG_INTEGRATED_ASSEMBLER)
AS2( movd WORD_REG32(di), xmm1 )
#else
AS2( movd WORD_REG(di), xmm1 )
#endif
AS2( xor ax, WORD PTR [RED_TABLE + WORD_REG(di)*2] )
AS2( shl eax, 8 )
AS2( psrldq xmm0, 15 )
#if defined(CRYPTOPP_CLANG_INTEGRATED_ASSEMBLER)
AS2( movd WORD_REG32(di), xmm0 )
#else
AS2( movd WORD_REG(di), xmm0 )
#endif
AS2( xor ax, WORD PTR [RED_TABLE + WORD_REG(di)*2] )
AS2( movd xmm0, eax )
@ -710,11 +708,16 @@ size_t GCM_Base::AuthenticateBlocks(const byte *data, size_t len)
ASJ( jnz, 0, b )
AS2( movdqa [WORD_REG(si)], xmm0 )
#if CRYPTOPP_BOOL_X32
AS1(pop rbp)
AS1(pop rbx)
#else
AS_POP_IF86( bp)
AS_POP_IF86( bx)
#endif
#ifdef __GNUC__
GNU_AS_ATT_SYNTAX
".att_syntax prefix;"
:
: "c" (data), "d" (len/16), "S" (hashBuffer), "D" (s_reductionTable)
: "memory", "cc", "%eax"
@ -737,7 +740,7 @@ size_t GCM_Base::AuthenticateBlocks(const byte *data, size_t len)
#ifdef __GNUC__
__asm__ __volatile__
(
GNU_AS_INTEL_SYNTAX
".intel_syntax noprefix;"
#elif defined(CRYPTOPP_GENERATE_X64_MASM)
ALIGN 8
GCM_AuthenticateBlocks_64K PROC FRAME
@ -791,7 +794,7 @@ size_t GCM_Base::AuthenticateBlocks(const byte *data, size_t len)
AS2( movdqa [WORD_REG(si)], xmm0 )
#ifdef __GNUC__
GNU_AS_ATT_SYNTAX
".att_syntax prefix;"
:
: "c" (data), "d" (len/16), "S" (hashBuffer)
: "memory", "cc", "%edi", "%eax"

View File

@ -16,7 +16,7 @@ public:
GF256(byte modulus) : m_modulus(modulus) {}
Element RandomElement(RandomNumberGenerator &rng, int ignored = 0) const
{CRYPTOPP_UNUSED(ignored);return rng.GenerateByte();}
{CRYPTOPP_UNUSED(ignored); return rng.GenerateByte();}
bool Equal(Element a, Element b) const
{return a==b;}
@ -40,7 +40,7 @@ public:
{return a^=b;}
Element Double(Element a) const
{CRYPTOPP_UNUSED(a);return 0;}
{CRYPTOPP_UNUSED(a); return 0;}
Element One() const
{return 1;}

View File

@ -3,7 +3,6 @@
#include "pch.h"
#include "misc.h"
#include "gf2_32.h"
#include "trap.h"
NAMESPACE_BEGIN(CryptoPP)
@ -53,7 +52,7 @@ GF2_32::Element GF2_32::MultiplicativeInverse(Element a) const
word32 g0=m_modulus, g1=a, g2=a;
word32 v0=0, v1=1, v2=1;
CRYPTOPP_ASSERT(g1);
assert(g1);
while (!(g2 & 0x80000000))
{
@ -71,25 +70,25 @@ GF2_32::Element GF2_32::MultiplicativeInverse(Element a) const
{
if (g1 < g0 || ((g0^g1) < g0 && (g0^g1) < g1))
{
CRYPTOPP_ASSERT(BitPrecision(g1) <= BitPrecision(g0));
assert(BitPrecision(g1) <= BitPrecision(g0));
g2 = g1;
v2 = v1;
}
else
{
CRYPTOPP_ASSERT(BitPrecision(g1) > BitPrecision(g0));
assert(BitPrecision(g1) > BitPrecision(g0));
g2 = g0; g0 = g1; g1 = g2;
v2 = v0; v0 = v1; v1 = v2;
}
while ((g0^g2) >= g2)
{
CRYPTOPP_ASSERT(BitPrecision(g0) > BitPrecision(g2));
assert(BitPrecision(g0) > BitPrecision(g2));
g2 <<= 1;
v2 <<= 1;
}
CRYPTOPP_ASSERT(BitPrecision(g0) == BitPrecision(g2));
assert(BitPrecision(g0) == BitPrecision(g2));
g0 ^= g2;
v0 ^= v2;
}

View File

@ -2,6 +2,7 @@
#define CRYPTOPP_GF2_32_H
#include "cryptlib.h"
#include "secblock.h"
#include "misc.h"
NAMESPACE_BEGIN(CryptoPP)
@ -16,7 +17,7 @@ public:
GF2_32(word32 modulus=0x0000008D) : m_modulus(modulus) {}
Element RandomElement(RandomNumberGenerator &rng, int ignored = 0) const
{CRYPTOPP_UNUSED(ignored);return rng.GenerateWord32();}
{CRYPTOPP_UNUSED(ignored); return rng.GenerateWord32();}
bool Equal(Element a, Element b) const
{return a==b;}
@ -40,7 +41,7 @@ public:
{return a^=b;}
Element Double(Element a) const
{CRYPTOPP_UNUSED(a);return 0;}
{CRYPTOPP_UNUSED(a); return 0;}
Element MultiplicativeIdentity() const
{return 1;}

View File

@ -1,16 +1,19 @@
// gf2n.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
#ifndef CRYPTOPP_IMPORTS
#include "gf2n.h"
#include "cryptlib.h"
#include "algebra.h"
#include "words.h"
#include "randpool.h"
#include "filters.h"
#include "smartptr.h"
#include "gf2n.h"
#include "asn.h"
#include "oids.h"
#include "trap.h"
#include <iostream>
@ -23,7 +26,7 @@ PolynomialMod2::PolynomialMod2()
PolynomialMod2::PolynomialMod2(word value, size_t bitLength)
: reg(BitsToWords(bitLength))
{
CRYPTOPP_ASSERT(value==0 || reg.size()>0);
assert(value==0 || reg.size()>0);
if (reg.size() > 0)
{
@ -50,7 +53,7 @@ void PolynomialMod2::Randomize(RandomNumberGenerator &rng, size_t nbits)
PolynomialMod2 PolynomialMod2::AllOnes(size_t bitLength)
{
PolynomialMod2 result((word)0, bitLength);
SetWords(result.reg, ~(word)0, result.reg.size());
SetWords(result.reg, word(SIZE_MAX), result.reg.size());
if (bitLength%WORD_BITS)
result.reg[result.reg.size()-1] = (word)Crop(result.reg[result.reg.size()-1], bitLength%WORD_BITS);
return result;
@ -211,7 +214,6 @@ unsigned int PolynomialMod2::Parity() const
PolynomialMod2& PolynomialMod2::operator=(const PolynomialMod2& t)
{
// Assign guards for self-assignment
reg.Assign(t.reg);
return *this;
}
@ -551,7 +553,7 @@ GF2NP::Element GF2NP::SquareRoot(const Element &a) const
GF2NP::Element GF2NP::HalfTrace(const Element &a) const
{
CRYPTOPP_ASSERT(m%2 == 1);
assert(m%2 == 1);
Element h = a;
for (unsigned int i=1; i<=(m-1)/2; i++)
h = Add(Square(Square(h)), a);
@ -590,7 +592,7 @@ GF2NT::GF2NT(unsigned int t0, unsigned int t1, unsigned int t2)
, t0(t0), t1(t1)
, result((word)0, m)
{
CRYPTOPP_ASSERT(t0 > t1 && t1 > t2 && t2==0);
assert(t0 > t1 && t1 > t2 && t2==0);
}
const GF2NT::Element& GF2NT::MultiplicativeInverse(const Element &a) const
@ -608,7 +610,7 @@ const GF2NT::Element& GF2NT::MultiplicativeInverse(const Element &a) const
SetWords(T, 0, 3*m_modulus.reg.size());
b[0]=1;
CRYPTOPP_ASSERT(a.reg.size() <= m_modulus.reg.size());
assert(a.reg.size() <= m_modulus.reg.size());
CopyWords(f, a.reg, a.reg.size());
CopyWords(g, m_modulus.reg, m_modulus.reg.size());
@ -620,7 +622,7 @@ const GF2NT::Element& GF2NT::MultiplicativeInverse(const Element &a) const
ShiftWordsRightByWords(f, fgLen, 1);
if (c[bcLen-1])
bcLen++;
CRYPTOPP_ASSERT(bcLen <= m_modulus.reg.size());
assert(bcLen <= m_modulus.reg.size());
ShiftWordsLeftByWords(c, bcLen, 1);
k+=WORD_BITS;
t=f[0];
@ -651,7 +653,7 @@ const GF2NT::Element& GF2NT::MultiplicativeInverse(const Element &a) const
{
c[bcLen] = t;
bcLen++;
CRYPTOPP_ASSERT(bcLen <= m_modulus.reg.size());
assert(bcLen <= m_modulus.reg.size());
}
if (f[fgLen-1]==0 && g[fgLen-1]==0)
@ -791,7 +793,7 @@ const GF2NT::Element& GF2NT::Reduced(const Element &a) const
if ((t0-t1)%WORD_BITS > t0%WORD_BITS)
b[i-(t0-t1)/WORD_BITS-1] ^= temp << (WORD_BITS - (t0-t1)%WORD_BITS);
else
CRYPTOPP_ASSERT(temp << (WORD_BITS - (t0-t1)%WORD_BITS) == 0);
assert(temp << (WORD_BITS - (t0-t1)%WORD_BITS) == 0);
}
else
b[i-(t0-t1)/WORD_BITS] ^= temp;
@ -842,7 +844,6 @@ void GF2NPP::DEREncode(BufferedTransformation &bt) const
GF2NP * BERDecodeGF2NP(BufferedTransformation &bt)
{
// VC60 workaround: auto_ptr lacks reset()
member_ptr<GF2NP> result;
BERSequenceDecoder seq(bt);

12
gf2n.h
View File

@ -7,7 +7,7 @@
#include "secblock.h"
#include "algebra.h"
#include "misc.h"
#include "trap.h"
#include "asn.h"
#include <iosfwd>
@ -91,9 +91,9 @@ public:
//* Precondition: bt.MaxRetrievable() >= inputLen
void Decode(BufferedTransformation &bt, size_t inputLen);
//! encode value as big-endian octet std::string
//! encode value as big-endian octet string
void DEREncodeAsOctetString(BufferedTransformation &bt, size_t length) const;
//! decode value as big-endian octet std::string
//! decode value as big-endian octet string
void BERDecodeAsOctetString(BufferedTransformation &bt, size_t length);
//@}
@ -286,16 +286,16 @@ public:
virtual GF2NP * Clone() const {return new GF2NP(*this);}
virtual void DEREncode(BufferedTransformation &bt) const
{CRYPTOPP_UNUSED(bt);CRYPTOPP_ASSERT(false);} // no ASN.1 syntax yet for general polynomial basis
{CRYPTOPP_UNUSED(bt); assert(false);} // no ASN.1 syntax yet for general polynomial basis
void DEREncodeElement(BufferedTransformation &out, const Element &a) const;
void BERDecodeElement(BufferedTransformation &in, Element &a) const;
bool Equal(const Element &a, const Element &b) const
{CRYPTOPP_ASSERT(a.Degree() < m_modulus.Degree() && b.Degree() < m_modulus.Degree()); return a.Equals(b);}
{assert(a.Degree() < m_modulus.Degree() && b.Degree() < m_modulus.Degree()); return a.Equals(b);}
bool IsUnit(const Element &a) const
{CRYPTOPP_ASSERT(a.Degree() < m_modulus.Degree()); return !!a;}
{assert(a.Degree() < m_modulus.Degree()); return !!a;}
unsigned int MaxElementBitLength() const
{return m;}

View File

@ -1,14 +1,21 @@
// dsa.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
// TODO: fix the C4589 warnings
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4189 4589)
#endif
#ifndef CRYPTOPP_IMPORTS
#include "gfpcrypt.h"
#include "integer.h"
#include "nbtheory.h"
#include "asn.h"
#include "oids.h"
#include "nbtheory.h"
#include "trap.h"
#include "misc.h"
NAMESPACE_BEGIN(CryptoPP)
@ -70,8 +77,11 @@ void DL_SignatureMessageEncodingMethod_DSA::ComputeMessageRepresentative(RandomN
HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
byte *representative, size_t representativeBitLength) const
{
CRYPTOPP_ASSERT(recoverableMessageLength == 0);
CRYPTOPP_ASSERT(hashIdentifier.second == 0);
CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(recoverableMessage), CRYPTOPP_UNUSED(recoverableMessageLength);
CRYPTOPP_UNUSED(messageEmpty), CRYPTOPP_UNUSED(hashIdentifier);
assert(recoverableMessageLength == 0);
assert(hashIdentifier.second == 0);
const size_t representativeByteLength = BitsToBytes(representativeBitLength);
const size_t digestSize = hash.DigestSize();
const size_t paddingLength = SaturatingSubtract(representativeByteLength, digestSize);
@ -92,8 +102,12 @@ void DL_SignatureMessageEncodingMethod_NR::ComputeMessageRepresentative(RandomNu
HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
byte *representative, size_t representativeBitLength) const
{
CRYPTOPP_ASSERT(recoverableMessageLength == 0);
CRYPTOPP_ASSERT(hashIdentifier.second == 0);
CRYPTOPP_UNUSED(rng);CRYPTOPP_UNUSED(recoverableMessage); CRYPTOPP_UNUSED(recoverableMessageLength);
CRYPTOPP_UNUSED(hash); CRYPTOPP_UNUSED(hashIdentifier); CRYPTOPP_UNUSED(messageEmpty);
CRYPTOPP_UNUSED(representative); CRYPTOPP_UNUSED(representativeBitLength);
assert(recoverableMessageLength == 0);
assert(hashIdentifier.second == 0);
const size_t representativeByteLength = BitsToBytes(representativeBitLength);
const size_t digestSize = hash.DigestSize();
const size_t paddingLength = SaturatingSubtract(representativeByteLength, digestSize);
@ -187,8 +201,23 @@ void DL_GroupParameters_IntegerBased::GenerateRandom(RandomNumberGenerator &rng,
Initialize(p, q, g);
}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
void DL_GroupParameters_IntegerBased::EncodeElement(bool reversible, const Element &element, byte *encoded) const
{
CRYPTOPP_UNUSED(reversible);
element.Encode(encoded, GetModulus().ByteCount());
}
unsigned int DL_GroupParameters_IntegerBased::GetEncodedElementSize(bool reversible) const
{
CRYPTOPP_UNUSED(reversible);
return GetModulus().ByteCount();
}
#endif
Integer DL_GroupParameters_IntegerBased::DecodeElement(const byte *encoded, bool checkForGroupMembership) const
{
CRYPTOPP_UNUSED(checkForGroupMembership);
Integer g(encoded, GetModulus().ByteCount());
if (!ValidateElement(1, g, NULL))
throw DL_BadElement();

View File

@ -6,17 +6,22 @@
*/
#include "config.h"
#include "integer.h"
#include "pubkey.h"
#include "modexppc.h"
#include "sha.h"
#include "algparam.h"
#include "asn.h"
#include "smartptr.h"
#include "hmac.h"
#include "trap.h"
#include <limits.h>
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4189)
#endif
#include "cryptlib.h"
#include "pubkey.h"
#include "integer.h"
#include "modexppc.h"
#include "algparam.h"
#include "smartptr.h"
#include "sha.h"
#include "asn.h"
#include "hmac.h"
#include "misc.h"
NAMESPACE_BEGIN(CryptoPP)
@ -28,8 +33,6 @@ class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBased : public A
typedef DL_GroupParameters_IntegerBased ThisClass;
public:
virtual ~DL_GroupParameters_IntegerBased() { }
void Initialize(const DL_GroupParameters_IntegerBased &params)
{Initialize(params.GetModulus(), params.GetSubgroupOrder(), params.GetSubgroupGenerator());}
void Initialize(RandomNumberGenerator &rng, unsigned int pbits)
@ -55,9 +58,18 @@ public:
bool ValidateGroup(RandomNumberGenerator &rng, unsigned int level) const;
bool ValidateElement(unsigned int level, const Integer &element, const DL_FixedBasePrecomputation<Integer> *precomp) const;
bool FastSubgroupCheckAvailable() const {return GetCofactor() == 2;}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
// Cygwin i386 crash at -O3; see .
void EncodeElement(bool reversible, const Element &element, byte *encoded) const;
unsigned int GetEncodedElementSize(bool reversible) const;
#else
void EncodeElement(bool reversible, const Element &element, byte *encoded) const
{element.Encode(encoded, GetModulus().ByteCount());}
unsigned int GetEncodedElementSize(bool reversible) const {return GetModulus().ByteCount();}
{CRYPTOPP_UNUSED(reversible); element.Encode(encoded, GetModulus().ByteCount());}
unsigned int GetEncodedElementSize(bool reversible) const
{CRYPTOPP_UNUSED(reversible); return GetModulus().ByteCount();}
#endif
Integer DecodeElement(const byte *encoded, bool checkForGroupMembership) const;
Integer ConvertElementToInteger(const Element &element) const
{return element;}
@ -72,6 +84,10 @@ public:
void SetSubgroupOrder(const Integer &q)
{m_q = q; ParametersChanged();}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_GroupParameters_IntegerBased() {}
#endif
protected:
Integer ComputeGroupOrder(const Integer &modulus) const
{return modulus-(GetFieldType() == 1 ? 1 : -1);}
@ -92,7 +108,6 @@ class CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBasedImpl : public DL_GroupPa
public:
typedef typename GROUP_PRECOMP::Element Element;
virtual ~DL_GroupParameters_IntegerBasedImpl() { }
// GeneratibleCryptoMaterial interface
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
@ -117,6 +132,10 @@ public:
{return GetModulus() == rhs.GetModulus() && GetGenerator() == rhs.GetGenerator() && this->GetSubgroupOrder() == rhs.GetSubgroupOrder();}
bool operator!=(const DL_GroupParameters_IntegerBasedImpl<GROUP_PRECOMP, BASE_PRECOMP> &rhs) const
{return !operator==(rhs);}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_GroupParameters_IntegerBasedImpl() {}
#endif
};
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputation>;
@ -125,8 +144,6 @@ CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputa
class CRYPTOPP_DLL DL_GroupParameters_GFP : public DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputation>
{
public:
virtual ~DL_GroupParameters_GFP() { }
// DL_GroupParameters
bool IsIdentity(const Integer &element) const {return element == Integer::One();}
void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
@ -141,6 +158,10 @@ public:
Element MultiplyElements(const Element &a, const Element &b) const;
Element CascadeExponentiate(const Element &element1, const Integer &exponent1, const Element &element2, const Integer &exponent2) const;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_GroupParameters_GFP() {}
#endif
protected:
int GetFieldType() const {return 1;}
};
@ -151,6 +172,10 @@ class CRYPTOPP_DLL DL_GroupParameters_GFP_DefaultSafePrime : public DL_GroupPara
public:
typedef NoCofactorMultiplication DefaultCofactorOption;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_GroupParameters_GFP_DefaultSafePrime() {}
#endif
protected:
unsigned int GetDefaultSubgroupOrderSize(unsigned int modulusSize) const {return modulusSize-1;}
};
@ -160,7 +185,6 @@ template <class T>
class DL_Algorithm_GDSA : public DL_ElgamalLikeSignatureAlgorithm<T>
{
public:
virtual ~DL_Algorithm_GDSA() { }
static const char * CRYPTOPP_API StaticAlgorithmName() {return "DSA-1363";}
void Sign(const DL_GroupParameters<T> &params, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const
@ -169,7 +193,7 @@ public:
r %= q;
Integer kInv = k.InverseMod(q);
s = (kInv * (x*r + e)) % q;
CRYPTOPP_ASSERT(!!r && !!s);
assert(!!r && !!s);
}
bool Verify(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &e, const Integer &r, const Integer &s) const
@ -184,6 +208,10 @@ public:
// verify r == (g^u1 * y^u2 mod p) mod q
return r == params.ConvertElementToInteger(publicKey.CascadeExponentiateBaseAndPublicElement(u1, u2)) % q;
}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Algorithm_GDSA() {}
#endif
};
CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA<Integer>;
@ -193,7 +221,6 @@ template <class T>
class DL_Algorithm_NR : public DL_ElgamalLikeSignatureAlgorithm<T>
{
public:
virtual ~DL_Algorithm_NR() { }
static const char * CRYPTOPP_API StaticAlgorithmName() {return "NR";}
void Sign(const DL_GroupParameters<T> &params, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const
@ -201,7 +228,7 @@ public:
const Integer &q = params.GetSubgroupOrder();
r = (r + e) % q;
s = (k - x*r) % q;
CRYPTOPP_ASSERT(!!r);
assert(!!r);
}
bool Verify(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &e, const Integer &r, const Integer &s) const
@ -213,6 +240,10 @@ public:
// check r == (m_g^s * m_y^r + m) mod m_q
return r == (params.ConvertElementToInteger(publicKey.CascadeExponentiateBaseAndPublicElement(s, r)) + e) % q;
}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Algorithm_NR() {}
#endif
};
/*! DSA public key format is defined in 7.3.3 of RFC 2459. The
@ -233,6 +264,10 @@ public:
{this->SetPublicElement(Integer(bt));}
void DEREncodePublicKey(BufferedTransformation &bt) const
{this->GetPublicElement().DEREncode(bt);}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_PublicKey_GFP() {}
#endif
};
//! DL private key (in GF(p) groups)
@ -252,6 +287,10 @@ public:
{this->AccessGroupParameters().Initialize(p, g); this->SetPrivateExponent(x);}
void Initialize(const Integer &p, const Integer &q, const Integer &g, const Integer &x)
{this->AccessGroupParameters().Initialize(p, q, g); this->SetPrivateExponent(x);}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_PrivateKey_GFP() {}
#endif
};
//! DL signing/verification keys (in GF(p) groups)
@ -260,6 +299,10 @@ struct DL_SignatureKeys_GFP
typedef DL_GroupParameters_GFP GroupParameters;
typedef DL_PublicKey_GFP<GroupParameters> PublicKey;
typedef DL_PrivateKey_GFP<GroupParameters> PrivateKey;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_SignatureKeys_GFP() {}
#endif
};
//! DL encryption/decryption keys (in GF(p) groups)
@ -268,6 +311,10 @@ struct DL_CryptoKeys_GFP
typedef DL_GroupParameters_GFP_DefaultSafePrime GroupParameters;
typedef DL_PublicKey_GFP<GroupParameters> PublicKey;
typedef DL_PrivateKey_GFP<GroupParameters> PrivateKey;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_CryptoKeys_GFP() {}
#endif
};
//! provided for backwards compatibility, this class uses the old non-standard Crypto++ key format
@ -307,6 +354,10 @@ public:
this->GetPublicElement().DEREncode(seq);
seq.MessageEnd();
}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_PublicKey_GFP_OldFormat() {}
#endif
};
//! provided for backwards compatibility, this class uses the old non-standard Crypto++ key format
@ -348,6 +399,10 @@ public:
this->GetPrivateExponent().DEREncode(seq);
seq.MessageEnd();
}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_PrivateKey_GFP_OldFormat() {}
#endif
};
//! <a href="http://www.weidai.com/scan-mirror/sig.html#DSA-1363">DSA-1363</a>
@ -358,6 +413,9 @@ struct GDSA : public DL_SS<
DL_SignatureMessageEncodingMethod_DSA,
H>
{
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~GDSA() {}
#endif
};
//! <a href="http://www.weidai.com/scan-mirror/sig.html#NR">NR</a>
@ -368,6 +426,9 @@ struct NR : public DL_SS<
DL_SignatureMessageEncodingMethod_NR,
H>
{
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~NR() {}
#endif
};
//! DSA group parameters, these are GF(p) group parameters that are allowed by the DSA standard
@ -384,6 +445,10 @@ public:
{return pbits >= MIN_PRIME_LENGTH && pbits <= MAX_PRIME_LENGTH && pbits % PRIME_LENGTH_MULTIPLE == 0;}
enum {MIN_PRIME_LENGTH = 1024, MAX_PRIME_LENGTH = 3072, PRIME_LENGTH_MULTIPLE = 1024};
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_GroupParameters_DSA() {}
#endif
};
template <class H>
@ -394,6 +459,10 @@ struct DL_Keys_DSA
{
typedef DL_PublicKey_GFP<DL_GroupParameters_DSA> PublicKey;
typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_GFP<DL_GroupParameters_DSA>, DSA2<SHA> > PrivateKey;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_Keys_DSA() {}
#endif
};
//! <a href="http://en.wikipedia.org/wiki/Digital_Signature_Algorithm">DSA</a>, as specified in FIPS 186-3
@ -408,6 +477,14 @@ class DSA2 : public DL_SS<
{
public:
static std::string CRYPTOPP_API StaticAlgorithmName() {return "DSA/" + (std::string)H::StaticAlgorithmName();}
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
enum {MIN_PRIME_LENGTH = 1024, MAX_PRIME_LENGTH = 3072, PRIME_LENGTH_MULTIPLE = 1024};
#endif
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DSA2() {}
#endif
};
//! DSA with SHA-1, typedef'd for backwards compatibility
@ -422,7 +499,6 @@ template <class MAC, bool DHAES_MODE>
class DL_EncryptionAlgorithm_Xor : public DL_SymmetricEncryptionAlgorithm
{
public:
virtual ~DL_EncryptionAlgorithm_Xor() { }
bool ParameterSupported(const char *name) const {return strcmp(name, Name::EncodingParameters()) == 0;}
size_t GetSymmetricKeyLength(size_t plaintextLength) const
{return plaintextLength + MAC::DEFAULT_KEYLENGTH;}
@ -432,7 +508,8 @@ public:
{return (unsigned int)SaturatingSubtract(ciphertextLength, (unsigned int)MAC::DIGESTSIZE);}
void SymmetricEncrypt(RandomNumberGenerator &rng, const byte *key, const byte *plaintext, size_t plaintextLength, byte *ciphertext, const NameValuePairs &parameters) const
{
const byte *cipherKey, *macKey;
CRYPTOPP_UNUSED(rng);
const byte *cipherKey = NULL, *macKey = NULL;
if (DHAES_MODE)
{
macKey = key;
@ -492,6 +569,10 @@ public:
xorbuf(plaintext, ciphertext, cipherKey, plaintextLength);
return DecodingResult(plaintextLength);
}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_EncryptionAlgorithm_Xor() {}
#endif
};
//! _
@ -499,7 +580,6 @@ template <class T, bool DHAES_MODE, class KDF>
class DL_KeyDerivationAlgorithm_P1363 : public DL_KeyDerivationAlgorithm<T>
{
public:
virtual ~DL_KeyDerivationAlgorithm_P1363() { }
bool ParameterSupported(const char *name) const {return strcmp(name, Name::KeyDerivationParameters()) == 0;}
void Derive(const DL_GroupParameters<T> &params, byte *derivedKey, size_t derivedLength, const T &agreedElement, const T &ephemeralPublicKey, const NameValuePairs &parameters) const
{
@ -520,6 +600,10 @@ public:
parameters.GetValue(Name::KeyDerivationParameters(), derivationParameters);
KDF::DeriveKey(derivedKey, derivedLength, agreedSecret, agreedSecret.size(), derivationParameters.begin(), derivationParameters.size());
}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DL_KeyDerivationAlgorithm_P1363() {}
#endif
};
//! Discrete Log Integrated Encryption Scheme, AKA <a href="http://www.weidai.com/scan-mirror/ca.html#DLIES">DLIES</a>
@ -533,8 +617,16 @@ struct DLIES
DLIES<> >
{
static std::string CRYPTOPP_API StaticAlgorithmName() {return "DLIES";} // TODO: fix this after name is standardized
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~DLIES() {}
#endif
};
NAMESPACE_END
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif
#endif

Some files were not shown because too many files have changed in this diff Show More