Implement 40250 classic client port
This commit is contained in:
+143
@@ -0,0 +1,143 @@
|
||||
// 3way.cpp - modified by Wei Dai from Joan Daemen's 3way.c
|
||||
// The original code and all modifications are in the public domain.
|
||||
|
||||
#include "pch.h"
|
||||
#include "3way.h"
|
||||
#include "misc.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
#if defined(CRYPTOPP_DEBUG) && !defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
void ThreeWay_TestInstantiations()
|
||||
{
|
||||
ThreeWay::Encryption x1;
|
||||
ThreeWay::Decryption x2;
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
const word32 START_E = 0x0b0b; // round constant of first encryption round
|
||||
const word32 START_D = 0xb1b1; // round constant of first decryption round
|
||||
}
|
||||
|
||||
static inline word32 reverseBits(word32 a)
|
||||
{
|
||||
a = ((a & 0xAAAAAAAA) >> 1) | ((a & 0x55555555) << 1);
|
||||
a = ((a & 0xCCCCCCCC) >> 2) | ((a & 0x33333333) << 2);
|
||||
return ((a & 0xF0F0F0F0) >> 4) | ((a & 0x0F0F0F0F) << 4);
|
||||
}
|
||||
|
||||
#define mu(a0, a1, a2) \
|
||||
{ \
|
||||
a1 = reverseBits(a1); \
|
||||
word32 t = reverseBits(a0); \
|
||||
a0 = reverseBits(a2); \
|
||||
a2 = t; \
|
||||
}
|
||||
|
||||
#define pi_gamma_pi(a0, a1, a2) \
|
||||
{ \
|
||||
word32 b0, b2; \
|
||||
b2 = rotlConstant<1>(a2); \
|
||||
b0 = rotlConstant<22>(a0); \
|
||||
a0 = rotlConstant<1>(b0 ^ (a1|(~b2))); \
|
||||
a2 = rotlConstant<22>(b2 ^ (b0|(~a1))); \
|
||||
a1 ^= (b2|(~b0)); \
|
||||
}
|
||||
|
||||
// thanks to Paulo Barreto for this optimized theta()
|
||||
#define theta(a0, a1, a2) \
|
||||
{ \
|
||||
word32 b0, b1, c; \
|
||||
c = a0 ^ a1 ^ a2; \
|
||||
c = rotlConstant<16>(c) ^ rotlConstant<8>(c); \
|
||||
b0 = (a0 << 24) ^ (a2 >> 8) ^ (a1 << 8) ^ (a0 >> 24); \
|
||||
b1 = (a1 << 24) ^ (a0 >> 8) ^ (a2 << 8) ^ (a1 >> 24); \
|
||||
a0 ^= c ^ b0; \
|
||||
a1 ^= c ^ b1; \
|
||||
a2 ^= c ^ (b0 >> 16) ^ (b1 << 16); \
|
||||
}
|
||||
|
||||
#define rho(a0, a1, a2) \
|
||||
{ \
|
||||
theta(a0, a1, a2); \
|
||||
pi_gamma_pi(a0, a1, a2); \
|
||||
}
|
||||
|
||||
void ThreeWay::Base::UncheckedSetKey(const byte *uk, unsigned int length, const NameValuePairs ¶ms)
|
||||
{
|
||||
AssertValidKeyLength(length);
|
||||
|
||||
m_rounds = GetRoundsAndThrowIfInvalid(params, this);
|
||||
|
||||
for (unsigned int i=0; i<3; i++)
|
||||
m_k[i] = (word32)uk[4*i+3] | ((word32)uk[4*i+2]<<8) | ((word32)uk[4*i+1]<<16) | ((word32)uk[4*i]<<24);
|
||||
|
||||
if (!IsForwardTransformation())
|
||||
{
|
||||
theta(m_k[0], m_k[1], m_k[2]);
|
||||
mu(m_k[0], m_k[1], m_k[2]);
|
||||
m_k[0] = ByteReverse(m_k[0]);
|
||||
m_k[1] = ByteReverse(m_k[1]);
|
||||
m_k[2] = ByteReverse(m_k[2]);
|
||||
}
|
||||
}
|
||||
|
||||
void ThreeWay::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
typedef BlockGetAndPut<word32, BigEndian> Block;
|
||||
|
||||
word32 a0, a1, a2;
|
||||
Block::Get(inBlock)(a0)(a1)(a2);
|
||||
|
||||
word32 rc = START_E;
|
||||
|
||||
for(unsigned i=0; i<m_rounds; i++)
|
||||
{
|
||||
a0 ^= m_k[0] ^ (rc<<16);
|
||||
a1 ^= m_k[1];
|
||||
a2 ^= m_k[2] ^ rc;
|
||||
rho(a0, a1, a2);
|
||||
|
||||
rc <<= 1;
|
||||
if (rc&0x10000) rc ^= 0x11011;
|
||||
}
|
||||
a0 ^= m_k[0] ^ (rc<<16);
|
||||
a1 ^= m_k[1];
|
||||
a2 ^= m_k[2] ^ rc;
|
||||
theta(a0, a1, a2);
|
||||
|
||||
Block::Put(xorBlock, outBlock)(a0)(a1)(a2);
|
||||
}
|
||||
|
||||
void ThreeWay::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
typedef BlockGetAndPut<word32, LittleEndian> Block;
|
||||
|
||||
word32 a0, a1, a2;
|
||||
Block::Get(inBlock)(a0)(a1)(a2);
|
||||
|
||||
word32 rc = START_D;
|
||||
|
||||
mu(a0, a1, a2);
|
||||
for(unsigned i=0; i<m_rounds; i++)
|
||||
{
|
||||
a0 ^= m_k[0] ^ (rc<<16);
|
||||
a1 ^= m_k[1];
|
||||
a2 ^= m_k[2] ^ rc;
|
||||
rho(a0, a1, a2);
|
||||
|
||||
rc <<= 1;
|
||||
if (rc&0x10000) rc ^= 0x11011;
|
||||
}
|
||||
a0 ^= m_k[0] ^ (rc<<16);
|
||||
a1 ^= m_k[1];
|
||||
a2 ^= m_k[2] ^ rc;
|
||||
theta(a0, a1, a2);
|
||||
mu(a0, a1, a2);
|
||||
|
||||
Block::Put(xorBlock, outBlock)(a0)(a1)(a2);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// 3way.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file 3way.h
|
||||
/// \brief Classes for the 3-Way block cipher
|
||||
|
||||
#ifndef CRYPTOPP_THREEWAY_H
|
||||
#define CRYPTOPP_THREEWAY_H
|
||||
|
||||
#include "config.h"
|
||||
#include "seckey.h"
|
||||
#include "secblock.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief ThreeWay block cipher information
|
||||
struct ThreeWay_Info : public FixedBlockSize<12>, public FixedKeyLength<12>, public VariableRounds<11>
|
||||
{
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "3-Way";}
|
||||
};
|
||||
|
||||
/// \brief ThreeWay block cipher
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/3-Way">3-Way</a>
|
||||
class ThreeWay : public ThreeWay_Info, public BlockCipherDocumentation
|
||||
{
|
||||
/// \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:
|
||||
void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms);
|
||||
|
||||
protected:
|
||||
unsigned int m_rounds;
|
||||
FixedSizeSecBlock<word32, 3> m_k;
|
||||
};
|
||||
|
||||
/// \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;
|
||||
};
|
||||
|
||||
/// \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:
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
};
|
||||
|
||||
public:
|
||||
typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
|
||||
typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
|
||||
};
|
||||
|
||||
typedef ThreeWay::Encryption ThreeWayEncryption;
|
||||
typedef ThreeWay::Decryption ThreeWayDecryption;
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
# Crypto++ 8.4.0 — vendored from the 40250 client tree
|
||||
# (ClientVS22/extern/include/cryptopp, CRYPTOPP_VERSION 840). Needed for the
|
||||
# MT_PROTOCOL=classic backend's _IMPROVED_PACKET_ENCRYPTION_ cipher:
|
||||
# DH2 key agreement + hint-selected block ciphers (Twofish default) in CTR mode.
|
||||
# The server links this exact version (Server/.../extern/cryptopp_8_4_0.tar.gz).
|
||||
#
|
||||
# No upstream CMakeLists — we glob the library TUs and drop the test / bench /
|
||||
# adhoc / FIPS-selftest ones. ASM is disabled everywhere (CRYPTOPP_DISABLE_ASM)
|
||||
# so the same pure-C++/intrinsics build works on the Android NDK and iOS SDK;
|
||||
# the classic cipher doesn't need AES-NI / SHA-ext.
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
file(GLOB CRYPTOPP_SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
|
||||
|
||||
# TUs that are the cryptest program / benchmarks / dev scratch, not the library.
|
||||
set(_cp_exclude
|
||||
adhoc bench1 bench2 bench3 datatest dlltest fipsalgt fipstest pch
|
||||
regtest1 regtest2 regtest3 regtest4 test
|
||||
validat0 validat1 validat2 validat3 validat4 validat5
|
||||
validat6 validat7 validat8 validat9 validat10)
|
||||
foreach(_n ${_cp_exclude})
|
||||
list(REMOVE_ITEM CRYPTOPP_SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_n}.cpp")
|
||||
endforeach()
|
||||
|
||||
# Android: cpu.cpp does `#include "cpu-features.h"` (unconditionally on __ANDROID__)
|
||||
# and calls android_getCpuFeatures() etc. — those live in the NDK's cpufeatures
|
||||
# helper, which isn't on the sysroot include path by default.
|
||||
if(ANDROID)
|
||||
set(_ndk "${CMAKE_ANDROID_NDK}")
|
||||
if(NOT _ndk)
|
||||
set(_ndk "$ENV{ANDROID_NDK_HOME}")
|
||||
endif()
|
||||
set(_cpufeat "${_ndk}/sources/android/cpufeatures")
|
||||
if(EXISTS "${_cpufeat}/cpu-features.c")
|
||||
list(APPEND CRYPTOPP_SRC "${_cpufeat}/cpu-features.c")
|
||||
else()
|
||||
message(FATAL_ERROR "cryptopp/Android: cpu-features.c not found under ${_cpufeat}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
add_library(cryptopp STATIC ${CRYPTOPP_SRC})
|
||||
target_include_directories(cryptopp SYSTEM PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/..")
|
||||
if(ANDROID)
|
||||
target_include_directories(cryptopp SYSTEM PRIVATE "${_cpufeat}")
|
||||
endif()
|
||||
target_compile_features(cryptopp PUBLIC cxx_std_17)
|
||||
target_compile_definitions(cryptopp PUBLIC
|
||||
CRYPTOPP_DISABLE_ASM
|
||||
CRYPTOPP_DISABLE_SSSE3
|
||||
CRYPTOPP_DISABLE_AESNI)
|
||||
# Upstream is not warning-clean under -Wall; this is vendored 3rd-party code.
|
||||
target_compile_options(cryptopp PRIVATE -w)
|
||||
if(NOT MSVC)
|
||||
target_compile_options(cryptopp PRIVATE -fno-strict-aliasing)
|
||||
endif()
|
||||
|
||||
# Consumers include <cryptopp/sha.h> etc. — parent dir is on the include path
|
||||
# above (third_party/), so the "cryptopp/" prefix resolves.
|
||||
add_library(mt3p::cryptopp ALIAS cryptopp)
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
Compilation Copyright (c) 1995-2019 by Wei Dai. All rights reserved.
|
||||
This copyright applies only to this software distribution package
|
||||
as a compilation, and does not imply a copyright on any particular
|
||||
file in the package.
|
||||
|
||||
All individual files in this compilation are placed in the public domain by
|
||||
Wei Dai and other contributors.
|
||||
|
||||
I would like to thank the following authors for placing their works into
|
||||
the public domain:
|
||||
|
||||
Joan Daemen - 3way.cpp
|
||||
Leonard Janke - cast.cpp, seal.cpp
|
||||
Steve Reid - cast.cpp
|
||||
Phil Karn - des.cpp
|
||||
Andrew M. Kuchling - md2.cpp, md4.cpp
|
||||
Colin Plumb - md5.cpp
|
||||
Seal Woods - rc6.cpp
|
||||
Chris Morgan - rijndael.cpp
|
||||
Paulo Baretto - rijndael.cpp, skipjack.cpp, square.cpp
|
||||
Richard De Moliner - safer.cpp
|
||||
Matthew Skala - twofish.cpp
|
||||
Kevin Springle - camellia.cpp, shacal2.cpp, ttmac.cpp, whrlpool.cpp, ripemd.cpp
|
||||
Ronny Van Keer - sha3.cpp
|
||||
Aumasson, Neves, Wilcox-O'Hearn and Winnerlein - blake2.cpp, blake2b_simd.cpp, blake2s_simd.cpp
|
||||
Aaram Yun - aria.cpp, aria_simd.cpp
|
||||
Han Lulu, Markku-Juhani O. Saarinen - sm4.cpp sm4_simd.cpp
|
||||
Daniel J. Bernstein, Jack Lloyd - chacha.cpp, chacha_simd.cpp, chacha_avx.cpp
|
||||
Andrew Moon - ed25519, x25519, donna_32.cpp, donna_64.cpp, donna_sse.cpp
|
||||
|
||||
The Crypto++ Library uses portions of Andy Polyakov's CRYPTOGAMS for Poly1305
|
||||
scalar multiplication, aes_armv4.S, sha1_armv4.S and sha256_armv4.S. CRYPTOGAMS
|
||||
is dual licensed with a permissive BSD-style license. The CRYPTOGAMS license is
|
||||
reproduced below.
|
||||
|
||||
The Crypto++ Library uses portions of Jack Lloyd's Botan for ChaCha SSE2 and
|
||||
AVX. Botan placed the code in public domain for Crypto++ to use.
|
||||
|
||||
The Crypto++ Library (as a compilation) is currently licensed under the Boost
|
||||
Software License 1.0 (http://www.boost.org/users/license.html).
|
||||
|
||||
Boost Software License - Version 1.0 - August 17th, 2003
|
||||
|
||||
Permission is hereby granted, free of charge, to any person or organization
|
||||
obtaining a copy of the software and accompanying documentation covered by
|
||||
this license (the "Software") to use, reproduce, display, distribute,
|
||||
execute, and transmit the Software, and to prepare derivative works of the
|
||||
Software, and to permit third-parties to whom the Software is furnished to
|
||||
do so, all subject to the following:
|
||||
|
||||
The copyright notices in the Software and this entire statement, including
|
||||
the above license grant, this restriction and the following disclaimer,
|
||||
must be included in all copies of the Software, in whole or in part, and
|
||||
all derivative works of the Software, unless such copies or derivative
|
||||
works are solely in the form of machine-executable object code generated by
|
||||
a source language processor.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
|
||||
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
|
||||
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
|
||||
CRYPTOGAMS License
|
||||
|
||||
Copyright (c) 2006-2017, CRYPTOGAMS by <appro@openssl.org>
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
* Redistributions of source code must retain copyright notices,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials
|
||||
provided with the distribution.
|
||||
* Neither the name of the CRYPTOGAMS nor the names of its copyright
|
||||
holder and contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
Crypto++: free C++ Class Library of Cryptographic Schemes
|
||||
Version 8.4 - TBD
|
||||
|
||||
Crypto++ Library is a free C++ class library of cryptographic schemes.
|
||||
Currently the library contains the following algorithms:
|
||||
|
||||
algorithm type name
|
||||
|
||||
authenticated encryption schemes GCM, CCM, EAX, ChaCha20Poly1305 and
|
||||
XChaCha20Poly1305
|
||||
|
||||
high speed stream ciphers ChaCha (8/12/20), ChaCha (IETF), Panama, Salsa20,
|
||||
Sosemanuk, XSalsa20, XChaCha20
|
||||
|
||||
AES and AES candidates AES (Rijndael), RC6, MARS, Twofish, Serpent,
|
||||
CAST-256
|
||||
|
||||
ARIA, Blowfish, Camellia, CHAM, HIGHT, IDEA,
|
||||
Kalyna (128/256/512), LEA, SEED, RC5, SHACAL-2,
|
||||
other block ciphers SIMON (64/128), Skipjack, SPECK (64/128),
|
||||
Simeck, SM4, Threefish (256/512/1024),
|
||||
Triple-DES (DES-EDE2 and DES-EDE3), TEA, XTEA
|
||||
|
||||
block cipher modes of operation ECB, CBC, CBC ciphertext stealing (CTS),
|
||||
CFB, OFB, counter mode (CTR), XTS
|
||||
|
||||
message authentication codes BLAKE2s, BLAKE2b, CMAC, CBC-MAC, DMAC, GMAC, HMAC,
|
||||
Poly1305, Poly1305 (IETF), SipHash, Two-Track-MAC,
|
||||
VMAC
|
||||
|
||||
BLAKE2s, BLAKE2b, Keccack (F1600), SHA-1,
|
||||
hash functions SHA-2 (224/256/384/512), SHA-3 (224/256/384/512),
|
||||
SHAKE (128/256), SipHash, SM3, Tiger,
|
||||
RIPEMD (128/160/256/320), WHIRLPOOL
|
||||
|
||||
RSA, DSA, Determinsitic DSA, ElGamal,
|
||||
public-key cryptography Nyberg-Rueppel (NR), Rabin-Williams (RW), LUC,
|
||||
LUCELG, EC-based German Digital Signature (ECGDSA),
|
||||
DLIES (variants of DHAES), ESIGN
|
||||
|
||||
padding schemes for public-key PKCS#1 v2.0, OAEP, PSS, PSSR, IEEE P1363
|
||||
systems EMSA2 and EMSA5
|
||||
|
||||
Diffie-Hellman (DH), Unified Diffie-Hellman (DH2),
|
||||
key agreement schemes Menezes-Qu-Vanstone (MQV), Hashed MQV (HMQV),
|
||||
Fully Hashed MQV (FHMQV), LUCDIF, XTR-DH
|
||||
|
||||
elliptic curve cryptography ECDSA, Determinsitic ECDSA, ed25519, ECNR, ECIES,
|
||||
ECDH, ECMQV, x25519
|
||||
|
||||
insecure or obsolescent MD2, MD4, MD5, Panama Hash, DES, ARC4, SEAL
|
||||
algorithms retained for backwards 3.0, WAKE-OFB, DESX (DES-XEX3), RC2,
|
||||
compatibility and historical SAFER, 3-WAY, GOST, SHARK, CAST-128, Square
|
||||
value
|
||||
|
||||
Other features include:
|
||||
|
||||
* pseudo random number generators (PRNG): ANSI X9.17 appendix C, RandomPool,
|
||||
DARN, VIA Padlock, RDRAND, RDSEED, NIST Hash and HMAC DRBGs
|
||||
* password based key derivation functions: PBKDF1 and PBKDF2 from PKCS #5,
|
||||
PBKDF from PKCS #12 appendix B, HKDF from RFC 5869, Scrypt from RFC 7914
|
||||
* Shamir's secret sharing scheme and Rabin's information dispersal algorithm
|
||||
(IDA)
|
||||
* fast multi-precision integer (bignum) and polynomial operations
|
||||
* finite field arithmetics, including GF(p) and GF(2^n)
|
||||
* prime number generation and verification
|
||||
* useful non-cryptographic algorithms
|
||||
+ DEFLATE (RFC 1951) compression/decompression with gzip (RFC 1952) and
|
||||
zlib (RFC 1950) format support
|
||||
+ Hex, base-32, base-64, URL safe base-64 encoding and decoding
|
||||
+ 32-bit CRC, CRC-C and Adler32 checksum
|
||||
* class wrappers for these platform and operating system features (optional):
|
||||
+ high resolution timers on Windows, Unix, and Mac OS
|
||||
+ /dev/random, /dev/urandom, /dev/srandom
|
||||
+ Microsoft's CryptGenRandom or BCryptGenRandom on Windows
|
||||
* A high level interface for most of the above, using a filter/pipeline
|
||||
metaphor
|
||||
* benchmarks and validation testing
|
||||
* x86, x64 (x86-64), x32 (ILP32), ARM-32, Aarch32, Aarch64 and Power8 in-core code
|
||||
for the commonly used algorithms
|
||||
+ run-time CPU feature detection and code selection
|
||||
+ supports GCC-style and MSVC-style inline assembly, and MASM for x64
|
||||
+ x86, x64 (x86-64), x32 provides MMX, SSE2, and SSE4 implementations
|
||||
+ ARM-32, Aarch32 and Aarch64 provides NEON, ASIMD and ARMv8 implementations
|
||||
+ Power8 provides in-core AES using NX Crypto Acceleration
|
||||
|
||||
The Crypto++ library was orginally written by Wei Dai. The library is now
|
||||
maintained by several team members and the community. You are welcome to use it
|
||||
for any purpose without paying anyone, but see 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.
|
||||
|
||||
* Visual Studio 2003 - 2019
|
||||
* GCC 3.3 - 10.1
|
||||
* Apple Clang 4.3 - 9.3
|
||||
* LLVM Clang 2.9 - 10.0
|
||||
* C++ Builder 2015
|
||||
* Intel C++ Compiler 9 - 16.0
|
||||
* Sun Studio 12u1 - 12.6
|
||||
* IBM XL C/C++ 10.0 - 13.3
|
||||
|
||||
*** Important Usage Notes ***
|
||||
|
||||
1. If a constructor for A takes a pointer to an object B (except primitive
|
||||
types such as int and char), then A owns B and will delete B at A's
|
||||
destruction. If a constructor for A takes a reference to an object B,
|
||||
then the caller retains ownership of B and should not destroy it until
|
||||
A no longer needs it.
|
||||
|
||||
2. Crypto++ is thread safe at the class level. This means you can use
|
||||
Crypto++ safely in a multithreaded application, but you must provide
|
||||
synchronization when multiple threads access a common Crypto++ object.
|
||||
|
||||
*** MSVC-Specific Information ***
|
||||
|
||||
To compile Crypto++ with MSVC, open "cryptest.sln" (for MSVC 2003 - 2015)
|
||||
and build one or more of the following projects:
|
||||
|
||||
cryptest Non-DLL-Import Configuration - This builds the full static library
|
||||
along with a full test driver.
|
||||
cryptest DLL-Import Configuration - This builds a static library containing
|
||||
only algorithms not in the DLL, along with a full test driver that uses
|
||||
both the DLL and the static library.
|
||||
cryptdll - This builds the DLL. Please note that if you wish to use Crypto++
|
||||
as a FIPS validated module, you must use a pre-built DLL that has undergone
|
||||
the FIPS validation process instead of building your own.
|
||||
dlltest - This builds a sample application that only uses the DLL.
|
||||
|
||||
The DLL used to provide FIPS validated cryptography. The library was moved
|
||||
to the CMVP's <A HREF=
|
||||
"http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140val-historical.htm">
|
||||
Historical Validation List</A>. The library and the DLL are no longer considered
|
||||
validated. You should no longer use the DLL.
|
||||
|
||||
To use the Crypto++ DLL in your application, #include "dll.h" before including
|
||||
any other Crypto++ header files, and place the DLL in the same directory as
|
||||
your .exe file. dll.h includes the line #pragma comment(lib, "cryptopp")
|
||||
so you don't have to explicitly list the import library in your project
|
||||
settings. To use a static library form of Crypto++, make the "cryptlib"
|
||||
project a dependency of your application project, or specify it as
|
||||
an additional library to link with in your project settings.
|
||||
In either case you should check the compiler options to
|
||||
make sure that the library and your application are using the same C++
|
||||
run-time libraries and calling conventions.
|
||||
|
||||
*** DLL Memory Management ***
|
||||
|
||||
Because it's possible for the Crypto++ DLL to delete objects allocated
|
||||
by the calling application, they must use the same C++ memory heap. Three
|
||||
methods are provided to achieve this.
|
||||
1. The calling application can tell Crypto++ what heap to use. This method
|
||||
is required when the calling application uses a non-standard heap.
|
||||
2. Crypto++ can tell the calling application what heap to use. This method
|
||||
is required when the calling application uses a statically linked C++ Run
|
||||
Time Library. (Method 1 does not work in this case because the Crypto++ DLL
|
||||
is initialized before the calling application's heap is initialized.)
|
||||
3. Crypto++ can automatically use the heap provided by the calling application's
|
||||
dynamically linked C++ Run Time Library. The calling application must
|
||||
make sure that the dynamically linked C++ Run Time Library is initialized
|
||||
before Crypto++ is loaded. (At this time it is not clear if it is possible
|
||||
to control the order in which DLLs are initialized on Windows 9x machines,
|
||||
so it might be best to avoid using this method.)
|
||||
|
||||
When Crypto++ attaches to a new process, it searches all modules loaded
|
||||
into the process space for exported functions "GetNewAndDeleteForCryptoPP"
|
||||
and "SetNewAndDeleteFromCryptoPP". If one of these functions is found,
|
||||
Crypto++ uses methods 1 or 2, respectively, by calling the function.
|
||||
Otherwise, method 3 is used.
|
||||
|
||||
*** Linux and Unix-like Specific Information ***
|
||||
|
||||
A makefile is included for you to compile Crypto++ with GCC and compatibles.
|
||||
Make sure you are using GNU Make and GNU ld. The make process will produce
|
||||
two files, libcryptopp.a and cryptest.exe. Run "cryptest.exe v" for the
|
||||
validation suite and "cryptest.exe tv all" for additional test vectors.
|
||||
|
||||
The makefile uses '-DNDEBUG -g2 -O2' CXXFLAGS by default. If you use an
|
||||
alternate build system, like Autotools or CMake, then ensure the build system
|
||||
includes '-DNDEBUG' for production or release builds. The Crypto++ library uses
|
||||
asserts for debugging and diagnostics during development; it does not
|
||||
rely on them to crash a program at runtime.
|
||||
|
||||
If an assert triggers in production software, then unprotected sensitive
|
||||
information could be egressed from the program to the filesystem or the
|
||||
platform's error reporting program, like Apport on Ubuntu or CrashReporter
|
||||
on Apple.
|
||||
|
||||
The makefile orders object files to help remediate problems associated with
|
||||
C++ static initialization order. The library does not use custom linker scripts.
|
||||
If you use an alternate build system, like Autotools or CMake, and collect source
|
||||
files into a list, then ensure these three are at the head of the list: 'cryptlib.cpp
|
||||
cpu.cpp integer.cpp <other sources>'. They should be linked in the same order:
|
||||
'cryptlib.o cpu.o integer.o <other objects>'.
|
||||
|
||||
If your linker supports initialization attributes, like init_priority, then you can
|
||||
define CRYPTOPP_INIT_PRIORITY to control object initialization order. Set it to a
|
||||
value like 250. User programs can use CRYPTOPP_USER_PRIORITY to avoid conflicts with
|
||||
library values. Initialization attributes are more reliable than object file ordering,
|
||||
but its not ubiquitously supported by linkers.
|
||||
|
||||
The makefile links to the static version of the Crypto++ library to avoid binary
|
||||
planting and other LD_PRELOAD tricks. You should use the static version of the
|
||||
library in your programs to help avoid unwanted redirections.
|
||||
|
||||
*** Side Channel Attacks ***
|
||||
|
||||
Crypto++ attempts to resist side channel attacks using various remediations.
|
||||
The remdiations are applied as a best effort but are probably incomplete. They
|
||||
are incomplete due to cpu speculation bugs like Spectre, Meltdown, Foreshadow.
|
||||
The attacks target both cpu caches and internal buffers. Intel generally refers
|
||||
to internal buffer attacks as "Microarchitectural Data Sampling" (MDS).
|
||||
|
||||
The library uses hardware instructions when possible for block ciphers, hashes
|
||||
and other operations. The hardware acceleration remediates some timing
|
||||
attacks. The library also uses cache-aware algoirthms and access patterns
|
||||
to minimize leakage cache evictions.
|
||||
|
||||
Elliptic curves over binary fields are believed to leak information. The task is a
|
||||
work in progress. We don't believe binary fields are used in production, so we feel it
|
||||
is a low risk at the moment.
|
||||
|
||||
Crypto++ does not enagage Specter remediations at this time. The GCC options
|
||||
for Specter are -mfunction-return=thunk and -mindirect-branch=thunk, and the
|
||||
library uses them during testing. If you want the Specter workarounds then add
|
||||
the GCC options to your CXXFLAGS when building the library.
|
||||
|
||||
To help resist attacks you should disable hyperthreading on cpus. If you
|
||||
suspect or find an information leak then please report it.
|
||||
|
||||
*** Documentation and Support ***
|
||||
|
||||
Crypto++ is documented through inline comments in header files, which are
|
||||
processed through Doxygen to produce an HTML reference manual. You can find
|
||||
a link to the manual from http://www.cryptopp.com. Also at that site is
|
||||
the Crypto++ FAQ, which you should browse through before attempting to
|
||||
use this library, because it will likely answer many of questions that
|
||||
may come up. Finally, the site provide the wiki which has many topics
|
||||
and code examples.
|
||||
|
||||
If you run into any problems, please try the Crypto++ mailing list.
|
||||
The subscription information and the list archive are available on
|
||||
http://www.cryptopp.com.
|
||||
|
||||
*** Source Code and Contributing ***
|
||||
|
||||
The source code and its planned changes are available at the following locations.
|
||||
|
||||
* The Crypto++ GitHub repository allows you to view the latest (unreleased)
|
||||
Crypto++ source code via the Linux kernel's git beginning around June 2015.
|
||||
Its also serves as an incubator to nuture and grow the library.
|
||||
* The former Crypto++ SourceForge repository allows you to view the Crypto++
|
||||
source code via Apache's subversion until about July 2015. At that time,
|
||||
SourceForge had infrastructure problems and a cutover to GutHub was performed.
|
||||
* The Roadmap on the wiki provides the general direction the library is heading.
|
||||
It includes planned features and releases, and even some wishlist items.
|
||||
|
||||
Contributions of all types are welcomed. Contributions include the following.
|
||||
|
||||
* Bug finding and fixes
|
||||
* Features and enhancements
|
||||
* Test scripts and test cases
|
||||
* Branch and release testing
|
||||
* Documentation and updates
|
||||
|
||||
If you think you have found a bug in the library, then you should discuss it on the
|
||||
Users mailing list. Discussing it will help bring the issue to the attention of folks
|
||||
who can help resolve the issue. If you want to contribute a bug fix to the library,
|
||||
then make a Pull Request or make a Diff available somewhere. Also see Bug Reports on
|
||||
the wiki.
|
||||
|
||||
Features and enhancements are welcomend additions to the library. This category tends
|
||||
to be time consuming because algorithms and their test cases need to be reviewed and
|
||||
merged. Please be mindful of the test cases, and attempt to procure them from an
|
||||
independent source.
|
||||
|
||||
The library cherishes test scripts and test cases. They ensure the library is fit and
|
||||
they help uncover issues with the library before users experience them. If you have
|
||||
some time, then write some test cases, especially the ones that are intended to break
|
||||
things.
|
||||
|
||||
Branch and release testing is your chance to ensure Master (and planned merges) meets
|
||||
your expectations and perform as expected. If you have a few spare cycles, then please
|
||||
test Master on your favorite platform. We need more testing on MinGW, Windows Phone,
|
||||
Windows Store, Solaris 10 (and below), and modern iOS and OS X (including TV and
|
||||
Watch builds).
|
||||
|
||||
Documentation and updates includes both the inline source code annotations using
|
||||
Doxygen, and the online information provided in the wiki. The wiki is more verbose and
|
||||
usually provides more contextual information than the API reference. Besides testing,
|
||||
documentation is one of the highest returns on investment.
|
||||
|
||||
*** History ***
|
||||
|
||||
The items in this section comprise the most recent history. Please see History.txt
|
||||
for the record back to Crypto++ 1.0.
|
||||
|
||||
8.4.0 - January 2, 2021
|
||||
- minor release, recompile of programs required
|
||||
- expanded community input and support
|
||||
* 67 unique contributors as of this release
|
||||
- fix SIGILL on POWER8 when compiling with GCC 10
|
||||
- fix potential out-of-bounds write in FixedSizeAllocatorWithCleanup
|
||||
- fix compile on AIX POWER7 with IBM XLC 12.01
|
||||
- fix compile on Solaris with SunCC 12.6
|
||||
- revert changes for constant-time elliptic curve algorithms
|
||||
- fix makefile clean and distclean recipes
|
||||
|
||||
8.3.0 - December 20, 2020
|
||||
- minor release, recompile of programs required
|
||||
- expanded community input and support
|
||||
* 66 unique contributors as of this release
|
||||
- fix use of macro CRYPTOPP_ALIGN_DATA
|
||||
- fix potential out-of-bounds read in ECDSA
|
||||
- fix std::bad_alloc when using ByteQueue in pipeline
|
||||
- fix missing CRYPTOPP_CXX17_EXCEPTIONS with Clang
|
||||
- fix potential out-of-bounds read in GCM mode
|
||||
- add configure.sh when preprocessor macros fail
|
||||
- fix potential out-of-bounds read in SipHash
|
||||
- fix compile error on POWER9 due to vec_xl_be
|
||||
- fix K233 curve on POWER8
|
||||
- add Cirrus CI testing
|
||||
- fix broken encryption for some 64-bit ciphers
|
||||
- fix Android cpu-features.c using C++ compiler
|
||||
- disable RDRAND and RDSEED for some AMD processors
|
||||
- fix BLAKE2 hash calculation using Salt and Personalization
|
||||
- refresh Android and iOS build scripts
|
||||
- add XTS mode
|
||||
- fix circular dependency between misc.h and secblock.h
|
||||
- add Certificate interface
|
||||
- fix recursion in AES::Encryption without AESNI
|
||||
- add missing OID for ElGamal encryption
|
||||
- fix missing override in KeyDerivationFunction-derived classes
|
||||
- fix RDSEED assemble under MSVC
|
||||
- fix elliptic curve timing leaks (CVE-2019-14318)
|
||||
- add link-library variable to Makefiles
|
||||
- fix SIZE_MAX definition in misc.h
|
||||
- add GetWord64 and PutWord64 to BufferedTransformation
|
||||
- use HKDF in AutoSeededX917RNG::Reseed
|
||||
- fix Asan finding in VMAC on i686 in inline asm
|
||||
- fix undeclared identifier _mm_roti_epi64 on Gentoo
|
||||
- fix ECIES and GetSymmetricKeyLength
|
||||
- fix possible divide by zero in PKCS5_PBKDF2_HMAC
|
||||
- refine ASN.1 encoders and decoders
|
||||
- disable BMI2 code paths in Integer class
|
||||
- fix use of CRYPTOPP_CLANG_VERSION
|
||||
- add NEON SHA1, SHA256 and SHA512 from Cryptogams
|
||||
- add ARM SHA1, SHA256 and SHA512 from Cryptogams
|
||||
- make config.h more autoconf friendly
|
||||
- handle Clang triplet armv8l-unknown-linux-gnueabihf
|
||||
- fix reference binding to misaligned address in xed25519
|
||||
- clear asserts in TestDataNameValuePairs
|
||||
|
||||
8.2.0 - April 28, 2019
|
||||
- minor release, no recompile of programs required
|
||||
- expanded community input and support
|
||||
* 56 unique contributors as of this release
|
||||
- use PowerPC unaligned loads and stores with Power8
|
||||
- add SKIPJACK test vectors
|
||||
- fix SHAKE-128 and SHAKE-256 compile
|
||||
- removed IS_NEON from Makefile
|
||||
- fix Aarch64 build on Fedora 29
|
||||
- fix missing GF2NT_233_Multiply_Reduce_CLMUL in FIPS DLL
|
||||
- add missing BLAKE2 constructors
|
||||
- fix missing BlockSize() in BLAKE2 classes
|
||||
|
||||
8.1.0 - February 22, 2019
|
||||
- minor release, no recompile of programs required
|
||||
- expanded community input and support
|
||||
* 56 unique contributors as of this release
|
||||
- fix OS X PowerPC builds with Clang
|
||||
- add Microsoft ARM64 support
|
||||
- fix iPhone Simulator build due to missing symbols
|
||||
- add CRYPTOPP_BUGGY_SIMD_LOAD_AND_STORE
|
||||
- add carryless multiplies for NIST b233 and k233 curves
|
||||
- fix OpenMP build due to use of OpenMP 4 with down-level compilers
|
||||
- add SignStream and VerifyStream for ed25519 and large files
|
||||
- fix missing AlgorithmProvider in PanamaHash
|
||||
- add SHAKE-128 and SHAKE-256
|
||||
- fix AVX2 build due to _mm256_broadcastsi128_si256
|
||||
- add IETF ChaCha, XChaCha, ChaChaPoly1305 and XChaChaPoly1305
|
||||
|
||||
8.0.0 - December 28, 2018
|
||||
- major release, recompile of programs required
|
||||
- expanded community input and support
|
||||
* 54 unique contributors as of this release
|
||||
- add x25519 key exchange and ed25519 signature scheme
|
||||
- add limited Asymmetric Key Package support from RFC 5958
|
||||
- add Power9 DARN random number generator support
|
||||
- add CHAM, HC-128, HC-256, Hight, LEA, Rabbit, Simeck
|
||||
- fix FixedSizeAllocatorWithCleanup may be unaligned on some platforms
|
||||
- cutover to GNU Make-based cpu feature tests
|
||||
- rename files with dashes to underscores
|
||||
- fix LegacyDecryptor and LegacyDecryptorWithMAC use wrong MAC
|
||||
- fix incorrect AES/CBC decryption on Windows
|
||||
- avoid Singleton<T> when possible, avoid std::call_once completely
|
||||
- fix SPARC alignment problems due to GetAlignmentOf<T>() on word64
|
||||
- add ARM AES asm implementation from Cryptogams
|
||||
- remove CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS support
|
||||
|
||||
June 2015 - Changing of the guard. Wei Dai turned the library over to the
|
||||
community. The first community release was Crypto++ 5.6.3. Wei is
|
||||
no longer involved with the daily operations of the project. Wei
|
||||
still provides guidance when we have questions.
|
||||
|
||||
Originally written by Wei Dai, maintained by the Crypto++ Project
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#include "config.h"
|
||||
#include <iosfwd>
|
||||
#include <string>
|
||||
|
||||
#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)
|
||||
USING_NAMESPACE(std)
|
||||
|
||||
#ifndef CRYPTOPP_UNUSED
|
||||
# define CRYPTOPP_UNUSED(x) (void(x))
|
||||
#endif
|
||||
|
||||
// Used for testing the compiler and linker in cryptest.sh
|
||||
#if defined(CRYPTOPP_ADHOC_MAIN) || defined(ADHOC_MAIN)
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
CRYPTOPP_UNUSED(argc), CRYPTOPP_UNUSED(argv);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Classic use of adhoc to setup calling convention
|
||||
#else
|
||||
|
||||
extern int (*AdhocTest)(int argc, char *argv[]);
|
||||
|
||||
int MyAdhocTest(int argc, char *argv[])
|
||||
{
|
||||
CRYPTOPP_UNUSED(argc), CRYPTOPP_UNUSED(argv);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int s_i = (AdhocTest = &MyAdhocTest, 0);
|
||||
|
||||
#endif
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
// adler32.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
#include "adler32.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
void Adler32::Update(const byte *input, size_t length)
|
||||
{
|
||||
const unsigned long BASE = 65521;
|
||||
|
||||
unsigned long s1 = m_s1;
|
||||
unsigned long s2 = m_s2;
|
||||
|
||||
if (length % 8 != 0)
|
||||
{
|
||||
do
|
||||
{
|
||||
s1 += *input++;
|
||||
s2 += s1;
|
||||
length--;
|
||||
} while (length % 8 != 0);
|
||||
|
||||
if (s1 >= BASE)
|
||||
s1 -= BASE;
|
||||
s2 %= BASE;
|
||||
}
|
||||
|
||||
while (length > 0)
|
||||
{
|
||||
s1 += input[0]; s2 += s1;
|
||||
s1 += input[1]; s2 += s1;
|
||||
s1 += input[2]; s2 += s1;
|
||||
s1 += input[3]; s2 += s1;
|
||||
s1 += input[4]; s2 += s1;
|
||||
s1 += input[5]; s2 += s1;
|
||||
s1 += input[6]; s2 += s1;
|
||||
s1 += input[7]; s2 += s1;
|
||||
|
||||
length -= 8;
|
||||
input += 8;
|
||||
|
||||
if (s1 >= BASE)
|
||||
s1 -= BASE;
|
||||
if (length % 0x8000 == 0)
|
||||
s2 %= BASE;
|
||||
}
|
||||
|
||||
CRYPTOPP_ASSERT(s1 < BASE);
|
||||
CRYPTOPP_ASSERT(s2 < BASE);
|
||||
|
||||
m_s1 = (word16)s1;
|
||||
m_s2 = (word16)s2;
|
||||
}
|
||||
|
||||
void Adler32::TruncatedFinal(byte *hash, size_t size)
|
||||
{
|
||||
ThrowIfInvalidTruncatedSize(size);
|
||||
|
||||
switch (size)
|
||||
{
|
||||
default:
|
||||
hash[3] = byte(m_s1);
|
||||
// fall through
|
||||
case 3:
|
||||
hash[2] = byte(m_s1 >> 8);
|
||||
// fall through
|
||||
case 2:
|
||||
hash[1] = byte(m_s2);
|
||||
// fall through
|
||||
case 1:
|
||||
hash[0] = byte(m_s2 >> 8);
|
||||
// fall through
|
||||
case 0:
|
||||
;
|
||||
// fall through
|
||||
}
|
||||
|
||||
Reset();
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
// adler32.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file adler32.h
|
||||
/// \brief Class file for ADLER-32 checksum calculations
|
||||
|
||||
#ifndef CRYPTOPP_ADLER32_H
|
||||
#define CRYPTOPP_ADLER32_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// ADLER-32 checksum calculations
|
||||
class Adler32 : public HashTransformation
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = 4);
|
||||
Adler32() {Reset();}
|
||||
void Update(const byte *input, size_t length);
|
||||
void TruncatedFinal(byte *hash, size_t size);
|
||||
unsigned int DigestSize() const {return DIGESTSIZE;}
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "Adler32";}
|
||||
std::string AlgorithmName() const {return StaticAlgorithmName();}
|
||||
|
||||
private:
|
||||
void Reset() {m_s1 = 1; m_s2 = 0;}
|
||||
|
||||
word16 m_s1, m_s2;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+1281
File diff suppressed because it is too large
Load Diff
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
// aes.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file
|
||||
/// \brief Class file for the AES cipher (Rijndael)
|
||||
/// \details AES is a typdef for Rijndael classes. All key sizes are supported.
|
||||
/// The library only provides Rijndael with 128-bit blocks, and not 192-bit or 256-bit blocks
|
||||
/// \since Rijndael since Crypto++ 3.1, Intel AES-NI since Crypto++ 5.6.1, ARMv8 AES since Crypto++ 6.0,
|
||||
/// Power8 AES since Crypto++ 6.0
|
||||
|
||||
#ifndef CRYPTOPP_AES_H
|
||||
#define CRYPTOPP_AES_H
|
||||
|
||||
#include "rijndael.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief AES block cipher (Rijndael)
|
||||
/// \details AES is a typdef for Rijndael classes. All key sizes are supported.
|
||||
/// The library only provides Rijndael with 128-bit blocks, and not 192-bit or 256-bit blocks
|
||||
/// \sa <a href="http://www.cryptolounge.org/wiki/AES">AES</a> winner, announced on 10/2/2000
|
||||
/// \since Rijndael since Crypto++ 3.1, Intel AES-NI since Crypto++ 5.6.1, ARMv8 AES since Crypto++ 6.0,
|
||||
/// Power8 AES since Crypto++ 6.0
|
||||
DOCUMENTED_TYPEDEF(Rijndael, AES);
|
||||
|
||||
typedef RijndaelEncryption AESEncryption;
|
||||
typedef RijndaelDecryption AESDecryption;
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+1215
File diff suppressed because it is too large
Load Diff
+30
@@ -0,0 +1,30 @@
|
||||
/* Header file for use with Cryptogam's ARMv4 AES. */
|
||||
/* Also see http://www.openssl.org/~appro/cryptogams/ and */
|
||||
/* https://wiki.openssl.org/index.php?title=Cryptogams_AES */
|
||||
|
||||
#ifndef CRYPTOGAMS_AES_ARMV4_H
|
||||
#define CRYPTOGAMS_AES_ARMV4_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
//#define AES_MAXNR 14
|
||||
//typedef struct AES_KEY_st {
|
||||
// unsigned int rd_key[4 * (AES_MAXNR + 1)];
|
||||
// int rounds;
|
||||
//} AES_KEY;
|
||||
|
||||
// Instead of AES_KEY we use a 'word32 rkey[4*15+4]'. It has space for
|
||||
// both the AES_MAXNR round keys and the number of rounds in the tail.
|
||||
|
||||
int cryptogams_AES_set_encrypt_key(const unsigned char *userKey, const int bits, unsigned int *rkey);
|
||||
int cryptogams_AES_set_decrypt_key(const unsigned char *userKey, const int bits, unsigned int *rkey);
|
||||
void cryptogams_AES_encrypt_block(const unsigned char *in, unsigned char *out, const unsigned int *rkey);
|
||||
void cryptogams_AES_decrypt_block(const unsigned char *in, unsigned char *out, const unsigned int *rkey);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* CRYPTOGAMS_AES_ARMV4_H */
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
// algebra.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
|
||||
#ifndef CRYPTOPP_ALGEBRA_CPP // SunCC workaround: compiler could cause this file to be included twice
|
||||
#define CRYPTOPP_ALGEBRA_CPP
|
||||
|
||||
#include "algebra.h"
|
||||
#include "integer.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
template <class T> const T& AbstractGroup<T>::Double(const Element &a) const
|
||||
{
|
||||
return this->Add(a, a);
|
||||
}
|
||||
|
||||
template <class T> const T& AbstractGroup<T>::Subtract(const Element &a, const Element &b) const
|
||||
{
|
||||
// make copy of a in case Inverse() overwrites it
|
||||
Element a1(a);
|
||||
return this->Add(a1, Inverse(b));
|
||||
}
|
||||
|
||||
template <class T> T& AbstractGroup<T>::Accumulate(Element &a, const Element &b) const
|
||||
{
|
||||
return a = this->Add(a, b);
|
||||
}
|
||||
|
||||
template <class T> T& AbstractGroup<T>::Reduce(Element &a, const Element &b) const
|
||||
{
|
||||
return a = this->Subtract(a, b);
|
||||
}
|
||||
|
||||
template <class T> const T& AbstractRing<T>::Square(const Element &a) const
|
||||
{
|
||||
return this->Multiply(a, a);
|
||||
}
|
||||
|
||||
template <class T> const T& AbstractRing<T>::Divide(const Element &a, const Element &b) const
|
||||
{
|
||||
// make copy of a in case MultiplicativeInverse() overwrites it
|
||||
Element a1(a);
|
||||
return this->Multiply(a1, this->MultiplicativeInverse(b));
|
||||
}
|
||||
|
||||
template <class T> const T& AbstractEuclideanDomain<T>::Mod(const Element &a, const Element &b) const
|
||||
{
|
||||
Element q;
|
||||
this->DivisionAlgorithm(result, q, a, b);
|
||||
return result;
|
||||
}
|
||||
|
||||
template <class T> const T& AbstractEuclideanDomain<T>::Gcd(const Element &a, const Element &b) const
|
||||
{
|
||||
Element g[3]={b, a};
|
||||
unsigned int i0=0, i1=1, i2=2;
|
||||
|
||||
while (!this->Equal(g[i1], this->Identity()))
|
||||
{
|
||||
g[i2] = this->Mod(g[i0], g[i1]);
|
||||
unsigned int t = i0; i0 = i1; i1 = i2; i2 = t;
|
||||
}
|
||||
|
||||
return result = g[i0];
|
||||
}
|
||||
|
||||
template <class T> const typename QuotientRing<T>::Element& QuotientRing<T>::MultiplicativeInverse(const Element &a) const
|
||||
{
|
||||
Element g[3]={m_modulus, a};
|
||||
Element v[3]={m_domain.Identity(), m_domain.MultiplicativeIdentity()};
|
||||
Element y;
|
||||
unsigned int i0=0, i1=1, i2=2;
|
||||
|
||||
while (!this->Equal(g[i1], this->Identity()))
|
||||
{
|
||||
// y = g[i0] / g[i1];
|
||||
// g[i2] = g[i0] % g[i1];
|
||||
m_domain.DivisionAlgorithm(g[i2], y, g[i0], g[i1]);
|
||||
// v[i2] = v[i0] - (v[i1] * y);
|
||||
v[i2] = m_domain.Subtract(v[i0], m_domain.Multiply(v[i1], y));
|
||||
unsigned int t = i0; i0 = i1; i1 = i2; i2 = t;
|
||||
}
|
||||
|
||||
return m_domain.IsUnit(g[i0]) ? m_domain.Divide(v[i0], g[i0]) : m_domain.Identity();
|
||||
}
|
||||
|
||||
template <class T> T AbstractGroup<T>::ScalarMultiply(const Element &base, const Integer &exponent) const
|
||||
{
|
||||
Element result;
|
||||
this->SimultaneousMultiply(&result, base, &exponent, 1);
|
||||
return result;
|
||||
}
|
||||
|
||||
template <class T> T AbstractGroup<T>::CascadeScalarMultiply(const Element &x, const Integer &e1, const Element &y, const Integer &e2) const
|
||||
{
|
||||
const unsigned expLen = STDMAX(e1.BitCount(), e2.BitCount());
|
||||
if (expLen==0)
|
||||
return this->Identity();
|
||||
|
||||
const unsigned w = (expLen <= 46 ? 1 : (expLen <= 260 ? 2 : 3));
|
||||
const unsigned tableSize = 1<<w;
|
||||
std::vector<Element> powerTable(tableSize << w);
|
||||
|
||||
powerTable[1] = x;
|
||||
powerTable[tableSize] = y;
|
||||
if (w==1)
|
||||
powerTable[3] = this->Add(x,y);
|
||||
else
|
||||
{
|
||||
powerTable[2] = this->Double(x);
|
||||
powerTable[2*tableSize] = this->Double(y);
|
||||
|
||||
unsigned i, j;
|
||||
|
||||
for (i=3; i<tableSize; i+=2)
|
||||
powerTable[i] = Add(powerTable[i-2], powerTable[2]);
|
||||
for (i=1; i<tableSize; i+=2)
|
||||
for (j=i+tableSize; j<(tableSize<<w); j+=tableSize)
|
||||
powerTable[j] = Add(powerTable[j-tableSize], y);
|
||||
|
||||
for (i=3*tableSize; i<(tableSize<<w); i+=2*tableSize)
|
||||
powerTable[i] = Add(powerTable[i-2*tableSize], powerTable[2*tableSize]);
|
||||
for (i=tableSize; i<(tableSize<<w); i+=2*tableSize)
|
||||
for (j=i+2; j<i+tableSize; j+=2)
|
||||
powerTable[j] = Add(powerTable[j-1], x);
|
||||
}
|
||||
|
||||
Element result;
|
||||
unsigned power1 = 0, power2 = 0, prevPosition = expLen-1;
|
||||
bool firstTime = true;
|
||||
|
||||
for (int i = expLen-1; i>=0; i--)
|
||||
{
|
||||
power1 = 2*power1 + e1.GetBit(i);
|
||||
power2 = 2*power2 + e2.GetBit(i);
|
||||
|
||||
if (i==0 || 2*power1 >= tableSize || 2*power2 >= tableSize)
|
||||
{
|
||||
unsigned squaresBefore = prevPosition-i;
|
||||
unsigned squaresAfter = 0;
|
||||
prevPosition = i;
|
||||
while ((power1 || power2) && power1%2 == 0 && power2%2==0)
|
||||
{
|
||||
power1 /= 2;
|
||||
power2 /= 2;
|
||||
squaresBefore--;
|
||||
squaresAfter++;
|
||||
}
|
||||
if (firstTime)
|
||||
{
|
||||
result = powerTable[(power2<<w) + power1];
|
||||
firstTime = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
while (squaresBefore--)
|
||||
result = this->Double(result);
|
||||
if (power1 || power2)
|
||||
Accumulate(result, powerTable[(power2<<w) + power1]);
|
||||
}
|
||||
while (squaresAfter--)
|
||||
result = this->Double(result);
|
||||
power1 = power2 = 0;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template <class Element, class Iterator> Element GeneralCascadeMultiplication(const AbstractGroup<Element> &group, Iterator begin, Iterator end)
|
||||
{
|
||||
if (end-begin == 1)
|
||||
return group.ScalarMultiply(begin->base, begin->exponent);
|
||||
else if (end-begin == 2)
|
||||
return group.CascadeScalarMultiply(begin->base, begin->exponent, (begin+1)->base, (begin+1)->exponent);
|
||||
else
|
||||
{
|
||||
Integer q, t;
|
||||
Iterator last = end;
|
||||
--last;
|
||||
|
||||
std::make_heap(begin, end);
|
||||
std::pop_heap(begin, end);
|
||||
|
||||
while (!!begin->exponent)
|
||||
{
|
||||
// last->exponent is largest exponent, begin->exponent is next largest
|
||||
t = last->exponent;
|
||||
Integer::Divide(last->exponent, q, t, begin->exponent);
|
||||
|
||||
if (q == Integer::One())
|
||||
group.Accumulate(begin->base, last->base); // avoid overhead of ScalarMultiply()
|
||||
else
|
||||
group.Accumulate(begin->base, group.ScalarMultiply(last->base, q));
|
||||
|
||||
std::push_heap(begin, end);
|
||||
std::pop_heap(begin, end);
|
||||
}
|
||||
|
||||
return group.ScalarMultiply(last->base, last->exponent);
|
||||
}
|
||||
}
|
||||
|
||||
struct WindowSlider
|
||||
{
|
||||
WindowSlider(const Integer &expIn, bool fastNegate, unsigned int windowSizeIn=0)
|
||||
: exp(expIn), windowModulus(Integer::One()), windowSize(windowSizeIn), windowBegin(0), expWindow(0)
|
||||
, fastNegate(fastNegate), negateNext(false), firstTime(true), finished(false)
|
||||
{
|
||||
if (windowSize == 0)
|
||||
{
|
||||
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)))));
|
||||
}
|
||||
windowModulus <<= windowSize;
|
||||
}
|
||||
|
||||
void FindNextWindow()
|
||||
{
|
||||
unsigned int expLen = exp.WordCount() * WORD_BITS;
|
||||
unsigned int skipCount = firstTime ? 0 : windowSize;
|
||||
firstTime = false;
|
||||
while (!exp.GetBit(skipCount))
|
||||
{
|
||||
if (skipCount >= expLen)
|
||||
{
|
||||
finished = true;
|
||||
return;
|
||||
}
|
||||
skipCount++;
|
||||
}
|
||||
|
||||
exp >>= skipCount;
|
||||
windowBegin += skipCount;
|
||||
expWindow = word32(exp % (word(1) << windowSize));
|
||||
|
||||
if (fastNegate && exp.GetBit(windowSize))
|
||||
{
|
||||
negateNext = true;
|
||||
expWindow = (word32(1) << windowSize) - expWindow;
|
||||
exp += windowModulus;
|
||||
}
|
||||
else
|
||||
negateNext = false;
|
||||
}
|
||||
|
||||
Integer exp, windowModulus;
|
||||
unsigned int windowSize, windowBegin;
|
||||
word32 expWindow;
|
||||
bool fastNegate, negateNext, firstTime, finished;
|
||||
};
|
||||
|
||||
template <class T>
|
||||
void AbstractGroup<T>::SimultaneousMultiply(T *results, const T &base, const Integer *expBegin, unsigned int expCount) const
|
||||
{
|
||||
std::vector<std::vector<Element> > buckets(expCount);
|
||||
std::vector<WindowSlider> exponents;
|
||||
exponents.reserve(expCount);
|
||||
unsigned int i;
|
||||
|
||||
for (i=0; expBegin && i<expCount; i++)
|
||||
{
|
||||
CRYPTOPP_ASSERT(expBegin->NotNegative());
|
||||
exponents.push_back(WindowSlider(*expBegin++, InversionIsFast(), 0));
|
||||
exponents[i].FindNextWindow();
|
||||
buckets[i].resize(((size_t) 1) << (exponents[i].windowSize-1), Identity());
|
||||
}
|
||||
|
||||
unsigned int expBitPosition = 0;
|
||||
Element g = base;
|
||||
bool notDone = true;
|
||||
|
||||
while (notDone)
|
||||
{
|
||||
notDone = false;
|
||||
for (i=0; i<expCount; i++)
|
||||
{
|
||||
if (!exponents[i].finished && expBitPosition == exponents[i].windowBegin)
|
||||
{
|
||||
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].finished;
|
||||
}
|
||||
|
||||
if (notDone)
|
||||
{
|
||||
g = Double(g);
|
||||
expBitPosition++;
|
||||
}
|
||||
}
|
||||
|
||||
for (i=0; i<expCount; i++)
|
||||
{
|
||||
Element &r = *results++;
|
||||
r = buckets[i][buckets[i].size()-1];
|
||||
if (buckets[i].size() > 1)
|
||||
{
|
||||
for (int j = (int)buckets[i].size()-2; j >= 1; j--)
|
||||
{
|
||||
Accumulate(buckets[i][j], buckets[i][j+1]);
|
||||
Accumulate(r, buckets[i][j]);
|
||||
}
|
||||
Accumulate(buckets[i][0], buckets[i][1]);
|
||||
r = Add(Double(r), buckets[i][0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <class T> T AbstractRing<T>::Exponentiate(const Element &base, const Integer &exponent) const
|
||||
{
|
||||
Element result;
|
||||
SimultaneousExponentiate(&result, base, &exponent, 1);
|
||||
return result;
|
||||
}
|
||||
|
||||
template <class T> T AbstractRing<T>::CascadeExponentiate(const Element &x, const Integer &e1, const Element &y, const Integer &e2) const
|
||||
{
|
||||
return MultiplicativeGroup().AbstractGroup<T>::CascadeScalarMultiply(x, e1, y, e2);
|
||||
}
|
||||
|
||||
template <class Element, class Iterator> Element GeneralCascadeExponentiation(const AbstractRing<Element> &ring, Iterator begin, Iterator end)
|
||||
{
|
||||
return GeneralCascadeMultiplication<Element>(ring.MultiplicativeGroup(), begin, end);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
void AbstractRing<T>::SimultaneousExponentiate(T *results, const T &base, const Integer *exponents, unsigned int expCount) const
|
||||
{
|
||||
MultiplicativeGroup().AbstractGroup<T>::SimultaneousMultiply(results, base, exponents, expCount);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+453
@@ -0,0 +1,453 @@
|
||||
// algebra.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file algebra.h
|
||||
/// \brief Classes for performing mathematics over different fields
|
||||
|
||||
#ifndef CRYPTOPP_ALGEBRA_H
|
||||
#define CRYPTOPP_ALGEBRA_H
|
||||
|
||||
#include "config.h"
|
||||
#include "integer.h"
|
||||
#include "misc.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
class Integer;
|
||||
|
||||
/// \brief Abstract group
|
||||
/// \tparam T element class or type
|
||||
/// \details <tt>const Element&</tt> returned by member functions are references
|
||||
/// to internal data members. Since each object may have only
|
||||
/// one such data member for holding results, the following code
|
||||
/// will produce incorrect results:
|
||||
/// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
|
||||
/// But this should be fine:
|
||||
/// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
|
||||
template <class T> class CRYPTOPP_NO_VTABLE AbstractGroup
|
||||
{
|
||||
public:
|
||||
typedef T Element;
|
||||
|
||||
virtual ~AbstractGroup() {}
|
||||
|
||||
/// \brief Compare two elements for equality
|
||||
/// \param a first element
|
||||
/// \param b second element
|
||||
/// \return true if the elements are equal, false otherwise
|
||||
/// \details Equal() tests the elements for equality using <tt>a==b</tt>
|
||||
virtual bool Equal(const Element &a, const Element &b) const =0;
|
||||
|
||||
/// \brief Provides the Identity element
|
||||
/// \return the Identity element
|
||||
virtual const Element& Identity() const =0;
|
||||
|
||||
/// \brief Adds elements in the group
|
||||
/// \param a first element
|
||||
/// \param b second element
|
||||
/// \return the sum of <tt>a</tt> and <tt>b</tt>
|
||||
virtual const Element& Add(const Element &a, const Element &b) const =0;
|
||||
|
||||
/// \brief Inverts the element in the group
|
||||
/// \param a first element
|
||||
/// \return the inverse of the element
|
||||
virtual const Element& Inverse(const Element &a) const =0;
|
||||
|
||||
/// \brief Determine if inversion is fast
|
||||
/// \return true if inversion is fast, false otherwise
|
||||
virtual bool InversionIsFast() const {return false;}
|
||||
|
||||
/// \brief Doubles an element in the group
|
||||
/// \param a the element
|
||||
/// \return the element doubled
|
||||
virtual const Element& Double(const Element &a) const;
|
||||
|
||||
/// \brief Subtracts elements in the group
|
||||
/// \param a first element
|
||||
/// \param b second element
|
||||
/// \return the difference of <tt>a</tt> and <tt>b</tt>. The element <tt>a</tt> must provide a Subtract member function.
|
||||
virtual const Element& Subtract(const Element &a, const Element &b) const;
|
||||
|
||||
/// \brief TODO
|
||||
/// \param a first element
|
||||
/// \param b second element
|
||||
/// \return TODO
|
||||
virtual Element& Accumulate(Element &a, const Element &b) const;
|
||||
|
||||
/// \brief Reduces an element in the congruence class
|
||||
/// \param a element to reduce
|
||||
/// \param b the congruence class
|
||||
/// \return the reduced element
|
||||
virtual Element& Reduce(Element &a, const Element &b) const;
|
||||
|
||||
/// \brief Performs a scalar multiplication
|
||||
/// \param a multiplicand
|
||||
/// \param e multiplier
|
||||
/// \return the product
|
||||
virtual Element ScalarMultiply(const Element &a, const Integer &e) const;
|
||||
|
||||
/// \brief TODO
|
||||
/// \param x first multiplicand
|
||||
/// \param e1 the first multiplier
|
||||
/// \param y second multiplicand
|
||||
/// \param e2 the second multiplier
|
||||
/// \return TODO
|
||||
virtual Element CascadeScalarMultiply(const Element &x, const Integer &e1, const Element &y, const Integer &e2) const;
|
||||
|
||||
/// \brief Multiplies a base to multiple exponents in a group
|
||||
/// \param results an array of Elements
|
||||
/// \param base the base to raise to the exponents
|
||||
/// \param exponents an array of exponents
|
||||
/// \param exponentsCount the number of exponents in the array
|
||||
/// \details SimultaneousMultiply() multiplies the base to each exponent in the exponents array and stores the
|
||||
/// result at the respective position in the results array.
|
||||
/// \details SimultaneousMultiply() must be implemented in a derived class.
|
||||
/// \pre <tt>COUNTOF(results) == exponentsCount</tt>
|
||||
/// \pre <tt>COUNTOF(exponents) == exponentsCount</tt>
|
||||
virtual void SimultaneousMultiply(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
|
||||
};
|
||||
|
||||
/// \brief Abstract ring
|
||||
/// \tparam T element class or type
|
||||
/// \details <tt>const Element&</tt> returned by member functions are references
|
||||
/// to internal data members. Since each object may have only
|
||||
/// one such data member for holding results, the following code
|
||||
/// will produce incorrect results:
|
||||
/// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
|
||||
/// But this should be fine:
|
||||
/// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
|
||||
template <class T> class CRYPTOPP_NO_VTABLE AbstractRing : public AbstractGroup<T>
|
||||
{
|
||||
public:
|
||||
typedef T Element;
|
||||
|
||||
/// \brief Construct an AbstractRing
|
||||
AbstractRing() {m_mg.m_pRing = this;}
|
||||
|
||||
/// \brief Copy construct an AbstractRing
|
||||
/// \param source other AbstractRing
|
||||
AbstractRing(const AbstractRing &source)
|
||||
{CRYPTOPP_UNUSED(source); m_mg.m_pRing = this;}
|
||||
|
||||
/// \brief Assign an AbstractRing
|
||||
/// \param source other AbstractRing
|
||||
AbstractRing& operator=(const AbstractRing &source)
|
||||
{CRYPTOPP_UNUSED(source); return *this;}
|
||||
|
||||
/// \brief Determines whether an element is a unit in the group
|
||||
/// \param a the element
|
||||
/// \return true if the element is a unit after reduction, false otherwise.
|
||||
virtual bool IsUnit(const Element &a) const =0;
|
||||
|
||||
/// \brief Retrieves the multiplicative identity
|
||||
/// \return the multiplicative identity
|
||||
virtual const Element& MultiplicativeIdentity() const =0;
|
||||
|
||||
/// \brief Multiplies elements in the group
|
||||
/// \param a the multiplicand
|
||||
/// \param b the multiplier
|
||||
/// \return the product of a and b
|
||||
virtual const Element& Multiply(const Element &a, const Element &b) const =0;
|
||||
|
||||
/// \brief Calculate the multiplicative inverse of an element in the group
|
||||
/// \param a the element
|
||||
virtual const Element& MultiplicativeInverse(const Element &a) const =0;
|
||||
|
||||
/// \brief Square an element in the group
|
||||
/// \param a the element
|
||||
/// \return the element squared
|
||||
virtual const Element& Square(const Element &a) const;
|
||||
|
||||
/// \brief Divides elements in the group
|
||||
/// \param a the dividend
|
||||
/// \param b the divisor
|
||||
/// \return the quotient
|
||||
virtual const Element& Divide(const Element &a, const Element &b) const;
|
||||
|
||||
/// \brief Raises a base to an exponent in the group
|
||||
/// \param a the base
|
||||
/// \param e the exponent
|
||||
/// \return the exponentiation
|
||||
virtual Element Exponentiate(const Element &a, const Integer &e) const;
|
||||
|
||||
/// \brief TODO
|
||||
/// \param x first element
|
||||
/// \param e1 first exponent
|
||||
/// \param y second element
|
||||
/// \param e2 second exponent
|
||||
/// \return TODO
|
||||
virtual Element CascadeExponentiate(const Element &x, const Integer &e1, const Element &y, const Integer &e2) const;
|
||||
|
||||
/// \brief Exponentiates a base to multiple exponents in the Ring
|
||||
/// \param results an array of Elements
|
||||
/// \param base the base to raise to the exponents
|
||||
/// \param exponents an array of exponents
|
||||
/// \param exponentsCount the number of exponents in the array
|
||||
/// \details SimultaneousExponentiate() raises the base to each exponent in the exponents array and stores the
|
||||
/// result at the respective position in the results array.
|
||||
/// \details SimultaneousExponentiate() must be implemented in a derived class.
|
||||
/// \pre <tt>COUNTOF(results) == exponentsCount</tt>
|
||||
/// \pre <tt>COUNTOF(exponents) == exponentsCount</tt>
|
||||
virtual void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
|
||||
|
||||
/// \brief Retrieves the multiplicative group
|
||||
/// \return the multiplicative group
|
||||
virtual const AbstractGroup<T>& MultiplicativeGroup() const
|
||||
{return m_mg;}
|
||||
|
||||
private:
|
||||
class MultiplicativeGroupT : public AbstractGroup<T>
|
||||
{
|
||||
public:
|
||||
const AbstractRing<T>& GetRing() const
|
||||
{return *m_pRing;}
|
||||
|
||||
bool Equal(const Element &a, const Element &b) const
|
||||
{return GetRing().Equal(a, b);}
|
||||
|
||||
const Element& Identity() const
|
||||
{return GetRing().MultiplicativeIdentity();}
|
||||
|
||||
const Element& Add(const Element &a, const Element &b) const
|
||||
{return GetRing().Multiply(a, b);}
|
||||
|
||||
Element& Accumulate(Element &a, const Element &b) const
|
||||
{return a = GetRing().Multiply(a, b);}
|
||||
|
||||
const Element& Inverse(const Element &a) const
|
||||
{return GetRing().MultiplicativeInverse(a);}
|
||||
|
||||
const Element& Subtract(const Element &a, const Element &b) const
|
||||
{return GetRing().Divide(a, b);}
|
||||
|
||||
Element& Reduce(Element &a, const Element &b) const
|
||||
{return a = GetRing().Divide(a, b);}
|
||||
|
||||
const Element& Double(const Element &a) const
|
||||
{return GetRing().Square(a);}
|
||||
|
||||
Element ScalarMultiply(const Element &a, const Integer &e) const
|
||||
{return GetRing().Exponentiate(a, e);}
|
||||
|
||||
Element CascadeScalarMultiply(const Element &x, const Integer &e1, const Element &y, const Integer &e2) const
|
||||
{return GetRing().CascadeExponentiate(x, e1, y, e2);}
|
||||
|
||||
void SimultaneousMultiply(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const
|
||||
{GetRing().SimultaneousExponentiate(results, base, exponents, exponentsCount);}
|
||||
|
||||
const AbstractRing<T> *m_pRing;
|
||||
};
|
||||
|
||||
MultiplicativeGroupT m_mg;
|
||||
};
|
||||
|
||||
// ********************************************************
|
||||
|
||||
/// \brief Base and exponent
|
||||
/// \tparam T base class or type
|
||||
/// \tparam E exponent class or type
|
||||
template <class T, class E = Integer>
|
||||
struct BaseAndExponent
|
||||
{
|
||||
public:
|
||||
BaseAndExponent() {}
|
||||
BaseAndExponent(const T &base, const E &exponent) : base(base), exponent(exponent) {}
|
||||
bool operator<(const BaseAndExponent<T, E> &rhs) const {return exponent < rhs.exponent;}
|
||||
T base;
|
||||
E exponent;
|
||||
};
|
||||
|
||||
// VC60 workaround: incomplete member template support
|
||||
template <class Element, class Iterator>
|
||||
Element GeneralCascadeMultiplication(const AbstractGroup<Element> &group, Iterator begin, Iterator end);
|
||||
template <class Element, class Iterator>
|
||||
Element GeneralCascadeExponentiation(const AbstractRing<Element> &ring, Iterator begin, Iterator end);
|
||||
|
||||
// ********************************************************
|
||||
|
||||
/// \brief Abstract Euclidean domain
|
||||
/// \tparam T element class or type
|
||||
/// \details <tt>const Element&</tt> returned by member functions are references
|
||||
/// to internal data members. Since each object may have only
|
||||
/// one such data member for holding results, the following code
|
||||
/// will produce incorrect results:
|
||||
/// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
|
||||
/// But this should be fine:
|
||||
/// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
|
||||
template <class T> class CRYPTOPP_NO_VTABLE AbstractEuclideanDomain : public AbstractRing<T>
|
||||
{
|
||||
public:
|
||||
typedef T Element;
|
||||
|
||||
/// \brief Performs the division algorithm on two elements in the ring
|
||||
/// \param r the remainder
|
||||
/// \param q the quotient
|
||||
/// \param a the dividend
|
||||
/// \param d the divisor
|
||||
virtual void DivisionAlgorithm(Element &r, Element &q, const Element &a, const Element &d) const =0;
|
||||
|
||||
/// \brief Performs a modular reduction in the ring
|
||||
/// \param a the element
|
||||
/// \param b the modulus
|
||||
/// \return the result of <tt>a%b</tt>.
|
||||
virtual const Element& Mod(const Element &a, const Element &b) const =0;
|
||||
|
||||
/// \brief Calculates the greatest common denominator in the ring
|
||||
/// \param a the first element
|
||||
/// \param b the second element
|
||||
/// \return the the greatest common denominator of a and b.
|
||||
virtual const Element& Gcd(const Element &a, const Element &b) const;
|
||||
|
||||
protected:
|
||||
mutable Element result;
|
||||
};
|
||||
|
||||
// ********************************************************
|
||||
|
||||
/// \brief Euclidean domain
|
||||
/// \tparam T element class or type
|
||||
/// \details <tt>const Element&</tt> returned by member functions are references
|
||||
/// to internal data members. Since each object may have only
|
||||
/// one such data member for holding results, the following code
|
||||
/// will produce incorrect results:
|
||||
/// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
|
||||
/// But this should be fine:
|
||||
/// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
|
||||
template <class T> class EuclideanDomainOf : public AbstractEuclideanDomain<T>
|
||||
{
|
||||
public:
|
||||
typedef T Element;
|
||||
|
||||
EuclideanDomainOf() {}
|
||||
|
||||
bool Equal(const Element &a, const Element &b) const
|
||||
{return a==b;}
|
||||
|
||||
const Element& Identity() const
|
||||
{return Element::Zero();}
|
||||
|
||||
const Element& Add(const Element &a, const Element &b) const
|
||||
{return result = a+b;}
|
||||
|
||||
Element& Accumulate(Element &a, const Element &b) const
|
||||
{return a+=b;}
|
||||
|
||||
const Element& Inverse(const Element &a) const
|
||||
{return result = -a;}
|
||||
|
||||
const Element& Subtract(const Element &a, const Element &b) const
|
||||
{return result = a-b;}
|
||||
|
||||
Element& Reduce(Element &a, const Element &b) const
|
||||
{return a-=b;}
|
||||
|
||||
const Element& Double(const Element &a) const
|
||||
{return result = a.Doubled();}
|
||||
|
||||
const Element& MultiplicativeIdentity() const
|
||||
{return Element::One();}
|
||||
|
||||
const Element& Multiply(const Element &a, const Element &b) const
|
||||
{return result = a*b;}
|
||||
|
||||
const Element& Square(const Element &a) const
|
||||
{return result = a.Squared();}
|
||||
|
||||
bool IsUnit(const Element &a) const
|
||||
{return a.IsUnit();}
|
||||
|
||||
const Element& MultiplicativeInverse(const Element &a) const
|
||||
{return result = a.MultiplicativeInverse();}
|
||||
|
||||
const Element& Divide(const Element &a, const Element &b) const
|
||||
{return result = a/b;}
|
||||
|
||||
const Element& Mod(const Element &a, const Element &b) const
|
||||
{return result = a%b;}
|
||||
|
||||
void DivisionAlgorithm(Element &r, Element &q, const Element &a, const Element &d) const
|
||||
{Element::Divide(r, q, a, d);}
|
||||
|
||||
bool operator==(const EuclideanDomainOf<T> &rhs) const
|
||||
{CRYPTOPP_UNUSED(rhs); return true;}
|
||||
|
||||
private:
|
||||
mutable Element result;
|
||||
};
|
||||
|
||||
/// \brief Quotient ring
|
||||
/// \tparam T element class or type
|
||||
/// \details <tt>const Element&</tt> returned by member functions are references
|
||||
/// to internal data members. Since each object may have only
|
||||
/// one such data member for holding results, the following code
|
||||
/// will produce incorrect results:
|
||||
/// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
|
||||
/// But this should be fine:
|
||||
/// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
|
||||
template <class T> class QuotientRing : public AbstractRing<typename T::Element>
|
||||
{
|
||||
public:
|
||||
typedef T EuclideanDomain;
|
||||
typedef typename T::Element Element;
|
||||
|
||||
QuotientRing(const EuclideanDomain &domain, const Element &modulus)
|
||||
: m_domain(domain), m_modulus(modulus) {}
|
||||
|
||||
const EuclideanDomain & GetDomain() const
|
||||
{return m_domain;}
|
||||
|
||||
const Element& GetModulus() const
|
||||
{return m_modulus;}
|
||||
|
||||
bool Equal(const Element &a, const Element &b) const
|
||||
{return m_domain.Equal(m_domain.Mod(m_domain.Subtract(a, b), m_modulus), m_domain.Identity());}
|
||||
|
||||
const Element& Identity() const
|
||||
{return m_domain.Identity();}
|
||||
|
||||
const Element& Add(const Element &a, const Element &b) const
|
||||
{return m_domain.Add(a, b);}
|
||||
|
||||
Element& Accumulate(Element &a, const Element &b) const
|
||||
{return m_domain.Accumulate(a, b);}
|
||||
|
||||
const Element& Inverse(const Element &a) const
|
||||
{return m_domain.Inverse(a);}
|
||||
|
||||
const Element& Subtract(const Element &a, const Element &b) const
|
||||
{return m_domain.Subtract(a, b);}
|
||||
|
||||
Element& Reduce(Element &a, const Element &b) const
|
||||
{return m_domain.Reduce(a, b);}
|
||||
|
||||
const Element& Double(const Element &a) const
|
||||
{return m_domain.Double(a);}
|
||||
|
||||
bool IsUnit(const Element &a) const
|
||||
{return m_domain.IsUnit(m_domain.Gcd(a, m_modulus));}
|
||||
|
||||
const Element& MultiplicativeIdentity() const
|
||||
{return m_domain.MultiplicativeIdentity();}
|
||||
|
||||
const Element& Multiply(const Element &a, const Element &b) const
|
||||
{return m_domain.Mod(m_domain.Multiply(a, b), m_modulus);}
|
||||
|
||||
const Element& Square(const Element &a) const
|
||||
{return m_domain.Mod(m_domain.Square(a), m_modulus);}
|
||||
|
||||
const Element& MultiplicativeInverse(const Element &a) const;
|
||||
|
||||
bool operator==(const QuotientRing<T> &rhs) const
|
||||
{return m_domain == rhs.m_domain && m_modulus == rhs.m_modulus;}
|
||||
|
||||
protected:
|
||||
EuclideanDomain m_domain;
|
||||
Element m_modulus;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#ifdef CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES
|
||||
#include "algebra.cpp"
|
||||
#endif
|
||||
|
||||
#endif
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
// algparam.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
#include "algparam.h"
|
||||
#include "integer.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
bool CombinedNameValuePairs::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
|
||||
{
|
||||
if (strcmp(name, "ValueNames") == 0)
|
||||
return m_pairs1.GetVoidValue(name, valueType, pValue) && m_pairs2.GetVoidValue(name, valueType, pValue);
|
||||
else
|
||||
return m_pairs1.GetVoidValue(name, valueType, pValue) || m_pairs2.GetVoidValue(name, valueType, pValue);
|
||||
}
|
||||
|
||||
void AlgorithmParametersBase::operator=(const AlgorithmParametersBase &rhs)
|
||||
{
|
||||
CRYPTOPP_UNUSED(rhs);
|
||||
CRYPTOPP_ASSERT(false);
|
||||
}
|
||||
|
||||
bool AlgorithmParametersBase::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
|
||||
{
|
||||
if (strcmp(name, "ValueNames") == 0)
|
||||
{
|
||||
NameValuePairs::ThrowIfTypeMismatch(name, typeid(std::string), valueType);
|
||||
if (m_next.get())
|
||||
m_next->GetVoidValue(name, valueType, pValue);
|
||||
(*reinterpret_cast<std::string *>(pValue) += m_name) += ";";
|
||||
return true;
|
||||
}
|
||||
else if (strcmp(name, m_name) == 0)
|
||||
{
|
||||
AssignValue(name, valueType, pValue);
|
||||
m_used = true;
|
||||
return true;
|
||||
}
|
||||
else if (m_next.get())
|
||||
return m_next->GetVoidValue(name, valueType, pValue);
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
AlgorithmParameters::AlgorithmParameters()
|
||||
: m_defaultThrowIfNotUsed(true)
|
||||
{
|
||||
}
|
||||
|
||||
AlgorithmParameters::AlgorithmParameters(const AlgorithmParameters &x)
|
||||
: m_defaultThrowIfNotUsed(x.m_defaultThrowIfNotUsed)
|
||||
{
|
||||
m_next.reset(const_cast<AlgorithmParameters &>(x).m_next.release());
|
||||
}
|
||||
|
||||
AlgorithmParameters & AlgorithmParameters::operator=(const AlgorithmParameters &x)
|
||||
{
|
||||
m_next.reset(const_cast<AlgorithmParameters &>(x).m_next.release());
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool AlgorithmParameters::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
|
||||
{
|
||||
if (m_next.get())
|
||||
return m_next->GetVoidValue(name, valueType, pValue);
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+520
@@ -0,0 +1,520 @@
|
||||
// algparam.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file algparam.h
|
||||
/// \brief Classes for working with NameValuePairs
|
||||
|
||||
#ifndef CRYPTOPP_ALGPARAM_H
|
||||
#define CRYPTOPP_ALGPARAM_H
|
||||
|
||||
#include "config.h"
|
||||
#include "cryptlib.h"
|
||||
|
||||
#include "smartptr.h"
|
||||
#include "secblock.h"
|
||||
#include "integer.h"
|
||||
#include "misc.h"
|
||||
|
||||
#include <string>
|
||||
#include <typeinfo>
|
||||
#include <exception>
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief Used to pass byte array input as part of a NameValuePairs object
|
||||
class ConstByteArrayParameter
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a ConstByteArrayParameter
|
||||
/// \param data a C-String
|
||||
/// \param deepCopy flag indicating whether the data should be copied
|
||||
/// \details The deepCopy option is used when the NameValuePairs object can't
|
||||
/// keep a copy of the data available
|
||||
ConstByteArrayParameter(const char *data = NULLPTR, bool deepCopy = false)
|
||||
: m_deepCopy(false), m_data(NULLPTR), m_size(0)
|
||||
{
|
||||
Assign(reinterpret_cast<const byte *>(data), data ? strlen(data) : 0, deepCopy);
|
||||
}
|
||||
|
||||
/// \brief Construct a ConstByteArrayParameter
|
||||
/// \param data a memory buffer
|
||||
/// \param size the length of the memory buffer
|
||||
/// \param deepCopy flag indicating whether the data should be copied
|
||||
/// \details The deepCopy option is used when the NameValuePairs object can't
|
||||
/// keep a copy of the data available
|
||||
ConstByteArrayParameter(const byte *data, size_t size, bool deepCopy = false)
|
||||
: m_deepCopy(false), m_data(NULLPTR), m_size(0)
|
||||
{
|
||||
Assign(data, size, deepCopy);
|
||||
}
|
||||
|
||||
/// \brief Construct a ConstByteArrayParameter
|
||||
/// \tparam T a std::basic_string<char> or std::vector<byte> class
|
||||
/// \param string a std::basic_string<char> or std::vector<byte> object
|
||||
/// \param deepCopy flag indicating whether the data should be copied
|
||||
/// \details The deepCopy option is used when the NameValuePairs object can't
|
||||
/// keep a copy of the data available
|
||||
template <class T> ConstByteArrayParameter(const T &string, bool deepCopy = false)
|
||||
: m_deepCopy(false), m_data(NULLPTR), m_size(0)
|
||||
{
|
||||
CRYPTOPP_COMPILE_ASSERT(sizeof(typename T::value_type) == 1);
|
||||
Assign(reinterpret_cast<const byte *>(&string[0]), string.size(), deepCopy);
|
||||
}
|
||||
|
||||
/// \brief Assign contents from a memory buffer
|
||||
/// \param data a memory buffer
|
||||
/// \param size the length of the memory buffer
|
||||
/// \param deepCopy flag indicating whether the data should be copied
|
||||
/// \details The deepCopy option is used when the NameValuePairs object can't
|
||||
/// keep a copy of the data available
|
||||
void Assign(const byte *data, size_t size, bool deepCopy)
|
||||
{
|
||||
// This fires, which means: no data with a size, or data with no size.
|
||||
// CRYPTOPP_ASSERT((data && size) || !(data || size));
|
||||
if (deepCopy)
|
||||
m_block.Assign(data, size);
|
||||
else
|
||||
{
|
||||
m_data = data;
|
||||
m_size = size;
|
||||
}
|
||||
m_deepCopy = deepCopy;
|
||||
}
|
||||
|
||||
/// \brief Pointer to the first byte in the memory block
|
||||
const byte *begin() const {return m_deepCopy ? m_block.begin() : m_data;}
|
||||
/// \brief Pointer beyond the last byte in the memory block
|
||||
const byte *end() const {return m_deepCopy ? m_block.end() : m_data + m_size;}
|
||||
/// \brief Length of the memory block
|
||||
size_t size() const {return m_deepCopy ? m_block.size() : m_size;}
|
||||
|
||||
private:
|
||||
bool m_deepCopy;
|
||||
const byte *m_data;
|
||||
size_t m_size;
|
||||
SecByteBlock m_block;
|
||||
};
|
||||
|
||||
/// \brief Used to pass byte array input as part of a NameValuePairs object
|
||||
class ByteArrayParameter
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a ByteArrayParameter
|
||||
/// \param data a memory buffer
|
||||
/// \param size the length of the memory buffer
|
||||
ByteArrayParameter(byte *data = NULLPTR, unsigned int size = 0)
|
||||
: m_data(data), m_size(size) {}
|
||||
|
||||
/// \brief Construct a ByteArrayParameter
|
||||
/// \param block a SecByteBlock
|
||||
ByteArrayParameter(SecByteBlock &block)
|
||||
: m_data(block.begin()), m_size(block.size()) {}
|
||||
|
||||
/// \brief Pointer to the first byte in the memory block
|
||||
byte *begin() const {return m_data;}
|
||||
/// \brief Pointer beyond the last byte in the memory block
|
||||
byte *end() const {return m_data + m_size;}
|
||||
/// \brief Length of the memory block
|
||||
size_t size() const {return m_size;}
|
||||
|
||||
private:
|
||||
byte *m_data;
|
||||
size_t m_size;
|
||||
};
|
||||
|
||||
/// \brief Combines two sets of NameValuePairs
|
||||
/// \details CombinedNameValuePairs allows you to provide two sets of of NameValuePairs.
|
||||
/// If a name is not found in the first set, then the second set is searched for the
|
||||
/// name and value pair. The second set of NameValuePairs often provides default values.
|
||||
class CRYPTOPP_DLL CombinedNameValuePairs : public NameValuePairs
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a CombinedNameValuePairs
|
||||
/// \param pairs1 reference to the first set of NameValuePairs
|
||||
/// \param pairs2 reference to the second set of NameValuePairs
|
||||
CombinedNameValuePairs(const NameValuePairs &pairs1, const NameValuePairs &pairs2)
|
||||
: m_pairs1(pairs1), m_pairs2(pairs2) {}
|
||||
|
||||
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
|
||||
|
||||
private:
|
||||
const NameValuePairs &m_pairs1, &m_pairs2;
|
||||
};
|
||||
|
||||
#ifndef CRYPTOPP_DOXYGEN_PROCESSING
|
||||
template <class T, class BASE>
|
||||
class GetValueHelperClass
|
||||
{
|
||||
public:
|
||||
GetValueHelperClass(const T *pObject, const char *name, const std::type_info &valueType, void *pValue, const NameValuePairs *searchFirst)
|
||||
: m_pObject(pObject), m_name(name), m_valueType(&valueType), m_pValue(pValue), m_found(false), m_getValueNames(false)
|
||||
{
|
||||
if (strcmp(m_name, "ValueNames") == 0)
|
||||
{
|
||||
m_found = m_getValueNames = true;
|
||||
NameValuePairs::ThrowIfTypeMismatch(m_name, typeid(std::string), *m_valueType);
|
||||
if (searchFirst)
|
||||
searchFirst->GetVoidValue(m_name, valueType, pValue);
|
||||
if (typeid(T) != typeid(BASE))
|
||||
pObject->BASE::GetVoidValue(m_name, valueType, pValue);
|
||||
((*reinterpret_cast<std::string *>(m_pValue) += "ThisPointer:") += typeid(T).name()) += ';';
|
||||
}
|
||||
|
||||
if (!m_found && strncmp(m_name, "ThisPointer:", 12) == 0 && strcmp(m_name+12, typeid(T).name()) == 0)
|
||||
{
|
||||
NameValuePairs::ThrowIfTypeMismatch(m_name, typeid(T *), *m_valueType);
|
||||
*reinterpret_cast<const T **>(pValue) = pObject;
|
||||
m_found = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!m_found && searchFirst)
|
||||
m_found = searchFirst->GetVoidValue(m_name, valueType, pValue);
|
||||
|
||||
if (!m_found && typeid(T) != typeid(BASE))
|
||||
m_found = pObject->BASE::GetVoidValue(m_name, valueType, pValue);
|
||||
}
|
||||
|
||||
operator bool() const {return m_found;}
|
||||
|
||||
template <class R>
|
||||
GetValueHelperClass<T,BASE> & operator()(const char *name, const R & (T::*pm)() const)
|
||||
{
|
||||
if (m_getValueNames)
|
||||
(*reinterpret_cast<std::string *>(m_pValue) += name) += ";";
|
||||
if (!m_found && strcmp(name, m_name) == 0)
|
||||
{
|
||||
NameValuePairs::ThrowIfTypeMismatch(name, typeid(R), *m_valueType);
|
||||
*reinterpret_cast<R *>(m_pValue) = (m_pObject->*pm)();
|
||||
m_found = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
GetValueHelperClass<T,BASE> &Assignable()
|
||||
{
|
||||
#ifndef __INTEL_COMPILER // ICL 9.1 workaround: Intel compiler copies the vTable pointer for some reason
|
||||
if (m_getValueNames)
|
||||
((*reinterpret_cast<std::string *>(m_pValue) += "ThisObject:") += typeid(T).name()) += ';';
|
||||
if (!m_found && strncmp(m_name, "ThisObject:", 11) == 0 && strcmp(m_name+11, typeid(T).name()) == 0)
|
||||
{
|
||||
NameValuePairs::ThrowIfTypeMismatch(m_name, typeid(T), *m_valueType);
|
||||
*reinterpret_cast<T *>(m_pValue) = *m_pObject;
|
||||
m_found = true;
|
||||
}
|
||||
#endif
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
const T *m_pObject;
|
||||
const char *m_name;
|
||||
const std::type_info *m_valueType;
|
||||
void *m_pValue;
|
||||
bool m_found, m_getValueNames;
|
||||
};
|
||||
|
||||
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=NULLPTR)
|
||||
{
|
||||
return GetValueHelperClass<T, BASE>(pObject, name, valueType, pValue, searchFirst);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
GetValueHelperClass<T, T> GetValueHelper(const T *pObject, const char *name, const std::type_info &valueType, void *pValue, const NameValuePairs *searchFirst=NULLPTR)
|
||||
{
|
||||
return GetValueHelperClass<T, T>(pObject, name, valueType, pValue, searchFirst);
|
||||
}
|
||||
|
||||
// ********************************************************
|
||||
|
||||
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)(const R&))
|
||||
{
|
||||
if (!m_done)
|
||||
{
|
||||
R value;
|
||||
if (!m_source.GetValue(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)(const R&, const S&))
|
||||
{
|
||||
if (!m_done)
|
||||
{
|
||||
R value1;
|
||||
if (!m_source.GetValue(name1, value1))
|
||||
throw InvalidArgument(std::string(typeid(T).name()) + ": Missing required parameter '" + name1 + "'");
|
||||
S value2;
|
||||
if (!m_source.GetValue(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;
|
||||
};
|
||||
|
||||
template <class BASE, class T>
|
||||
AssignFromHelperClass<T, BASE> AssignFromHelper(T *pObject, const NameValuePairs &source)
|
||||
{
|
||||
return AssignFromHelperClass<T, BASE>(pObject, source);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
AssignFromHelperClass<T, T> AssignFromHelper(T *pObject, const NameValuePairs &source)
|
||||
{
|
||||
return AssignFromHelperClass<T, T>(pObject, source);
|
||||
}
|
||||
|
||||
#endif // CRYPTOPP_DOXYGEN_PROCESSING
|
||||
|
||||
// ********************************************************
|
||||
|
||||
#ifndef CRYPTOPP_NO_ASSIGN_TO_INTEGER
|
||||
// Allow the linker to discard Integer code if not needed.
|
||||
// Also see http://github.com/weidai11/cryptopp/issues/389.
|
||||
CRYPTOPP_DLL bool AssignIntToInteger(const std::type_info &valueType, void *pInteger, const void *pInt);
|
||||
#endif
|
||||
|
||||
CRYPTOPP_DLL const std::type_info & CRYPTOPP_API IntegerTypeId();
|
||||
|
||||
/// \brief Base class for AlgorithmParameters
|
||||
class CRYPTOPP_DLL AlgorithmParametersBase
|
||||
{
|
||||
public:
|
||||
/// \brief Exception thrown when an AlgorithmParameter is unused
|
||||
class ParameterNotUsed : public Exception
|
||||
{
|
||||
public:
|
||||
ParameterNotUsed(const char *name) : Exception(OTHER_ERROR, std::string("AlgorithmParametersBase: parameter \"") + name + "\" not used") {}
|
||||
};
|
||||
|
||||
virtual ~AlgorithmParametersBase() CRYPTOPP_THROW
|
||||
{
|
||||
|
||||
#if defined(CRYPTOPP_CXX17_UNCAUGHT_EXCEPTIONS)
|
||||
if (std::uncaught_exceptions() == 0)
|
||||
#elif defined(CRYPTOPP_CXX98_UNCAUGHT_EXCEPTION)
|
||||
if (std::uncaught_exception() == false)
|
||||
#else
|
||||
try
|
||||
#endif
|
||||
{
|
||||
if (m_throwIfNotUsed && !m_used)
|
||||
throw ParameterNotUsed(m_name);
|
||||
}
|
||||
#if !defined(CRYPTOPP_CXX98_UNCAUGHT_EXCEPTION)
|
||||
# if !defined(CRYPTOPP_CXX17_UNCAUGHT_EXCEPTIONS)
|
||||
catch(const Exception&)
|
||||
{
|
||||
}
|
||||
# endif
|
||||
#endif
|
||||
}
|
||||
|
||||
// this is actually a move, not a copy
|
||||
AlgorithmParametersBase(const AlgorithmParametersBase &x)
|
||||
: m_name(x.m_name), m_throwIfNotUsed(x.m_throwIfNotUsed), m_used(x.m_used)
|
||||
{
|
||||
m_next.reset(const_cast<AlgorithmParametersBase &>(x).m_next.release());
|
||||
x.m_used = true;
|
||||
}
|
||||
|
||||
/// \brief Construct a AlgorithmParametersBase
|
||||
/// \param name the parameter name
|
||||
/// \param throwIfNotUsed flags indicating whether an exception should be thrown
|
||||
/// \details If throwIfNotUsed is true, then a ParameterNotUsed exception
|
||||
/// will be thrown in the destructor if the parameter is not not retrieved.
|
||||
AlgorithmParametersBase(const char *name, bool throwIfNotUsed)
|
||||
: m_name(name), m_throwIfNotUsed(throwIfNotUsed), m_used(false) {}
|
||||
|
||||
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
|
||||
|
||||
protected:
|
||||
friend class AlgorithmParameters;
|
||||
void operator=(const AlgorithmParametersBase& rhs); // assignment not allowed, declare this for VC60
|
||||
|
||||
virtual void AssignValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
|
||||
virtual void MoveInto(void *p) const =0; // not really const
|
||||
|
||||
const char *m_name;
|
||||
bool m_throwIfNotUsed;
|
||||
mutable bool m_used;
|
||||
member_ptr<AlgorithmParametersBase> m_next;
|
||||
};
|
||||
|
||||
/// \brief Template base class for AlgorithmParameters
|
||||
/// \tparam T the class or type
|
||||
template <class T>
|
||||
class AlgorithmParametersTemplate : public AlgorithmParametersBase
|
||||
{
|
||||
public:
|
||||
/// \brief Construct an AlgorithmParametersTemplate
|
||||
/// \param name the name of the value
|
||||
/// \param value a reference to the value
|
||||
/// \param throwIfNotUsed flags indicating whether an exception should be thrown
|
||||
/// \details If throwIfNotUsed is true, then a ParameterNotUsed exception
|
||||
/// will be thrown in the destructor if the parameter is not not retrieved.
|
||||
AlgorithmParametersTemplate(const char *name, const T &value, bool throwIfNotUsed)
|
||||
: AlgorithmParametersBase(name, throwIfNotUsed), m_value(value)
|
||||
{
|
||||
}
|
||||
|
||||
void AssignValue(const char *name, const std::type_info &valueType, void *pValue) const
|
||||
{
|
||||
#ifndef CRYPTOPP_NO_ASSIGN_TO_INTEGER
|
||||
// Special case for retrieving an Integer parameter when an int was passed in
|
||||
if (!(typeid(T) == typeid(int) && AssignIntToInteger(valueType, pValue, &m_value)))
|
||||
#endif
|
||||
{
|
||||
NameValuePairs::ThrowIfTypeMismatch(name, typeid(T), valueType);
|
||||
*reinterpret_cast<T *>(pValue) = m_value;
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(DEBUG_NEW) && (_MSC_VER >= 1300)
|
||||
# pragma push_macro("new")
|
||||
# undef new
|
||||
#endif
|
||||
|
||||
void MoveInto(void *buffer) const
|
||||
{
|
||||
AlgorithmParametersTemplate<T>* p = new(buffer) AlgorithmParametersTemplate<T>(*this);
|
||||
CRYPTOPP_UNUSED(p); // silence warning
|
||||
}
|
||||
|
||||
#if defined(DEBUG_NEW) && (_MSC_VER >= 1300)
|
||||
# pragma pop_macro("new")
|
||||
#endif
|
||||
|
||||
protected:
|
||||
T m_value;
|
||||
};
|
||||
|
||||
CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<bool>;
|
||||
CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<int>;
|
||||
CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<ConstByteArrayParameter>;
|
||||
|
||||
/// \brief An object that implements NameValuePairs
|
||||
/// \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by
|
||||
/// repeatedly using operator() on the object returned by MakeParameters, for example:
|
||||
/// <pre>
|
||||
/// AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3);
|
||||
/// </pre>
|
||||
class CRYPTOPP_DLL AlgorithmParameters : public NameValuePairs
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a AlgorithmParameters
|
||||
/// \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by
|
||||
/// repeatedly using operator() on the object returned by MakeParameters, for example:
|
||||
/// <pre>
|
||||
/// AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3);
|
||||
/// </pre>
|
||||
AlgorithmParameters();
|
||||
|
||||
#ifdef __BORLANDC__
|
||||
/// \brief Construct a AlgorithmParameters
|
||||
/// \tparam T the class or type
|
||||
/// \param name the name of the object or value to retrieve
|
||||
/// \param value reference to a variable that receives the value
|
||||
/// \param throwIfNotUsed if true, the object will throw an exception if the value is not accessed
|
||||
/// \note throwIfNotUsed is ignored if using a compiler that does not support std::uncaught_exception(),
|
||||
/// such as MSVC 7.0 and earlier.
|
||||
/// \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by
|
||||
/// repeatedly using operator() on the object returned by MakeParameters, for example:
|
||||
/// <pre>
|
||||
/// AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3);
|
||||
/// </pre>
|
||||
template <class T>
|
||||
AlgorithmParameters(const char *name, const T &value, bool throwIfNotUsed=true)
|
||||
: m_next(new AlgorithmParametersTemplate<T>(name, value, throwIfNotUsed))
|
||||
, m_defaultThrowIfNotUsed(throwIfNotUsed)
|
||||
{
|
||||
}
|
||||
#endif
|
||||
|
||||
AlgorithmParameters(const AlgorithmParameters &x);
|
||||
|
||||
AlgorithmParameters & operator=(const AlgorithmParameters &x);
|
||||
|
||||
/// \tparam T the class or type
|
||||
/// \param name the name of the object or value to retrieve
|
||||
/// \param value reference to a variable that receives the value
|
||||
/// \param throwIfNotUsed if true, the object will throw an exception if the value is not accessed
|
||||
template <class T>
|
||||
AlgorithmParameters & operator()(const char *name, const T &value, bool throwIfNotUsed)
|
||||
{
|
||||
member_ptr<AlgorithmParametersBase> p(new AlgorithmParametersTemplate<T>(name, value, throwIfNotUsed));
|
||||
p->m_next.reset(m_next.release());
|
||||
m_next.reset(p.release());
|
||||
m_defaultThrowIfNotUsed = throwIfNotUsed;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/// \brief Appends a NameValuePair to a collection of NameValuePairs
|
||||
/// \tparam T the class or type
|
||||
/// \param name the name of the object or value to retrieve
|
||||
/// \param value reference to a variable that receives the value
|
||||
template <class T>
|
||||
AlgorithmParameters & operator()(const char *name, const T &value)
|
||||
{
|
||||
return operator()(name, value, m_defaultThrowIfNotUsed);
|
||||
}
|
||||
|
||||
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
|
||||
|
||||
protected:
|
||||
member_ptr<AlgorithmParametersBase> m_next;
|
||||
bool m_defaultThrowIfNotUsed;
|
||||
};
|
||||
|
||||
/// \brief Create an object that implements NameValuePairs
|
||||
/// \tparam T the class or type
|
||||
/// \param name the name of the object or value to retrieve
|
||||
/// \param value reference to a variable that receives the value
|
||||
/// \param throwIfNotUsed if true, the object will throw an exception if the value is not accessed
|
||||
/// \note throwIfNotUsed is ignored if using a compiler that does not support std::uncaught_exception(),
|
||||
/// such as MSVC 7.0 and earlier.
|
||||
/// \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by
|
||||
/// repeatedly using \p operator() on the object returned by \p MakeParameters, for example:
|
||||
/// <pre>
|
||||
/// AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3);
|
||||
/// </pre>
|
||||
#ifdef __BORLANDC__
|
||||
typedef AlgorithmParameters MakeParameters;
|
||||
#else
|
||||
template <class T>
|
||||
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed = true)
|
||||
{
|
||||
return AlgorithmParameters()(name, value, throwIfNotUsed);
|
||||
}
|
||||
#endif
|
||||
|
||||
#define CRYPTOPP_GET_FUNCTION_ENTRY(name) (Name::name(), &ThisClass::Get##name)
|
||||
#define CRYPTOPP_SET_FUNCTION_ENTRY(name) (Name::name(), &ThisClass::Set##name)
|
||||
#define CRYPTOPP_SET_FUNCTION_ENTRY2(name1, name2) (Name::name1(), Name::name2(), &ThisClass::Set##name1##And##name2)
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
// allocate.cpp - written and placed in the public domain by Jeffrey Walton
|
||||
|
||||
// The functions in allocate.h and allocate.cpp were originally in misc.h
|
||||
// and misc.cpp. They were extracted in September 2019 to sidestep a circular
|
||||
// dependency with misc.h and secblock.h.
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
#include "allocate.h"
|
||||
#include "stdcpp.h"
|
||||
#include "misc.h"
|
||||
#include "trap.h"
|
||||
|
||||
// for memalign
|
||||
#if defined(CRYPTOPP_MEMALIGN_AVAILABLE) || defined(CRYPTOPP_MM_MALLOC_AVAILABLE) || defined(QNX)
|
||||
# include <malloc.h>
|
||||
#endif
|
||||
// for posix_memalign
|
||||
#if defined(CRYPTOPP_POSIX_MEMALIGN_AVAILABLE)
|
||||
# include <stdlib.h>
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
void CallNewHandler()
|
||||
{
|
||||
using std::new_handler;
|
||||
using std::set_new_handler;
|
||||
|
||||
new_handler newHandler = set_new_handler(NULLPTR);
|
||||
if (newHandler)
|
||||
set_new_handler(newHandler);
|
||||
|
||||
if (newHandler)
|
||||
newHandler();
|
||||
else
|
||||
throw std::bad_alloc();
|
||||
}
|
||||
|
||||
void * AlignedAllocate(size_t size)
|
||||
{
|
||||
byte *p;
|
||||
#if defined(CRYPTOPP_MM_MALLOC_AVAILABLE)
|
||||
while ((p = (byte *)_mm_malloc(size, 16)) == NULLPTR)
|
||||
#elif defined(CRYPTOPP_MEMALIGN_AVAILABLE)
|
||||
while ((p = (byte *)memalign(16, size)) == NULLPTR)
|
||||
#elif defined(CRYPTOPP_MALLOC_ALIGNMENT_IS_16)
|
||||
while ((p = (byte *)malloc(size)) == NULLPTR)
|
||||
#elif defined(CRYPTOPP_POSIX_MEMALIGN_AVAILABLE)
|
||||
while (posix_memalign(reinterpret_cast<void**>(&p), 16, size) != 0)
|
||||
#else
|
||||
while ((p = (byte *)malloc(size + 16)) == NULLPTR)
|
||||
#endif
|
||||
CallNewHandler();
|
||||
|
||||
#ifdef CRYPTOPP_NO_ALIGNED_ALLOC
|
||||
size_t adjustment = 16-((size_t)p%16);
|
||||
CRYPTOPP_ASSERT(adjustment > 0);
|
||||
p += adjustment;
|
||||
p[-1] = (byte)adjustment;
|
||||
#endif
|
||||
|
||||
// If this assert fires then there are problems that need
|
||||
// to be fixed. Please open a bug report.
|
||||
CRYPTOPP_ASSERT(IsAlignedOn(p, 16));
|
||||
return p;
|
||||
}
|
||||
|
||||
void AlignedDeallocate(void *p)
|
||||
{
|
||||
// Guard pointer due to crash on AIX when CRYPTOPP_NO_ALIGNED_ALLOC
|
||||
// is in effect. The guard was previously in place in SecBlock,
|
||||
// but it was removed at f4d68353ca7c as part of GH #875.
|
||||
CRYPTOPP_ASSERT(p);
|
||||
|
||||
if (p != NULLPTR)
|
||||
{
|
||||
#ifdef CRYPTOPP_MM_MALLOC_AVAILABLE
|
||||
_mm_free(p);
|
||||
#elif defined(CRYPTOPP_NO_ALIGNED_ALLOC)
|
||||
p = (byte *)p - ((byte *)p)[-1];
|
||||
free(p);
|
||||
#else
|
||||
free(p);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
void * UnalignedAllocate(size_t size)
|
||||
{
|
||||
void *p;
|
||||
while ((p = malloc(size)) == NULLPTR)
|
||||
CallNewHandler();
|
||||
return p;
|
||||
}
|
||||
|
||||
void UnalignedDeallocate(void *p)
|
||||
{
|
||||
free(p);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif // CRYPTOPP_IMPORTS
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
// allocate.h - written and placed in the public domain by Jeffrey Walton
|
||||
|
||||
// The functions in allocate.h and allocate.cpp were originally in misc.h
|
||||
// and misc.cpp. They were extracted in September 2019 to sidestep a circular
|
||||
// dependency with misc.h and secblock.h.
|
||||
|
||||
/// \file allocate.h
|
||||
/// \brief Functions for allocating aligned buffers
|
||||
|
||||
#ifndef CRYPTOPP_ALLOCATE_H
|
||||
#define CRYPTOPP_ALLOCATE_H
|
||||
|
||||
#include "config.h"
|
||||
#include "cryptlib.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief Attempts to reclaim unused memory
|
||||
/// \throw bad_alloc
|
||||
/// \details In the normal course of running a program, a request for memory
|
||||
/// normally succeeds. If a call to AlignedAllocate or UnalignedAllocate fails,
|
||||
/// then CallNewHandler is called in n effort to recover. Internally,
|
||||
/// CallNewHandler calls set_new_handler(nullptr) in an effort to free memory.
|
||||
/// There is no guarantee CallNewHandler will be able to obtain more memory so
|
||||
/// an allocation succeeds. If the call to set_new_handler fails, then CallNewHandler
|
||||
/// throws a bad_alloc exception.
|
||||
/// \throw bad_alloc on failure
|
||||
/// \since Crypto++ 5.0
|
||||
/// \sa AlignedAllocate, AlignedDeallocate, UnalignedAllocate, UnalignedDeallocate
|
||||
CRYPTOPP_DLL void CRYPTOPP_API CallNewHandler();
|
||||
|
||||
/// \brief Allocates a buffer on 16-byte boundary
|
||||
/// \param size the size of the buffer
|
||||
/// \details AlignedAllocate is primarily used when the data will be
|
||||
/// processed by SSE, NEON, ARMv8 or PowerPC instructions. The assembly
|
||||
/// language routines rely on the alignment. If the alignment is not
|
||||
/// respected, then a SIGBUS could be generated on Unix and Linux, and an
|
||||
/// EXCEPTION_DATATYPE_MISALIGNMENT could be generated on Windows.
|
||||
/// \details Formerly, AlignedAllocate and AlignedDeallocate were only
|
||||
/// available on certain platforms when CRYTPOPP_DISABLE_ASM was not in
|
||||
/// effect. However, Android and iOS debug simulator builds got into a
|
||||
/// state where the aligned allocator was not available and caused link
|
||||
/// failures.
|
||||
/// \since AlignedAllocate for SIMD since Crypto++ 1.0, AlignedAllocate
|
||||
/// for all builds since Crypto++ 8.1
|
||||
/// \sa AlignedDeallocate, UnalignedAllocate, UnalignedDeallocate, CallNewHandler,
|
||||
/// <A HREF="http://github.com/weidai11/cryptopp/issues/779">Issue 779</A>
|
||||
CRYPTOPP_DLL void* CRYPTOPP_API AlignedAllocate(size_t size);
|
||||
|
||||
/// \brief Frees a buffer allocated with AlignedAllocate
|
||||
/// \param ptr the buffer to free
|
||||
/// \since AlignedDeallocate for SIMD since Crypto++ 1.0, AlignedAllocate
|
||||
/// for all builds since Crypto++ 8.1
|
||||
/// \sa AlignedAllocate, UnalignedAllocate, UnalignedDeallocate, CallNewHandler,
|
||||
/// <A HREF="http://github.com/weidai11/cryptopp/issues/779">Issue 779</A>
|
||||
CRYPTOPP_DLL void CRYPTOPP_API AlignedDeallocate(void *ptr);
|
||||
|
||||
/// \brief Allocates a buffer
|
||||
/// \param size the size of the buffer
|
||||
/// \since Crypto++ 1.0
|
||||
/// \sa AlignedAllocate, AlignedDeallocate, UnalignedDeallocate, CallNewHandler,
|
||||
/// <A HREF="http://github.com/weidai11/cryptopp/issues/779">Issue 779</A>
|
||||
CRYPTOPP_DLL void * CRYPTOPP_API UnalignedAllocate(size_t size);
|
||||
|
||||
/// \brief Frees a buffer allocated with UnalignedAllocate
|
||||
/// \param ptr the buffer to free
|
||||
/// \since Crypto++ 1.0
|
||||
/// \sa AlignedAllocate, AlignedDeallocate, UnalignedAllocate, CallNewHandler,
|
||||
/// <A HREF="http://github.com/weidai11/cryptopp/issues/779">Issue 779</A>
|
||||
CRYPTOPP_DLL void CRYPTOPP_API UnalignedDeallocate(void *ptr);
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif // CRYPTOPP_ALLOCATE_H
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
// arc4.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
// The ARC4 algorithm was first revealed in an anonymous email to the
|
||||
// cypherpunks mailing list. This file originally contained some
|
||||
// code copied from this email. The code has since been rewritten in order
|
||||
// to clarify the copyright status of this file. It should now be
|
||||
// completely in the public domain.
|
||||
|
||||
#include "pch.h"
|
||||
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
|
||||
#include "arc4.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
namespace Weak1 {
|
||||
|
||||
#if defined(CRYPTOPP_DEBUG) && !defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
void ARC4_TestInstantiations()
|
||||
{
|
||||
ARC4 x;
|
||||
}
|
||||
#endif
|
||||
|
||||
ARC4_Base::~ARC4_Base()
|
||||
{
|
||||
m_x = m_y = 0;
|
||||
}
|
||||
|
||||
void ARC4_Base::UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms)
|
||||
{
|
||||
AssertValidKeyLength(length);
|
||||
|
||||
m_x = 1;
|
||||
m_y = 0;
|
||||
|
||||
unsigned int i;
|
||||
for (i=0; i<256; i++)
|
||||
m_state[i] = byte(i);
|
||||
|
||||
unsigned int keyIndex = 0, stateIndex = 0;
|
||||
for (i=0; i<256; i++)
|
||||
{
|
||||
unsigned int a = m_state[i];
|
||||
stateIndex += key[keyIndex] + a;
|
||||
stateIndex &= 0xff;
|
||||
m_state[i] = m_state[stateIndex];
|
||||
m_state[stateIndex] = byte(a);
|
||||
if (++keyIndex >= length)
|
||||
keyIndex = 0;
|
||||
}
|
||||
|
||||
int discardBytes = params.GetIntValueWithDefault("DiscardBytes", GetDefaultDiscardBytes());
|
||||
DiscardBytes(discardBytes);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
static inline unsigned int MakeByte(T &x, T &y, byte *s)
|
||||
{
|
||||
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++ = static_cast<byte>(MakeByte(m_x, m_y, m_state));
|
||||
}
|
||||
|
||||
void ARC4_Base::ProcessData(byte *outString, const byte *inString, size_t length)
|
||||
{
|
||||
if (length == 0)
|
||||
return;
|
||||
|
||||
byte *const s = m_state;
|
||||
unsigned int x = m_x;
|
||||
unsigned int y = m_y;
|
||||
|
||||
if (inString == outString)
|
||||
{
|
||||
do
|
||||
{
|
||||
*outString++ ^= MakeByte(x, y, s);
|
||||
} while (--length);
|
||||
}
|
||||
else
|
||||
{
|
||||
do
|
||||
{
|
||||
*outString++ = *inString++ ^ byte(MakeByte(x, y, s));
|
||||
}
|
||||
while(--length);
|
||||
}
|
||||
|
||||
m_x = byte(x);
|
||||
m_y = byte(y);
|
||||
}
|
||||
|
||||
void ARC4_Base::DiscardBytes(size_t n)
|
||||
{
|
||||
if (n == 0)
|
||||
return;
|
||||
|
||||
byte *const s = m_state;
|
||||
unsigned int x = m_x;
|
||||
unsigned int y = m_y;
|
||||
|
||||
do
|
||||
{
|
||||
MakeByte(x, y, s);
|
||||
}
|
||||
while(--n);
|
||||
|
||||
m_x = byte(x);
|
||||
m_y = byte(y);
|
||||
}
|
||||
|
||||
}
|
||||
NAMESPACE_END
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
// arc4.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file arc4.h
|
||||
/// \brief Classes for ARC4 cipher
|
||||
/// \since Crypto++ 3.1
|
||||
|
||||
#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 {
|
||||
|
||||
/// \brief ARC4 base class
|
||||
/// \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions
|
||||
/// \since Crypto++ 3.1
|
||||
class CRYPTOPP_NO_VTABLE ARC4_Base : public VariableKeyLength<16, 1, 256>, public RandomNumberGenerator, public SymmetricCipher, public SymmetricCipherDocumentation
|
||||
{
|
||||
public:
|
||||
~ARC4_Base();
|
||||
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "ARC4";}
|
||||
|
||||
void GenerateBlock(byte *output, size_t size);
|
||||
void DiscardBytes(size_t n);
|
||||
|
||||
void ProcessData(byte *outString, const byte *inString, size_t length);
|
||||
|
||||
bool IsRandomAccess() const {return false;}
|
||||
bool IsSelfInverting() const {return true;}
|
||||
bool IsForwardTransformation() const {return true;}
|
||||
|
||||
typedef SymmetricCipherFinal<ARC4_Base> Encryption;
|
||||
typedef SymmetricCipherFinal<ARC4_Base> Decryption;
|
||||
|
||||
protected:
|
||||
void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms);
|
||||
virtual unsigned int GetDefaultDiscardBytes() const {return 0;}
|
||||
|
||||
FixedSizeSecBlock<byte, 256> m_state;
|
||||
byte m_x, m_y;
|
||||
};
|
||||
|
||||
/// \brief Alleged RC4
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/RC4">Alleged RC4</a>
|
||||
/// \since Crypto++ 3.1
|
||||
DOCUMENTED_TYPEDEF(SymmetricCipherFinal<ARC4_Base>, ARC4);
|
||||
|
||||
/// \brief MARC4 base class
|
||||
/// \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions
|
||||
/// \details MARC4 discards the first 256 bytes of keystream, which may be weaker than the rest
|
||||
/// \since Crypto++ 3.1
|
||||
class CRYPTOPP_NO_VTABLE MARC4_Base : public ARC4_Base
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "MARC4";}
|
||||
|
||||
typedef SymmetricCipherFinal<MARC4_Base> Encryption;
|
||||
typedef SymmetricCipherFinal<MARC4_Base> Decryption;
|
||||
|
||||
protected:
|
||||
unsigned int GetDefaultDiscardBytes() const {return 256;}
|
||||
};
|
||||
|
||||
/// \brief Modified Alleged RC4
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/RC4">Alleged RC4</a>
|
||||
/// \since Crypto++ 3.1
|
||||
DOCUMENTED_TYPEDEF(SymmetricCipherFinal<MARC4_Base>, MARC4);
|
||||
|
||||
}
|
||||
#if CRYPTOPP_ENABLE_NAMESPACE_WEAK >= 1
|
||||
namespace Weak {using namespace Weak1;} // import Weak1 into CryptoPP::Weak
|
||||
#else
|
||||
using namespace Weak1; // import Weak1 into CryptoPP with warning
|
||||
#ifdef __GNUC__
|
||||
#warning "You may be using a weak algorithm that has been retained for backwards compatibility. Please '#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1' before including this .h file and prepend the class name with 'Weak::' to remove this warning."
|
||||
#else
|
||||
#pragma message("You may be using a weak algorithm that has been retained for backwards compatibility. Please '#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1' before including this .h file and prepend the class name with 'Weak::' to remove this warning.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
// argnames.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file argnames.h
|
||||
/// \brief Standard names for retrieving values by name when working with \p NameValuePairs
|
||||
|
||||
#ifndef CRYPTOPP_ARGNAMES_H
|
||||
#define CRYPTOPP_ARGNAMES_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
DOCUMENTED_NAMESPACE_BEGIN(Name)
|
||||
|
||||
#define CRYPTOPP_DEFINE_NAME_STRING(name) inline const char *name() {return #name;}
|
||||
|
||||
CRYPTOPP_DEFINE_NAME_STRING(ValueNames) ///< string, a list of value names with a semicolon (';') after each name
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Version) ///< int
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Seed) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Key) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(IV) ///< ConstByteArrayParameter, also accepts const byte * for backwards compatibility
|
||||
CRYPTOPP_DEFINE_NAME_STRING(StolenIV) ///< byte *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Nonce) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Rounds) ///< int
|
||||
CRYPTOPP_DEFINE_NAME_STRING(FeedbackSize) ///< int
|
||||
CRYPTOPP_DEFINE_NAME_STRING(WordSize) ///< int, in bytes
|
||||
CRYPTOPP_DEFINE_NAME_STRING(BlockSize) ///< int, in bytes
|
||||
CRYPTOPP_DEFINE_NAME_STRING(EffectiveKeyLength) ///< int, in bits
|
||||
CRYPTOPP_DEFINE_NAME_STRING(KeySize) ///< int, in bits
|
||||
CRYPTOPP_DEFINE_NAME_STRING(ModulusSize) ///< int, in bits
|
||||
CRYPTOPP_DEFINE_NAME_STRING(SubgroupOrderSize) ///< int, in bits
|
||||
CRYPTOPP_DEFINE_NAME_STRING(PrivateExponentSize)///< int, in bits
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Modulus) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(PublicExponent) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(PrivateExponent) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(PublicElement) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(SubgroupOrder) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Cofactor) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(SubgroupGenerator) ///< Integer, ECP::Point, or EC2N::Point
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Curve) ///< ECP or EC2N
|
||||
CRYPTOPP_DEFINE_NAME_STRING(GroupOID) ///< OID
|
||||
CRYPTOPP_DEFINE_NAME_STRING(PointerToPrimeSelector) ///< const PrimeSelector *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Prime1) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Prime2) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(ModPrime1PrivateExponent) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(ModPrime2PrivateExponent) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(MultiplicativeInverseOfPrime2ModPrime1) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(QuadraticResidueModPrime1) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(QuadraticResidueModPrime2) ///< Integer
|
||||
CRYPTOPP_DEFINE_NAME_STRING(PutMessage) ///< bool
|
||||
CRYPTOPP_DEFINE_NAME_STRING(TruncatedDigestSize) ///< int
|
||||
CRYPTOPP_DEFINE_NAME_STRING(BlockPaddingScheme) ///< StreamTransformationFilter::BlockPaddingScheme
|
||||
CRYPTOPP_DEFINE_NAME_STRING(HashVerificationFilterFlags) ///< word32
|
||||
CRYPTOPP_DEFINE_NAME_STRING(AuthenticatedDecryptionFilterFlags) ///< word32
|
||||
CRYPTOPP_DEFINE_NAME_STRING(SignatureVerificationFilterFlags) ///< word32
|
||||
CRYPTOPP_DEFINE_NAME_STRING(InputBuffer) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(OutputBuffer) ///< ByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(InputFileName) ///< const char *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(InputFileNameWide) ///< const wchar_t *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(InputStreamPointer) ///< std::istream *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(InputBinaryMode) ///< bool
|
||||
CRYPTOPP_DEFINE_NAME_STRING(OutputFileName) ///< const char *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(OutputFileNameWide) ///< const wchar_t *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(OutputStreamPointer) ///< std::ostream *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(OutputBinaryMode) ///< bool
|
||||
CRYPTOPP_DEFINE_NAME_STRING(EncodingParameters) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(KeyDerivationParameters) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Separator) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Terminator) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Uppercase) ///< bool
|
||||
CRYPTOPP_DEFINE_NAME_STRING(GroupSize) ///< int
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Pad) ///< bool
|
||||
CRYPTOPP_DEFINE_NAME_STRING(PaddingByte) ///< byte
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Log2Base) ///< int
|
||||
CRYPTOPP_DEFINE_NAME_STRING(EncodingLookupArray) ///< const byte *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(DecodingLookupArray) ///< const byte *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(InsertLineBreaks) ///< bool
|
||||
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(Blinding) ///< bool, timing attack mitigations, ON by default
|
||||
CRYPTOPP_DEFINE_NAME_STRING(DerivedKey) ///< ByteArrayParameter, key derivation, derived key
|
||||
CRYPTOPP_DEFINE_NAME_STRING(DerivedKeyLength) ///< int, key derivation, derived key length in bytes
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Personalization) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(PersonalizationSize) ///< int, in bytes
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Salt) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Tweak) ///< ConstByteArrayParameter
|
||||
CRYPTOPP_DEFINE_NAME_STRING(SaltSize) ///< int, in bytes
|
||||
CRYPTOPP_DEFINE_NAME_STRING(TreeMode) ///< byte
|
||||
CRYPTOPP_DEFINE_NAME_STRING(FileName) ///< const char *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(FileTime) ///< int
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Comment) ///< const char *
|
||||
CRYPTOPP_DEFINE_NAME_STRING(Identity) ///< ConstByteArrayParameter
|
||||
DOCUMENTED_NAMESPACE_END
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+343
@@ -0,0 +1,343 @@
|
||||
// aria.cpp - written and placed in the public domain by Jeffrey Walton
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
|
||||
#include "aria.h"
|
||||
#include "misc.h"
|
||||
#include "cpu.h"
|
||||
|
||||
#if CRYPTOPP_SSE2_INTRIN_AVAILABLE
|
||||
# define CRYPTOPP_ENABLE_ARIA_SSE2_INTRINSICS 1
|
||||
#endif
|
||||
|
||||
#if CRYPTOPP_SSSE3_AVAILABLE
|
||||
# define CRYPTOPP_ENABLE_ARIA_SSSE3_INTRINSICS 1
|
||||
#endif
|
||||
|
||||
// GCC cast warning. Note: this is used on round key table,
|
||||
// which is word32 and naturally aligned.
|
||||
#define UINT32_CAST(x) ((word32 *)(void *)(x))
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
NAMESPACE_BEGIN(ARIATab)
|
||||
|
||||
extern const word32 S1[256];
|
||||
extern const word32 S2[256];
|
||||
extern const word32 X1[256];
|
||||
extern const word32 X2[256];
|
||||
extern const word32 KRK[3][4];
|
||||
|
||||
NAMESPACE_END
|
||||
NAMESPACE_END
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
using CryptoPP::ARIATab::S1;
|
||||
using CryptoPP::ARIATab::S2;
|
||||
using CryptoPP::ARIATab::X1;
|
||||
using CryptoPP::ARIATab::X2;
|
||||
using CryptoPP::ARIATab::KRK;
|
||||
|
||||
inline byte ARIA_BRF(const word32 x, const int y) {
|
||||
return static_cast<byte>(GETBYTE(x, y));
|
||||
}
|
||||
|
||||
// Key XOR Layer
|
||||
#define ARIA_KXL { \
|
||||
typedef BlockGetAndPut<word32, NativeByteOrder, true, true> NativeBlock; \
|
||||
NativeBlock::Put(rk, t)(t[0])(t[1])(t[2])(t[3]); \
|
||||
}
|
||||
|
||||
// S-Box Layer 1 + M
|
||||
#define SBL1_M(T0,T1,T2,T3) { \
|
||||
T0=S1[ARIA_BRF(T0,3)]^S2[ARIA_BRF(T0,2)]^X1[ARIA_BRF(T0,1)]^X2[ARIA_BRF(T0,0)]; \
|
||||
T1=S1[ARIA_BRF(T1,3)]^S2[ARIA_BRF(T1,2)]^X1[ARIA_BRF(T1,1)]^X2[ARIA_BRF(T1,0)]; \
|
||||
T2=S1[ARIA_BRF(T2,3)]^S2[ARIA_BRF(T2,2)]^X1[ARIA_BRF(T2,1)]^X2[ARIA_BRF(T2,0)]; \
|
||||
T3=S1[ARIA_BRF(T3,3)]^S2[ARIA_BRF(T3,2)]^X1[ARIA_BRF(T3,1)]^X2[ARIA_BRF(T3,0)]; \
|
||||
}
|
||||
|
||||
// S-Box Layer 2 + M
|
||||
#define SBL2_M(T0,T1,T2,T3) { \
|
||||
T0=X1[ARIA_BRF(T0,3)]^X2[ARIA_BRF(T0,2)]^S1[ARIA_BRF(T0,1)]^S2[ARIA_BRF(T0,0)]; \
|
||||
T1=X1[ARIA_BRF(T1,3)]^X2[ARIA_BRF(T1,2)]^S1[ARIA_BRF(T1,1)]^S2[ARIA_BRF(T1,0)]; \
|
||||
T2=X1[ARIA_BRF(T2,3)]^X2[ARIA_BRF(T2,2)]^S1[ARIA_BRF(T2,1)]^S2[ARIA_BRF(T2,0)]; \
|
||||
T3=X1[ARIA_BRF(T3,3)]^X2[ARIA_BRF(T3,2)]^S1[ARIA_BRF(T3,1)]^S2[ARIA_BRF(T3,0)]; \
|
||||
}
|
||||
|
||||
#define ARIA_P(T0,T1,T2,T3) { \
|
||||
(T1) = (((T1)<< 8)&0xff00ff00) ^ (((T1)>> 8)&0x00ff00ff); \
|
||||
(T2) = rotrConstant<16>(T2); \
|
||||
(T3) = ByteReverse((T3)); \
|
||||
}
|
||||
|
||||
#define ARIA_M(X,Y) { \
|
||||
Y=(X)<<8 ^ (X)>>8 ^ (X)<<16 ^ (X)>>16 ^ (X)<<24 ^ (X)>>24; \
|
||||
}
|
||||
|
||||
#define ARIA_MM(T0,T1,T2,T3) { \
|
||||
(T1)^=(T2); (T2)^=(T3); (T0)^=(T1); \
|
||||
(T3)^=(T1); (T2)^=(T0); (T1)^=(T2); \
|
||||
}
|
||||
|
||||
#define ARIA_FO {SBL1_M(t[0],t[1],t[2],t[3]) ARIA_MM(t[0],t[1],t[2],t[3]) ARIA_P(t[0],t[1],t[2],t[3]) ARIA_MM(t[0],t[1],t[2],t[3])}
|
||||
#define ARIA_FE {SBL2_M(t[0],t[1],t[2],t[3]) ARIA_MM(t[0],t[1],t[2],t[3]) ARIA_P(t[2],t[3],t[0],t[1]) ARIA_MM(t[0],t[1],t[2],t[3])}
|
||||
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
extern void ARIA_UncheckedSetKey_Schedule_NEON(byte* rk, word32* ws, unsigned int keylen);
|
||||
extern void ARIA_ProcessAndXorBlock_NEON(const byte* xorBlock, byte* outblock, const byte *rk, word32 *t);
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_SSSE3_AVAILABLE)
|
||||
extern void ARIA_ProcessAndXorBlock_SSSE3(const byte* xorBlock, byte* outBlock, const byte *rk, word32 *t);
|
||||
#endif
|
||||
|
||||
// n-bit right shift of Y XORed to X
|
||||
template <unsigned int N>
|
||||
inline void ARIA_GSRK(const word32 X[4], const word32 Y[4], byte RK[16])
|
||||
{
|
||||
// MSVC is not generating a "rotate immediate". Constify to help it along.
|
||||
static const unsigned int Q = 4-(N/32);
|
||||
static const unsigned int R = N % 32;
|
||||
UINT32_CAST(RK)[0] = (X[0]) ^ ((Y[(Q )%4])>>R) ^ ((Y[(Q+3)%4])<<(32-R));
|
||||
UINT32_CAST(RK)[1] = (X[1]) ^ ((Y[(Q+1)%4])>>R) ^ ((Y[(Q )%4])<<(32-R));
|
||||
UINT32_CAST(RK)[2] = (X[2]) ^ ((Y[(Q+2)%4])>>R) ^ ((Y[(Q+1)%4])<<(32-R));
|
||||
UINT32_CAST(RK)[3] = (X[3]) ^ ((Y[(Q+3)%4])>>R) ^ ((Y[(Q+2)%4])<<(32-R));
|
||||
}
|
||||
|
||||
void ARIA::Base::UncheckedSetKey(const byte *key, unsigned int keylen, const NameValuePairs ¶ms)
|
||||
{
|
||||
CRYPTOPP_UNUSED(params);
|
||||
|
||||
m_rk.New(16*17); // round keys
|
||||
m_w.New(4*7); // w0, w1, w2, w3, t and u
|
||||
|
||||
byte *rk = m_rk.data();
|
||||
int Q, q, R, r;
|
||||
|
||||
switch (keylen)
|
||||
{
|
||||
case 16:
|
||||
R = r = m_rounds = 12;
|
||||
Q = q = 0;
|
||||
break;
|
||||
case 32:
|
||||
R = r = m_rounds = 16;
|
||||
Q = q = 2;
|
||||
break;
|
||||
case 24:
|
||||
R = r = m_rounds = 14;
|
||||
Q = q = 1;
|
||||
break;
|
||||
default:
|
||||
Q = q = R = r = m_rounds = 0;
|
||||
CRYPTOPP_ASSERT(0);
|
||||
}
|
||||
|
||||
// w0 has room for 32 bytes. w1-w3 each has room for 16 bytes. t and u are 16 byte temp areas.
|
||||
word32 *w0 = m_w.data(), *w1 = m_w.data()+8, *w2 = m_w.data()+12, *w3 = m_w.data()+16, *t = m_w.data()+20;
|
||||
|
||||
GetBlock<word32, BigEndian, false>block(key);
|
||||
block(w0[0])(w0[1])(w0[2])(w0[3]);
|
||||
|
||||
t[0]=w0[0]^KRK[q][0]; t[1]=w0[1]^KRK[q][1];
|
||||
t[2]=w0[2]^KRK[q][2]; t[3]=w0[3]^KRK[q][3];
|
||||
|
||||
ARIA_FO;
|
||||
|
||||
if (keylen == 32)
|
||||
{
|
||||
block(w1[0])(w1[1])(w1[2])(w1[3]);
|
||||
}
|
||||
else if (keylen == 24)
|
||||
{
|
||||
block(w1[0])(w1[1]); w1[2] = w1[3] = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
w1[0]=w1[1]=w1[2]=w1[3]=0;
|
||||
}
|
||||
|
||||
w1[0]^=t[0]; w1[1]^=t[1]; w1[2]^=t[2]; w1[3]^=t[3];
|
||||
::memcpy(t, w1, 16);
|
||||
|
||||
q = (q==2) ? 0 : (q+1);
|
||||
t[0]^=KRK[q][0]; t[1]^=KRK[q][1]; t[2]^=KRK[q][2]; t[3]^=KRK[q][3];
|
||||
|
||||
ARIA_FE;
|
||||
|
||||
t[0]^=w0[0]; t[1]^=w0[1]; t[2]^=w0[2]; t[3]^=w0[3];
|
||||
::memcpy(w2, t, 16);
|
||||
|
||||
q = (q==2) ? 0 : (q+1);
|
||||
t[0]^=KRK[q][0]; t[1]^=KRK[q][1]; t[2]^=KRK[q][2]; t[3]^=KRK[q][3];
|
||||
|
||||
ARIA_FO;
|
||||
|
||||
w3[0]=t[0]^w1[0]; w3[1]=t[1]^w1[1]; w3[2]=t[2]^w1[2]; w3[3]=t[3]^w1[3];
|
||||
|
||||
#if CRYPTOPP_ARM_NEON_AVAILABLE
|
||||
if (HasNEON())
|
||||
{
|
||||
ARIA_UncheckedSetKey_Schedule_NEON(rk, m_w, keylen);
|
||||
}
|
||||
else
|
||||
#endif // CRYPTOPP_ARM_NEON_AVAILABLE
|
||||
{
|
||||
ARIA_GSRK<19>(w0, w1, rk + 0);
|
||||
ARIA_GSRK<19>(w1, w2, rk + 16);
|
||||
ARIA_GSRK<19>(w2, w3, rk + 32);
|
||||
ARIA_GSRK<19>(w3, w0, rk + 48);
|
||||
ARIA_GSRK<31>(w0, w1, rk + 64);
|
||||
ARIA_GSRK<31>(w1, w2, rk + 80);
|
||||
ARIA_GSRK<31>(w2, w3, rk + 96);
|
||||
ARIA_GSRK<31>(w3, w0, rk + 112);
|
||||
ARIA_GSRK<67>(w0, w1, rk + 128);
|
||||
ARIA_GSRK<67>(w1, w2, rk + 144);
|
||||
ARIA_GSRK<67>(w2, w3, rk + 160);
|
||||
ARIA_GSRK<67>(w3, w0, rk + 176);
|
||||
ARIA_GSRK<97>(w0, w1, rk + 192);
|
||||
|
||||
if (keylen > 16)
|
||||
{
|
||||
ARIA_GSRK<97>(w1, w2, rk + 208);
|
||||
ARIA_GSRK<97>(w2, w3, rk + 224);
|
||||
|
||||
if (keylen > 24)
|
||||
{
|
||||
ARIA_GSRK< 97>(w3, w0, rk + 240);
|
||||
ARIA_GSRK<109>(w0, w1, rk + 256);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Decryption operation
|
||||
if (!IsForwardTransformation())
|
||||
{
|
||||
word32 *a, *z, *s;
|
||||
rk = m_rk.data();
|
||||
r = R; q = Q;
|
||||
|
||||
a=UINT32_CAST(rk); s=m_w.data()+24; z=a+r*4;
|
||||
::memcpy(t, a, 16); ::memcpy(a, z, 16); ::memcpy(z, t, 16);
|
||||
|
||||
a+=4; z-=4;
|
||||
for (; a<z; a+=4, z-=4)
|
||||
{
|
||||
ARIA_M(a[0],t[0]); ARIA_M(a[1],t[1]); ARIA_M(a[2],t[2]); ARIA_M(a[3],t[3]);
|
||||
ARIA_MM(t[0],t[1],t[2],t[3]); ARIA_P(t[0],t[1],t[2],t[3]); ARIA_MM(t[0],t[1],t[2],t[3]);
|
||||
::memcpy(s, t, 16);
|
||||
|
||||
ARIA_M(z[0],t[0]); ARIA_M(z[1],t[1]); ARIA_M(z[2],t[2]); ARIA_M(z[3],t[3]);
|
||||
ARIA_MM(t[0],t[1],t[2],t[3]); ARIA_P(t[0],t[1],t[2],t[3]); ARIA_MM(t[0],t[1],t[2],t[3]);
|
||||
::memcpy(a, t, 16); ::memcpy(z, s, 16);
|
||||
}
|
||||
|
||||
ARIA_M(a[0],t[0]); ARIA_M(a[1],t[1]); ARIA_M(a[2],t[2]); ARIA_M(a[3],t[3]);
|
||||
ARIA_MM(t[0],t[1],t[2],t[3]); ARIA_P(t[0],t[1],t[2],t[3]); ARIA_MM(t[0],t[1],t[2],t[3]);
|
||||
::memcpy(z, t, 16);
|
||||
}
|
||||
|
||||
// Silence warnings
|
||||
CRYPTOPP_UNUSED(Q); CRYPTOPP_UNUSED(R);
|
||||
CRYPTOPP_UNUSED(q); CRYPTOPP_UNUSED(r);
|
||||
}
|
||||
|
||||
void ARIA::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
const byte *rk = reinterpret_cast<const byte*>(m_rk.data());
|
||||
word32 *t = const_cast<word32*>(m_w.data()+20);
|
||||
|
||||
// Timing attack countermeasure. See comments in Rijndael for more details.
|
||||
// We used Yun's 32-bit implementation, so we use words rather than bytes.
|
||||
const int cacheLineSize = GetCacheLineSize();
|
||||
unsigned int i;
|
||||
volatile word32 _u = 0;
|
||||
word32 u = _u;
|
||||
|
||||
for (i=0; i<COUNTOF(S1); i+=cacheLineSize/(sizeof(S1[0])))
|
||||
u |= *(S1+i);
|
||||
t[0] |= u;
|
||||
|
||||
GetBlock<word32, BigEndian>block(inBlock);
|
||||
block(t[0])(t[1])(t[2])(t[3]);
|
||||
|
||||
if (m_rounds > 12) {
|
||||
ARIA_KXL; rk+= 16; ARIA_FO;
|
||||
ARIA_KXL; rk+= 16; ARIA_FE;
|
||||
}
|
||||
|
||||
if (m_rounds > 14) {
|
||||
ARIA_KXL; rk+= 16; ARIA_FO;
|
||||
ARIA_KXL; rk+= 16; ARIA_FE;
|
||||
}
|
||||
|
||||
ARIA_KXL; rk+= 16; ARIA_FO; ARIA_KXL; rk+= 16; ARIA_FE;
|
||||
ARIA_KXL; rk+= 16; ARIA_FO; ARIA_KXL; rk+= 16; ARIA_FE;
|
||||
ARIA_KXL; rk+= 16; ARIA_FO; ARIA_KXL; rk+= 16; ARIA_FE;
|
||||
ARIA_KXL; rk+= 16; ARIA_FO; ARIA_KXL; rk+= 16; ARIA_FE;
|
||||
ARIA_KXL; rk+= 16; ARIA_FO; ARIA_KXL; rk+= 16; ARIA_FE;
|
||||
ARIA_KXL; rk+= 16; ARIA_FO; ARIA_KXL; rk+= 16;
|
||||
|
||||
#if CRYPTOPP_ENABLE_ARIA_SSSE3_INTRINSICS
|
||||
if (HasSSSE3())
|
||||
{
|
||||
ARIA_ProcessAndXorBlock_SSSE3(xorBlock, outBlock, rk, t);
|
||||
return;
|
||||
}
|
||||
else
|
||||
#endif // CRYPTOPP_ENABLE_ARIA_SSSE3_INTRINSICS
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
if (HasNEON())
|
||||
{
|
||||
ARIA_ProcessAndXorBlock_NEON(xorBlock, outBlock, rk, t);
|
||||
return;
|
||||
}
|
||||
else
|
||||
#endif // CRYPTOPP_ARM_NEON_AVAILABLE
|
||||
#if (CRYPTOPP_LITTLE_ENDIAN)
|
||||
{
|
||||
outBlock[ 0] = (byte)(X1[ARIA_BRF(t[0],3)] ) ^ rk[ 3];
|
||||
outBlock[ 1] = (byte)(X2[ARIA_BRF(t[0],2)]>>8) ^ rk[ 2];
|
||||
outBlock[ 2] = (byte)(S1[ARIA_BRF(t[0],1)] ) ^ rk[ 1];
|
||||
outBlock[ 3] = (byte)(S2[ARIA_BRF(t[0],0)] ) ^ rk[ 0];
|
||||
outBlock[ 4] = (byte)(X1[ARIA_BRF(t[1],3)] ) ^ rk[ 7];
|
||||
outBlock[ 5] = (byte)(X2[ARIA_BRF(t[1],2)]>>8) ^ rk[ 6];
|
||||
outBlock[ 6] = (byte)(S1[ARIA_BRF(t[1],1)] ) ^ rk[ 5];
|
||||
outBlock[ 7] = (byte)(S2[ARIA_BRF(t[1],0)] ) ^ rk[ 4];
|
||||
outBlock[ 8] = (byte)(X1[ARIA_BRF(t[2],3)] ) ^ rk[11];
|
||||
outBlock[ 9] = (byte)(X2[ARIA_BRF(t[2],2)]>>8) ^ rk[10];
|
||||
outBlock[10] = (byte)(S1[ARIA_BRF(t[2],1)] ) ^ rk[ 9];
|
||||
outBlock[11] = (byte)(S2[ARIA_BRF(t[2],0)] ) ^ rk[ 8];
|
||||
outBlock[12] = (byte)(X1[ARIA_BRF(t[3],3)] ) ^ rk[15];
|
||||
outBlock[13] = (byte)(X2[ARIA_BRF(t[3],2)]>>8) ^ rk[14];
|
||||
outBlock[14] = (byte)(S1[ARIA_BRF(t[3],1)] ) ^ rk[13];
|
||||
outBlock[15] = (byte)(S2[ARIA_BRF(t[3],0)] ) ^ rk[12];
|
||||
}
|
||||
#else
|
||||
{
|
||||
outBlock[ 0] = (byte)(X1[ARIA_BRF(t[0],3)] ) ^ rk[ 0];
|
||||
outBlock[ 1] = (byte)(X2[ARIA_BRF(t[0],2)]>>8) ^ rk[ 1];
|
||||
outBlock[ 2] = (byte)(S1[ARIA_BRF(t[0],1)] ) ^ rk[ 2];
|
||||
outBlock[ 3] = (byte)(S2[ARIA_BRF(t[0],0)] ) ^ rk[ 3];
|
||||
outBlock[ 4] = (byte)(X1[ARIA_BRF(t[1],3)] ) ^ rk[ 4];
|
||||
outBlock[ 5] = (byte)(X2[ARIA_BRF(t[1],2)]>>8) ^ rk[ 5];
|
||||
outBlock[ 6] = (byte)(S1[ARIA_BRF(t[1],1)] ) ^ rk[ 6];
|
||||
outBlock[ 7] = (byte)(S2[ARIA_BRF(t[1],0)] ) ^ rk[ 7];
|
||||
outBlock[ 8] = (byte)(X1[ARIA_BRF(t[2],3)] ) ^ rk[ 8];
|
||||
outBlock[ 9] = (byte)(X2[ARIA_BRF(t[2],2)]>>8) ^ rk[ 9];
|
||||
outBlock[10] = (byte)(S1[ARIA_BRF(t[2],1)] ) ^ rk[10];
|
||||
outBlock[11] = (byte)(S2[ARIA_BRF(t[2],0)] ) ^ rk[11];
|
||||
outBlock[12] = (byte)(X1[ARIA_BRF(t[3],3)] ) ^ rk[12];
|
||||
outBlock[13] = (byte)(X2[ARIA_BRF(t[3],2)]>>8) ^ rk[13];
|
||||
outBlock[14] = (byte)(S1[ARIA_BRF(t[3],1)] ) ^ rk[14];
|
||||
outBlock[15] = (byte)(S2[ARIA_BRF(t[3],0)] ) ^ rk[15];
|
||||
}
|
||||
#endif // CRYPTOPP_LITTLE_ENDIAN
|
||||
|
||||
if (xorBlock != NULLPTR)
|
||||
for (unsigned int n=0; n<ARIA::BLOCKSIZE; ++n)
|
||||
outBlock[n] ^= xorBlock[n];
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
// aria.h - written and placed in the public domain by Jeffrey Walton
|
||||
|
||||
/// \file aria.h
|
||||
/// \brief Classes for the ARIA block cipher
|
||||
/// \details The Crypto++ ARIA implementation is based on the 32-bit implementation by Aaram Yun
|
||||
/// from the National Security Research Institute, KOREA. Aaram Yun's implementation is based on
|
||||
/// the 8-bit implementation by Jin Hong. The source files are available in ARIA.zip from the Korea
|
||||
/// Internet & Security Agency website.
|
||||
/// \sa <A HREF="http://tools.ietf.org/html/rfc5794">RFC 5794, A Description of the ARIA Encryption Algorithm</A>,
|
||||
/// <A HREF="http://seed.kisa.or.kr/iwt/ko/bbs/EgovReferenceList.do?bbsId=BBSMSTR_000000000002">Korea
|
||||
/// Internet & Security Agency homepage</A>
|
||||
|
||||
#ifndef CRYPTOPP_ARIA_H
|
||||
#define CRYPTOPP_ARIA_H
|
||||
|
||||
#include "config.h"
|
||||
#include "seckey.h"
|
||||
#include "secblock.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief ARIA block cipher information
|
||||
/// \since Crypto++ 6.0
|
||||
struct ARIA_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 32, 8>
|
||||
{
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "ARIA";}
|
||||
};
|
||||
|
||||
/// \brief ARIA block cipher
|
||||
/// \details The Crypto++ ARIA implementation is based on the 32-bit implementation by Aaram Yun
|
||||
/// from the National Security Research Institute, KOREA. Aaram Yun's implementation is based on
|
||||
/// the 8-bit implementation by Jin Hong. The source files are available in ARIA.zip from the Korea
|
||||
/// Internet & Security Agency website.
|
||||
/// \sa <A HREF="http://tools.ietf.org/html/rfc5794">RFC 5794, A Description of the ARIA Encryption Algorithm</A>,
|
||||
/// <A HREF="http://seed.kisa.or.kr/iwt/ko/bbs/EgovReferenceList.do?bbsId=BBSMSTR_000000000002">Korea
|
||||
/// Internet & Security Agency homepage</A>
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/ARIA">ARIA</a>
|
||||
/// \since Crypto++ 6.0
|
||||
class ARIA : public ARIA_Info, public BlockCipherDocumentation
|
||||
{
|
||||
public:
|
||||
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<ARIA_Info>
|
||||
{
|
||||
public:
|
||||
Base() : m_rounds(0) {}
|
||||
|
||||
protected:
|
||||
void UncheckedSetKey(const byte *key, unsigned int keylen, const NameValuePairs ¶ms);
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
|
||||
private:
|
||||
// Reference implementation allocates a table of 17 round keys.
|
||||
typedef SecBlock<byte, AllocatorWithCleanup<byte, true> > AlignedByteBlock;
|
||||
typedef SecBlock<word32, AllocatorWithCleanup<word32, true> > AlignedWordBlock;
|
||||
|
||||
AlignedByteBlock m_rk; // round keys
|
||||
AlignedWordBlock m_w; // w0, w1, w2, w3, t and u
|
||||
unsigned int m_rounds;
|
||||
};
|
||||
|
||||
public:
|
||||
typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
|
||||
typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
|
||||
};
|
||||
|
||||
typedef ARIA::Encryption ARIAEncryption;
|
||||
typedef ARIA::Decryption ARIADecryption;
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
// aria_simd.cpp - written and placed in the public domain by
|
||||
// Jeffrey Walton, Uri Blumenthal and Marcel Raad.
|
||||
//
|
||||
// This source file uses intrinsics to gain access to ARMv7a and
|
||||
// ARMv8a NEON instructions. A separate source file is needed
|
||||
// because additional CXXFLAGS are required to enable the
|
||||
// appropriate instructions sets in some build configurations.
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
#include "misc.h"
|
||||
|
||||
#if (CRYPTOPP_SSSE3_AVAILABLE)
|
||||
# include <tmmintrin.h>
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_ARM_NEON_HEADER)
|
||||
# include <arm_neon.h>
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_ARM_ACLE_HEADER)
|
||||
# include <stdint.h>
|
||||
# include <arm_acle.h>
|
||||
#endif
|
||||
|
||||
// Clang intrinsic casts, http://bugs.llvm.org/show_bug.cgi?id=20670
|
||||
#define M128_CAST(x) ((__m128i *)(void *)(x))
|
||||
#define CONST_M128_CAST(x) ((const __m128i *)(const void *)(x))
|
||||
|
||||
// Squash MS LNK4221 and libtool warnings
|
||||
extern const char ARIA_SIMD_FNAME[] = __FILE__;
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
NAMESPACE_BEGIN(ARIATab)
|
||||
|
||||
extern const word32 S1[256];
|
||||
extern const word32 S2[256];
|
||||
extern const word32 X1[256];
|
||||
extern const word32 X2[256];
|
||||
extern const word32 KRK[3][4];
|
||||
|
||||
NAMESPACE_END
|
||||
NAMESPACE_END
|
||||
|
||||
ANONYMOUS_NAMESPACE_BEGIN
|
||||
|
||||
using CryptoPP::byte;
|
||||
using CryptoPP::word32;
|
||||
|
||||
inline byte ARIA_BRF(const word32 x, const int y) {
|
||||
return static_cast<byte>(GETBYTE(x, y));
|
||||
}
|
||||
|
||||
ANONYMOUS_NAMESPACE_END
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
using CryptoPP::ARIATab::S1;
|
||||
using CryptoPP::ARIATab::S2;
|
||||
using CryptoPP::ARIATab::X1;
|
||||
using CryptoPP::ARIATab::X2;
|
||||
using CryptoPP::ARIATab::KRK;
|
||||
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
|
||||
template <unsigned int N>
|
||||
inline void ARIA_GSRK_NEON(const uint32x4_t X, const uint32x4_t Y, byte RK[16])
|
||||
{
|
||||
enum { Q1 = (4-(N/32)) % 4,
|
||||
Q2 = (3-(N/32)) % 4,
|
||||
R = N % 32
|
||||
};
|
||||
|
||||
vst1q_u8(RK, vreinterpretq_u8_u32(
|
||||
veorq_u32(X, veorq_u32(
|
||||
vshrq_n_u32(vextq_u32(Y, Y, Q1), R),
|
||||
vshlq_n_u32(vextq_u32(Y, Y, Q2), 32-R)))));
|
||||
}
|
||||
|
||||
void ARIA_UncheckedSetKey_Schedule_NEON(byte* rk, word32* ws, unsigned int keylen)
|
||||
{
|
||||
const uint32x4_t w0 = vld1q_u32(ws+ 0);
|
||||
const uint32x4_t w1 = vld1q_u32(ws+ 8);
|
||||
const uint32x4_t w2 = vld1q_u32(ws+12);
|
||||
const uint32x4_t w3 = vld1q_u32(ws+16);
|
||||
|
||||
ARIA_GSRK_NEON<19>(w0, w1, rk + 0);
|
||||
ARIA_GSRK_NEON<19>(w1, w2, rk + 16);
|
||||
ARIA_GSRK_NEON<19>(w2, w3, rk + 32);
|
||||
ARIA_GSRK_NEON<19>(w3, w0, rk + 48);
|
||||
ARIA_GSRK_NEON<31>(w0, w1, rk + 64);
|
||||
ARIA_GSRK_NEON<31>(w1, w2, rk + 80);
|
||||
ARIA_GSRK_NEON<31>(w2, w3, rk + 96);
|
||||
ARIA_GSRK_NEON<31>(w3, w0, rk + 112);
|
||||
ARIA_GSRK_NEON<67>(w0, w1, rk + 128);
|
||||
ARIA_GSRK_NEON<67>(w1, w2, rk + 144);
|
||||
ARIA_GSRK_NEON<67>(w2, w3, rk + 160);
|
||||
ARIA_GSRK_NEON<67>(w3, w0, rk + 176);
|
||||
ARIA_GSRK_NEON<97>(w0, w1, rk + 192);
|
||||
|
||||
if (keylen > 16)
|
||||
{
|
||||
ARIA_GSRK_NEON<97>(w1, w2, rk + 208);
|
||||
ARIA_GSRK_NEON<97>(w2, w3, rk + 224);
|
||||
|
||||
if (keylen > 24)
|
||||
{
|
||||
ARIA_GSRK_NEON< 97>(w3, w0, rk + 240);
|
||||
ARIA_GSRK_NEON<109>(w0, w1, rk + 256);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ARIA_ProcessAndXorBlock_NEON(const byte* xorBlock, byte* outBlock, const byte *rk, word32 *t)
|
||||
{
|
||||
outBlock[ 0] = (byte)(X1[ARIA_BRF(t[0],3)] );
|
||||
outBlock[ 1] = (byte)(X2[ARIA_BRF(t[0],2)]>>8);
|
||||
outBlock[ 2] = (byte)(S1[ARIA_BRF(t[0],1)] );
|
||||
outBlock[ 3] = (byte)(S2[ARIA_BRF(t[0],0)] );
|
||||
outBlock[ 4] = (byte)(X1[ARIA_BRF(t[1],3)] );
|
||||
outBlock[ 5] = (byte)(X2[ARIA_BRF(t[1],2)]>>8);
|
||||
outBlock[ 6] = (byte)(S1[ARIA_BRF(t[1],1)] );
|
||||
outBlock[ 7] = (byte)(S2[ARIA_BRF(t[1],0)] );
|
||||
outBlock[ 8] = (byte)(X1[ARIA_BRF(t[2],3)] );
|
||||
outBlock[ 9] = (byte)(X2[ARIA_BRF(t[2],2)]>>8);
|
||||
outBlock[10] = (byte)(S1[ARIA_BRF(t[2],1)] );
|
||||
outBlock[11] = (byte)(S2[ARIA_BRF(t[2],0)] );
|
||||
outBlock[12] = (byte)(X1[ARIA_BRF(t[3],3)] );
|
||||
outBlock[13] = (byte)(X2[ARIA_BRF(t[3],2)]>>8);
|
||||
outBlock[14] = (byte)(S1[ARIA_BRF(t[3],1)] );
|
||||
outBlock[15] = (byte)(S2[ARIA_BRF(t[3],0)] );
|
||||
|
||||
// 'outBlock' and 'xorBlock' may be unaligned.
|
||||
if (xorBlock != NULLPTR)
|
||||
{
|
||||
vst1q_u8(outBlock,
|
||||
veorq_u8(
|
||||
vld1q_u8(xorBlock),
|
||||
veorq_u8(
|
||||
vld1q_u8(outBlock),
|
||||
vrev32q_u8(vld1q_u8((rk))))));
|
||||
}
|
||||
else
|
||||
{
|
||||
vst1q_u8(outBlock,
|
||||
veorq_u8(
|
||||
vld1q_u8(outBlock),
|
||||
vrev32q_u8(vld1q_u8(rk))));
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CRYPTOPP_ARM_NEON_AVAILABLE
|
||||
|
||||
#if (CRYPTOPP_SSSE3_AVAILABLE)
|
||||
|
||||
void ARIA_ProcessAndXorBlock_SSSE3(const byte* xorBlock, byte* outBlock, const byte *rk, word32 *t)
|
||||
{
|
||||
const __m128i MASK = _mm_set_epi8(12,13,14,15, 8,9,10,11, 4,5,6,7, 0,1,2,3);
|
||||
|
||||
outBlock[ 0] = (byte)(X1[ARIA_BRF(t[0],3)] );
|
||||
outBlock[ 1] = (byte)(X2[ARIA_BRF(t[0],2)]>>8);
|
||||
outBlock[ 2] = (byte)(S1[ARIA_BRF(t[0],1)] );
|
||||
outBlock[ 3] = (byte)(S2[ARIA_BRF(t[0],0)] );
|
||||
outBlock[ 4] = (byte)(X1[ARIA_BRF(t[1],3)] );
|
||||
outBlock[ 5] = (byte)(X2[ARIA_BRF(t[1],2)]>>8);
|
||||
outBlock[ 6] = (byte)(S1[ARIA_BRF(t[1],1)] );
|
||||
outBlock[ 7] = (byte)(S2[ARIA_BRF(t[1],0)] );
|
||||
outBlock[ 8] = (byte)(X1[ARIA_BRF(t[2],3)] );
|
||||
outBlock[ 9] = (byte)(X2[ARIA_BRF(t[2],2)]>>8);
|
||||
outBlock[10] = (byte)(S1[ARIA_BRF(t[2],1)] );
|
||||
outBlock[11] = (byte)(S2[ARIA_BRF(t[2],0)] );
|
||||
outBlock[12] = (byte)(X1[ARIA_BRF(t[3],3)] );
|
||||
outBlock[13] = (byte)(X2[ARIA_BRF(t[3],2)]>>8);
|
||||
outBlock[14] = (byte)(S1[ARIA_BRF(t[3],1)] );
|
||||
outBlock[15] = (byte)(S2[ARIA_BRF(t[3],0)] );
|
||||
|
||||
// 'outBlock' and 'xorBlock' may be unaligned.
|
||||
if (xorBlock != NULLPTR)
|
||||
{
|
||||
_mm_storeu_si128(M128_CAST(outBlock),
|
||||
_mm_xor_si128(
|
||||
_mm_loadu_si128(CONST_M128_CAST(xorBlock)),
|
||||
_mm_xor_si128(
|
||||
_mm_loadu_si128(CONST_M128_CAST(outBlock)),
|
||||
_mm_shuffle_epi8(_mm_load_si128(CONST_M128_CAST(rk)), MASK)))
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
_mm_storeu_si128(M128_CAST(outBlock),
|
||||
_mm_xor_si128(_mm_loadu_si128(CONST_M128_CAST(outBlock)),
|
||||
_mm_shuffle_epi8(_mm_load_si128(CONST_M128_CAST(rk)), MASK)));
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CRYPTOPP_SSSE3_AVAILABLE
|
||||
|
||||
NAMESPACE_END
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
// ariatab.cpp - written and placed in the public domain by Jeffrey Walton
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
NAMESPACE_BEGIN(ARIATab)
|
||||
|
||||
CRYPTOPP_ALIGN_DATA(16)
|
||||
CRYPTOPP_TABLE
|
||||
const word32 S1[256]={
|
||||
0x00636363,0x007c7c7c,0x00777777,0x007b7b7b,0x00f2f2f2,0x006b6b6b,0x006f6f6f,0x00c5c5c5,
|
||||
0x00303030,0x00010101,0x00676767,0x002b2b2b,0x00fefefe,0x00d7d7d7,0x00ababab,0x00767676,
|
||||
0x00cacaca,0x00828282,0x00c9c9c9,0x007d7d7d,0x00fafafa,0x00595959,0x00474747,0x00f0f0f0,
|
||||
0x00adadad,0x00d4d4d4,0x00a2a2a2,0x00afafaf,0x009c9c9c,0x00a4a4a4,0x00727272,0x00c0c0c0,
|
||||
0x00b7b7b7,0x00fdfdfd,0x00939393,0x00262626,0x00363636,0x003f3f3f,0x00f7f7f7,0x00cccccc,
|
||||
0x00343434,0x00a5a5a5,0x00e5e5e5,0x00f1f1f1,0x00717171,0x00d8d8d8,0x00313131,0x00151515,
|
||||
0x00040404,0x00c7c7c7,0x00232323,0x00c3c3c3,0x00181818,0x00969696,0x00050505,0x009a9a9a,
|
||||
0x00070707,0x00121212,0x00808080,0x00e2e2e2,0x00ebebeb,0x00272727,0x00b2b2b2,0x00757575,
|
||||
0x00090909,0x00838383,0x002c2c2c,0x001a1a1a,0x001b1b1b,0x006e6e6e,0x005a5a5a,0x00a0a0a0,
|
||||
0x00525252,0x003b3b3b,0x00d6d6d6,0x00b3b3b3,0x00292929,0x00e3e3e3,0x002f2f2f,0x00848484,
|
||||
0x00535353,0x00d1d1d1,0x00000000,0x00ededed,0x00202020,0x00fcfcfc,0x00b1b1b1,0x005b5b5b,
|
||||
0x006a6a6a,0x00cbcbcb,0x00bebebe,0x00393939,0x004a4a4a,0x004c4c4c,0x00585858,0x00cfcfcf,
|
||||
0x00d0d0d0,0x00efefef,0x00aaaaaa,0x00fbfbfb,0x00434343,0x004d4d4d,0x00333333,0x00858585,
|
||||
0x00454545,0x00f9f9f9,0x00020202,0x007f7f7f,0x00505050,0x003c3c3c,0x009f9f9f,0x00a8a8a8,
|
||||
0x00515151,0x00a3a3a3,0x00404040,0x008f8f8f,0x00929292,0x009d9d9d,0x00383838,0x00f5f5f5,
|
||||
0x00bcbcbc,0x00b6b6b6,0x00dadada,0x00212121,0x00101010,0x00ffffff,0x00f3f3f3,0x00d2d2d2,
|
||||
0x00cdcdcd,0x000c0c0c,0x00131313,0x00ececec,0x005f5f5f,0x00979797,0x00444444,0x00171717,
|
||||
0x00c4c4c4,0x00a7a7a7,0x007e7e7e,0x003d3d3d,0x00646464,0x005d5d5d,0x00191919,0x00737373,
|
||||
0x00606060,0x00818181,0x004f4f4f,0x00dcdcdc,0x00222222,0x002a2a2a,0x00909090,0x00888888,
|
||||
0x00464646,0x00eeeeee,0x00b8b8b8,0x00141414,0x00dedede,0x005e5e5e,0x000b0b0b,0x00dbdbdb,
|
||||
0x00e0e0e0,0x00323232,0x003a3a3a,0x000a0a0a,0x00494949,0x00060606,0x00242424,0x005c5c5c,
|
||||
0x00c2c2c2,0x00d3d3d3,0x00acacac,0x00626262,0x00919191,0x00959595,0x00e4e4e4,0x00797979,
|
||||
0x00e7e7e7,0x00c8c8c8,0x00373737,0x006d6d6d,0x008d8d8d,0x00d5d5d5,0x004e4e4e,0x00a9a9a9,
|
||||
0x006c6c6c,0x00565656,0x00f4f4f4,0x00eaeaea,0x00656565,0x007a7a7a,0x00aeaeae,0x00080808,
|
||||
0x00bababa,0x00787878,0x00252525,0x002e2e2e,0x001c1c1c,0x00a6a6a6,0x00b4b4b4,0x00c6c6c6,
|
||||
0x00e8e8e8,0x00dddddd,0x00747474,0x001f1f1f,0x004b4b4b,0x00bdbdbd,0x008b8b8b,0x008a8a8a,
|
||||
0x00707070,0x003e3e3e,0x00b5b5b5,0x00666666,0x00484848,0x00030303,0x00f6f6f6,0x000e0e0e,
|
||||
0x00616161,0x00353535,0x00575757,0x00b9b9b9,0x00868686,0x00c1c1c1,0x001d1d1d,0x009e9e9e,
|
||||
0x00e1e1e1,0x00f8f8f8,0x00989898,0x00111111,0x00696969,0x00d9d9d9,0x008e8e8e,0x00949494,
|
||||
0x009b9b9b,0x001e1e1e,0x00878787,0x00e9e9e9,0x00cecece,0x00555555,0x00282828,0x00dfdfdf,
|
||||
0x008c8c8c,0x00a1a1a1,0x00898989,0x000d0d0d,0x00bfbfbf,0x00e6e6e6,0x00424242,0x00686868,
|
||||
0x00414141,0x00999999,0x002d2d2d,0x000f0f0f,0x00b0b0b0,0x00545454,0x00bbbbbb,0x00161616
|
||||
};
|
||||
|
||||
CRYPTOPP_ALIGN_DATA(16)
|
||||
CRYPTOPP_TABLE
|
||||
const word32 S2[256]={
|
||||
0xe200e2e2,0x4e004e4e,0x54005454,0xfc00fcfc,0x94009494,0xc200c2c2,0x4a004a4a,0xcc00cccc,
|
||||
0x62006262,0x0d000d0d,0x6a006a6a,0x46004646,0x3c003c3c,0x4d004d4d,0x8b008b8b,0xd100d1d1,
|
||||
0x5e005e5e,0xfa00fafa,0x64006464,0xcb00cbcb,0xb400b4b4,0x97009797,0xbe00bebe,0x2b002b2b,
|
||||
0xbc00bcbc,0x77007777,0x2e002e2e,0x03000303,0xd300d3d3,0x19001919,0x59005959,0xc100c1c1,
|
||||
0x1d001d1d,0x06000606,0x41004141,0x6b006b6b,0x55005555,0xf000f0f0,0x99009999,0x69006969,
|
||||
0xea00eaea,0x9c009c9c,0x18001818,0xae00aeae,0x63006363,0xdf00dfdf,0xe700e7e7,0xbb00bbbb,
|
||||
0x00000000,0x73007373,0x66006666,0xfb00fbfb,0x96009696,0x4c004c4c,0x85008585,0xe400e4e4,
|
||||
0x3a003a3a,0x09000909,0x45004545,0xaa00aaaa,0x0f000f0f,0xee00eeee,0x10001010,0xeb00ebeb,
|
||||
0x2d002d2d,0x7f007f7f,0xf400f4f4,0x29002929,0xac00acac,0xcf00cfcf,0xad00adad,0x91009191,
|
||||
0x8d008d8d,0x78007878,0xc800c8c8,0x95009595,0xf900f9f9,0x2f002f2f,0xce00cece,0xcd00cdcd,
|
||||
0x08000808,0x7a007a7a,0x88008888,0x38003838,0x5c005c5c,0x83008383,0x2a002a2a,0x28002828,
|
||||
0x47004747,0xdb00dbdb,0xb800b8b8,0xc700c7c7,0x93009393,0xa400a4a4,0x12001212,0x53005353,
|
||||
0xff00ffff,0x87008787,0x0e000e0e,0x31003131,0x36003636,0x21002121,0x58005858,0x48004848,
|
||||
0x01000101,0x8e008e8e,0x37003737,0x74007474,0x32003232,0xca00caca,0xe900e9e9,0xb100b1b1,
|
||||
0xb700b7b7,0xab00abab,0x0c000c0c,0xd700d7d7,0xc400c4c4,0x56005656,0x42004242,0x26002626,
|
||||
0x07000707,0x98009898,0x60006060,0xd900d9d9,0xb600b6b6,0xb900b9b9,0x11001111,0x40004040,
|
||||
0xec00ecec,0x20002020,0x8c008c8c,0xbd00bdbd,0xa000a0a0,0xc900c9c9,0x84008484,0x04000404,
|
||||
0x49004949,0x23002323,0xf100f1f1,0x4f004f4f,0x50005050,0x1f001f1f,0x13001313,0xdc00dcdc,
|
||||
0xd800d8d8,0xc000c0c0,0x9e009e9e,0x57005757,0xe300e3e3,0xc300c3c3,0x7b007b7b,0x65006565,
|
||||
0x3b003b3b,0x02000202,0x8f008f8f,0x3e003e3e,0xe800e8e8,0x25002525,0x92009292,0xe500e5e5,
|
||||
0x15001515,0xdd00dddd,0xfd00fdfd,0x17001717,0xa900a9a9,0xbf00bfbf,0xd400d4d4,0x9a009a9a,
|
||||
0x7e007e7e,0xc500c5c5,0x39003939,0x67006767,0xfe00fefe,0x76007676,0x9d009d9d,0x43004343,
|
||||
0xa700a7a7,0xe100e1e1,0xd000d0d0,0xf500f5f5,0x68006868,0xf200f2f2,0x1b001b1b,0x34003434,
|
||||
0x70007070,0x05000505,0xa300a3a3,0x8a008a8a,0xd500d5d5,0x79007979,0x86008686,0xa800a8a8,
|
||||
0x30003030,0xc600c6c6,0x51005151,0x4b004b4b,0x1e001e1e,0xa600a6a6,0x27002727,0xf600f6f6,
|
||||
0x35003535,0xd200d2d2,0x6e006e6e,0x24002424,0x16001616,0x82008282,0x5f005f5f,0xda00dada,
|
||||
0xe600e6e6,0x75007575,0xa200a2a2,0xef00efef,0x2c002c2c,0xb200b2b2,0x1c001c1c,0x9f009f9f,
|
||||
0x5d005d5d,0x6f006f6f,0x80008080,0x0a000a0a,0x72007272,0x44004444,0x9b009b9b,0x6c006c6c,
|
||||
0x90009090,0x0b000b0b,0x5b005b5b,0x33003333,0x7d007d7d,0x5a005a5a,0x52005252,0xf300f3f3,
|
||||
0x61006161,0xa100a1a1,0xf700f7f7,0xb000b0b0,0xd600d6d6,0x3f003f3f,0x7c007c7c,0x6d006d6d,
|
||||
0xed00eded,0x14001414,0xe000e0e0,0xa500a5a5,0x3d003d3d,0x22002222,0xb300b3b3,0xf800f8f8,
|
||||
0x89008989,0xde00dede,0x71007171,0x1a001a1a,0xaf00afaf,0xba00baba,0xb500b5b5,0x81008181
|
||||
};
|
||||
|
||||
CRYPTOPP_ALIGN_DATA(16)
|
||||
CRYPTOPP_TABLE
|
||||
const word32 X1[256]={
|
||||
0x52520052,0x09090009,0x6a6a006a,0xd5d500d5,0x30300030,0x36360036,0xa5a500a5,0x38380038,
|
||||
0xbfbf00bf,0x40400040,0xa3a300a3,0x9e9e009e,0x81810081,0xf3f300f3,0xd7d700d7,0xfbfb00fb,
|
||||
0x7c7c007c,0xe3e300e3,0x39390039,0x82820082,0x9b9b009b,0x2f2f002f,0xffff00ff,0x87870087,
|
||||
0x34340034,0x8e8e008e,0x43430043,0x44440044,0xc4c400c4,0xdede00de,0xe9e900e9,0xcbcb00cb,
|
||||
0x54540054,0x7b7b007b,0x94940094,0x32320032,0xa6a600a6,0xc2c200c2,0x23230023,0x3d3d003d,
|
||||
0xeeee00ee,0x4c4c004c,0x95950095,0x0b0b000b,0x42420042,0xfafa00fa,0xc3c300c3,0x4e4e004e,
|
||||
0x08080008,0x2e2e002e,0xa1a100a1,0x66660066,0x28280028,0xd9d900d9,0x24240024,0xb2b200b2,
|
||||
0x76760076,0x5b5b005b,0xa2a200a2,0x49490049,0x6d6d006d,0x8b8b008b,0xd1d100d1,0x25250025,
|
||||
0x72720072,0xf8f800f8,0xf6f600f6,0x64640064,0x86860086,0x68680068,0x98980098,0x16160016,
|
||||
0xd4d400d4,0xa4a400a4,0x5c5c005c,0xcccc00cc,0x5d5d005d,0x65650065,0xb6b600b6,0x92920092,
|
||||
0x6c6c006c,0x70700070,0x48480048,0x50500050,0xfdfd00fd,0xeded00ed,0xb9b900b9,0xdada00da,
|
||||
0x5e5e005e,0x15150015,0x46460046,0x57570057,0xa7a700a7,0x8d8d008d,0x9d9d009d,0x84840084,
|
||||
0x90900090,0xd8d800d8,0xabab00ab,0x00000000,0x8c8c008c,0xbcbc00bc,0xd3d300d3,0x0a0a000a,
|
||||
0xf7f700f7,0xe4e400e4,0x58580058,0x05050005,0xb8b800b8,0xb3b300b3,0x45450045,0x06060006,
|
||||
0xd0d000d0,0x2c2c002c,0x1e1e001e,0x8f8f008f,0xcaca00ca,0x3f3f003f,0x0f0f000f,0x02020002,
|
||||
0xc1c100c1,0xafaf00af,0xbdbd00bd,0x03030003,0x01010001,0x13130013,0x8a8a008a,0x6b6b006b,
|
||||
0x3a3a003a,0x91910091,0x11110011,0x41410041,0x4f4f004f,0x67670067,0xdcdc00dc,0xeaea00ea,
|
||||
0x97970097,0xf2f200f2,0xcfcf00cf,0xcece00ce,0xf0f000f0,0xb4b400b4,0xe6e600e6,0x73730073,
|
||||
0x96960096,0xacac00ac,0x74740074,0x22220022,0xe7e700e7,0xadad00ad,0x35350035,0x85850085,
|
||||
0xe2e200e2,0xf9f900f9,0x37370037,0xe8e800e8,0x1c1c001c,0x75750075,0xdfdf00df,0x6e6e006e,
|
||||
0x47470047,0xf1f100f1,0x1a1a001a,0x71710071,0x1d1d001d,0x29290029,0xc5c500c5,0x89890089,
|
||||
0x6f6f006f,0xb7b700b7,0x62620062,0x0e0e000e,0xaaaa00aa,0x18180018,0xbebe00be,0x1b1b001b,
|
||||
0xfcfc00fc,0x56560056,0x3e3e003e,0x4b4b004b,0xc6c600c6,0xd2d200d2,0x79790079,0x20200020,
|
||||
0x9a9a009a,0xdbdb00db,0xc0c000c0,0xfefe00fe,0x78780078,0xcdcd00cd,0x5a5a005a,0xf4f400f4,
|
||||
0x1f1f001f,0xdddd00dd,0xa8a800a8,0x33330033,0x88880088,0x07070007,0xc7c700c7,0x31310031,
|
||||
0xb1b100b1,0x12120012,0x10100010,0x59590059,0x27270027,0x80800080,0xecec00ec,0x5f5f005f,
|
||||
0x60600060,0x51510051,0x7f7f007f,0xa9a900a9,0x19190019,0xb5b500b5,0x4a4a004a,0x0d0d000d,
|
||||
0x2d2d002d,0xe5e500e5,0x7a7a007a,0x9f9f009f,0x93930093,0xc9c900c9,0x9c9c009c,0xefef00ef,
|
||||
0xa0a000a0,0xe0e000e0,0x3b3b003b,0x4d4d004d,0xaeae00ae,0x2a2a002a,0xf5f500f5,0xb0b000b0,
|
||||
0xc8c800c8,0xebeb00eb,0xbbbb00bb,0x3c3c003c,0x83830083,0x53530053,0x99990099,0x61610061,
|
||||
0x17170017,0x2b2b002b,0x04040004,0x7e7e007e,0xbaba00ba,0x77770077,0xd6d600d6,0x26260026,
|
||||
0xe1e100e1,0x69690069,0x14140014,0x63630063,0x55550055,0x21210021,0x0c0c000c,0x7d7d007d
|
||||
};
|
||||
|
||||
CRYPTOPP_ALIGN_DATA(16)
|
||||
CRYPTOPP_TABLE
|
||||
const word32 X2[256]={
|
||||
0x30303000,0x68686800,0x99999900,0x1b1b1b00,0x87878700,0xb9b9b900,0x21212100,0x78787800,
|
||||
0x50505000,0x39393900,0xdbdbdb00,0xe1e1e100,0x72727200,0x09090900,0x62626200,0x3c3c3c00,
|
||||
0x3e3e3e00,0x7e7e7e00,0x5e5e5e00,0x8e8e8e00,0xf1f1f100,0xa0a0a000,0xcccccc00,0xa3a3a300,
|
||||
0x2a2a2a00,0x1d1d1d00,0xfbfbfb00,0xb6b6b600,0xd6d6d600,0x20202000,0xc4c4c400,0x8d8d8d00,
|
||||
0x81818100,0x65656500,0xf5f5f500,0x89898900,0xcbcbcb00,0x9d9d9d00,0x77777700,0xc6c6c600,
|
||||
0x57575700,0x43434300,0x56565600,0x17171700,0xd4d4d400,0x40404000,0x1a1a1a00,0x4d4d4d00,
|
||||
0xc0c0c000,0x63636300,0x6c6c6c00,0xe3e3e300,0xb7b7b700,0xc8c8c800,0x64646400,0x6a6a6a00,
|
||||
0x53535300,0xaaaaaa00,0x38383800,0x98989800,0x0c0c0c00,0xf4f4f400,0x9b9b9b00,0xededed00,
|
||||
0x7f7f7f00,0x22222200,0x76767600,0xafafaf00,0xdddddd00,0x3a3a3a00,0x0b0b0b00,0x58585800,
|
||||
0x67676700,0x88888800,0x06060600,0xc3c3c300,0x35353500,0x0d0d0d00,0x01010100,0x8b8b8b00,
|
||||
0x8c8c8c00,0xc2c2c200,0xe6e6e600,0x5f5f5f00,0x02020200,0x24242400,0x75757500,0x93939300,
|
||||
0x66666600,0x1e1e1e00,0xe5e5e500,0xe2e2e200,0x54545400,0xd8d8d800,0x10101000,0xcecece00,
|
||||
0x7a7a7a00,0xe8e8e800,0x08080800,0x2c2c2c00,0x12121200,0x97979700,0x32323200,0xababab00,
|
||||
0xb4b4b400,0x27272700,0x0a0a0a00,0x23232300,0xdfdfdf00,0xefefef00,0xcacaca00,0xd9d9d900,
|
||||
0xb8b8b800,0xfafafa00,0xdcdcdc00,0x31313100,0x6b6b6b00,0xd1d1d100,0xadadad00,0x19191900,
|
||||
0x49494900,0xbdbdbd00,0x51515100,0x96969600,0xeeeeee00,0xe4e4e400,0xa8a8a800,0x41414100,
|
||||
0xdadada00,0xffffff00,0xcdcdcd00,0x55555500,0x86868600,0x36363600,0xbebebe00,0x61616100,
|
||||
0x52525200,0xf8f8f800,0xbbbbbb00,0x0e0e0e00,0x82828200,0x48484800,0x69696900,0x9a9a9a00,
|
||||
0xe0e0e000,0x47474700,0x9e9e9e00,0x5c5c5c00,0x04040400,0x4b4b4b00,0x34343400,0x15151500,
|
||||
0x79797900,0x26262600,0xa7a7a700,0xdedede00,0x29292900,0xaeaeae00,0x92929200,0xd7d7d700,
|
||||
0x84848400,0xe9e9e900,0xd2d2d200,0xbababa00,0x5d5d5d00,0xf3f3f300,0xc5c5c500,0xb0b0b000,
|
||||
0xbfbfbf00,0xa4a4a400,0x3b3b3b00,0x71717100,0x44444400,0x46464600,0x2b2b2b00,0xfcfcfc00,
|
||||
0xebebeb00,0x6f6f6f00,0xd5d5d500,0xf6f6f600,0x14141400,0xfefefe00,0x7c7c7c00,0x70707000,
|
||||
0x5a5a5a00,0x7d7d7d00,0xfdfdfd00,0x2f2f2f00,0x18181800,0x83838300,0x16161600,0xa5a5a500,
|
||||
0x91919100,0x1f1f1f00,0x05050500,0x95959500,0x74747400,0xa9a9a900,0xc1c1c100,0x5b5b5b00,
|
||||
0x4a4a4a00,0x85858500,0x6d6d6d00,0x13131300,0x07070700,0x4f4f4f00,0x4e4e4e00,0x45454500,
|
||||
0xb2b2b200,0x0f0f0f00,0xc9c9c900,0x1c1c1c00,0xa6a6a600,0xbcbcbc00,0xececec00,0x73737300,
|
||||
0x90909000,0x7b7b7b00,0xcfcfcf00,0x59595900,0x8f8f8f00,0xa1a1a100,0xf9f9f900,0x2d2d2d00,
|
||||
0xf2f2f200,0xb1b1b100,0x00000000,0x94949400,0x37373700,0x9f9f9f00,0xd0d0d000,0x2e2e2e00,
|
||||
0x9c9c9c00,0x6e6e6e00,0x28282800,0x3f3f3f00,0x80808000,0xf0f0f000,0x3d3d3d00,0xd3d3d300,
|
||||
0x25252500,0x8a8a8a00,0xb5b5b500,0xe7e7e700,0x42424200,0xb3b3b300,0xc7c7c700,0xeaeaea00,
|
||||
0xf7f7f700,0x4c4c4c00,0x11111100,0x33333300,0x03030300,0xa2a2a200,0xacacac00,0x60606000
|
||||
};
|
||||
|
||||
CRYPTOPP_ALIGN_DATA(16)
|
||||
CRYPTOPP_TABLE
|
||||
const word32 KRK[3][4] = {
|
||||
{0x517cc1b7, 0x27220a94, 0xfe13abe8, 0xfa9a6ee0},
|
||||
{0x6db14acc, 0x9e21c820, 0xff28b1d5, 0xef5de2b0},
|
||||
{0xdb92371d, 0x2126e970, 0x03249775, 0x04e8c90e}
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
NAMESPACE_END
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
// arm_simd.h - written and placed in public domain by Jeffrey Walton
|
||||
|
||||
/// \file arm_simd.h
|
||||
/// \brief Support functions for ARM and vector operations
|
||||
|
||||
#ifndef CRYPTOPP_ARM_SIMD_H
|
||||
#define CRYPTOPP_ARM_SIMD_H
|
||||
|
||||
#include "config.h"
|
||||
|
||||
#if (CRYPTOPP_ARM_NEON_HEADER)
|
||||
# include <arm_neon.h>
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_ARM_ACLE_HEADER)
|
||||
# include <stdint.h>
|
||||
# include <arm_acle.h>
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_ARM_PMULL_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
|
||||
/// \brief Polynomial multiplication
|
||||
/// \param a the first term
|
||||
/// \param b the second term
|
||||
/// \return vector product
|
||||
/// \details PMULL_00() performs polynomial multiplication and presents
|
||||
/// the result like Intel's <tt>c = _mm_clmulepi64_si128(a, b, 0x00)</tt>.
|
||||
/// The <tt>0x00</tt> indicates the low 64-bits of <tt>a</tt> and <tt>b</tt>
|
||||
/// are multiplied.
|
||||
/// \note An Intel XMM register is composed of 128-bits. The leftmost bit
|
||||
/// is MSB and numbered 127, while the the rightmost bit is LSB and
|
||||
/// numbered 0.
|
||||
/// \since Crypto++ 8.0
|
||||
inline uint64x2_t PMULL_00(const uint64x2_t a, const uint64x2_t b)
|
||||
{
|
||||
#if defined(_MSC_VER)
|
||||
const __n64 x = { vgetq_lane_u64(a, 0) };
|
||||
const __n64 y = { vgetq_lane_u64(b, 0) };
|
||||
return vmull_p64(x, y);
|
||||
#elif defined(__GNUC__)
|
||||
uint64x2_t r;
|
||||
__asm __volatile("pmull %0.1q, %1.1d, %2.1d \n\t"
|
||||
:"=w" (r) : "w" (a), "w" (b) );
|
||||
return r;
|
||||
#else
|
||||
return (uint64x2_t)(vmull_p64(
|
||||
vgetq_lane_u64(vreinterpretq_u64_u8(a),0),
|
||||
vgetq_lane_u64(vreinterpretq_u64_u8(b),0)));
|
||||
#endif
|
||||
}
|
||||
|
||||
/// \brief Polynomial multiplication
|
||||
/// \param a the first term
|
||||
/// \param b the second term
|
||||
/// \return vector product
|
||||
/// \details PMULL_01 performs() polynomial multiplication and presents
|
||||
/// the result like Intel's <tt>c = _mm_clmulepi64_si128(a, b, 0x01)</tt>.
|
||||
/// The <tt>0x01</tt> indicates the low 64-bits of <tt>a</tt> and high
|
||||
/// 64-bits of <tt>b</tt> are multiplied.
|
||||
/// \note An Intel XMM register is composed of 128-bits. The leftmost bit
|
||||
/// is MSB and numbered 127, while the the rightmost bit is LSB and
|
||||
/// numbered 0.
|
||||
/// \since Crypto++ 8.0
|
||||
inline uint64x2_t PMULL_01(const uint64x2_t a, const uint64x2_t b)
|
||||
{
|
||||
#if defined(_MSC_VER)
|
||||
const __n64 x = { vgetq_lane_u64(a, 0) };
|
||||
const __n64 y = { vgetq_lane_u64(b, 1) };
|
||||
return vmull_p64(x, y);
|
||||
#elif defined(__GNUC__)
|
||||
uint64x2_t r;
|
||||
__asm __volatile("pmull %0.1q, %1.1d, %2.1d \n\t"
|
||||
:"=w" (r) : "w" (a), "w" (vget_high_u64(b)) );
|
||||
return r;
|
||||
#else
|
||||
return (uint64x2_t)(vmull_p64(
|
||||
vgetq_lane_u64(vreinterpretq_u64_u8(a),0),
|
||||
vgetq_lane_u64(vreinterpretq_u64_u8(b),1)));
|
||||
#endif
|
||||
}
|
||||
|
||||
/// \brief Polynomial multiplication
|
||||
/// \param a the first term
|
||||
/// \param b the second term
|
||||
/// \return vector product
|
||||
/// \details PMULL_10() performs polynomial multiplication and presents
|
||||
/// the result like Intel's <tt>c = _mm_clmulepi64_si128(a, b, 0x10)</tt>.
|
||||
/// The <tt>0x10</tt> indicates the high 64-bits of <tt>a</tt> and low
|
||||
/// 64-bits of <tt>b</tt> are multiplied.
|
||||
/// \note An Intel XMM register is composed of 128-bits. The leftmost bit
|
||||
/// is MSB and numbered 127, while the the rightmost bit is LSB and
|
||||
/// numbered 0.
|
||||
/// \since Crypto++ 8.0
|
||||
inline uint64x2_t PMULL_10(const uint64x2_t a, const uint64x2_t b)
|
||||
{
|
||||
#if defined(_MSC_VER)
|
||||
const __n64 x = { vgetq_lane_u64(a, 1) };
|
||||
const __n64 y = { vgetq_lane_u64(b, 0) };
|
||||
return vmull_p64(x, y);
|
||||
#elif defined(__GNUC__)
|
||||
uint64x2_t r;
|
||||
__asm __volatile("pmull %0.1q, %1.1d, %2.1d \n\t"
|
||||
:"=w" (r) : "w" (vget_high_u64(a)), "w" (b) );
|
||||
return r;
|
||||
#else
|
||||
return (uint64x2_t)(vmull_p64(
|
||||
vgetq_lane_u64(vreinterpretq_u64_u8(a),1),
|
||||
vgetq_lane_u64(vreinterpretq_u64_u8(b),0)));
|
||||
#endif
|
||||
}
|
||||
|
||||
/// \brief Polynomial multiplication
|
||||
/// \param a the first term
|
||||
/// \param b the second term
|
||||
/// \return vector product
|
||||
/// \details PMULL_11() performs polynomial multiplication and presents
|
||||
/// the result like Intel's <tt>c = _mm_clmulepi64_si128(a, b, 0x11)</tt>.
|
||||
/// The <tt>0x11</tt> indicates the high 64-bits of <tt>a</tt> and <tt>b</tt>
|
||||
/// are multiplied.
|
||||
/// \note An Intel XMM register is composed of 128-bits. The leftmost bit
|
||||
/// is MSB and numbered 127, while the the rightmost bit is LSB and
|
||||
/// numbered 0.
|
||||
/// \since Crypto++ 8.0
|
||||
inline uint64x2_t PMULL_11(const uint64x2_t a, const uint64x2_t b)
|
||||
{
|
||||
#if defined(_MSC_VER)
|
||||
const __n64 x = { vgetq_lane_u64(a, 1) };
|
||||
const __n64 y = { vgetq_lane_u64(b, 1) };
|
||||
return vmull_p64(x, y);
|
||||
#elif defined(__GNUC__)
|
||||
uint64x2_t r;
|
||||
__asm __volatile("pmull2 %0.1q, %1.2d, %2.2d \n\t"
|
||||
:"=w" (r) : "w" (a), "w" (b) );
|
||||
return r;
|
||||
#else
|
||||
return (uint64x2_t)(vmull_p64(
|
||||
vgetq_lane_u64(vreinterpretq_u64_u8(a),1),
|
||||
vgetq_lane_u64(vreinterpretq_u64_u8(b),1)));
|
||||
#endif
|
||||
}
|
||||
|
||||
/// \brief Vector extraction
|
||||
/// \param a the first term
|
||||
/// \param b the second term
|
||||
/// \param c the byte count
|
||||
/// \return vector
|
||||
/// \details VEXT_U8() extracts the first <tt>c</tt> bytes of vector
|
||||
/// <tt>a</tt> and the remaining bytes in <tt>b</tt>.
|
||||
/// \since Crypto++ 8.0
|
||||
inline uint64x2_t VEXT_U8(uint64x2_t a, uint64x2_t b, unsigned int c)
|
||||
{
|
||||
#if defined(_MSC_VER)
|
||||
return (uint64x2_t)vextq_u8(
|
||||
vreinterpretq_u8_u64(a), vreinterpretq_u8_u64(b), c);
|
||||
#else
|
||||
uint64x2_t r;
|
||||
__asm __volatile("ext %0.16b, %1.16b, %2.16b, %3 \n\t"
|
||||
:"=w" (r) : "w" (a), "w" (b), "I" (c) );
|
||||
return r;
|
||||
#endif
|
||||
}
|
||||
|
||||
/// \brief Vector extraction
|
||||
/// \tparam C the byte count
|
||||
/// \param a the first term
|
||||
/// \param b the second term
|
||||
/// \return vector
|
||||
/// \details VEXT_U8() extracts the first <tt>C</tt> bytes of vector
|
||||
/// <tt>a</tt> and the remaining bytes in <tt>b</tt>.
|
||||
/// \since Crypto++ 8.0
|
||||
template <unsigned int C>
|
||||
inline uint64x2_t VEXT_U8(uint64x2_t a, uint64x2_t b)
|
||||
{
|
||||
// https://github.com/weidai11/cryptopp/issues/366
|
||||
#if defined(_MSC_VER)
|
||||
return (uint64x2_t)vextq_u8(
|
||||
vreinterpretq_u8_u64(a), vreinterpretq_u8_u64(b), C);
|
||||
#else
|
||||
uint64x2_t r;
|
||||
__asm __volatile("ext %0.16b, %1.16b, %2.16b, %3 \n\t"
|
||||
:"=w" (r) : "w" (a), "w" (b), "I" (C) );
|
||||
return r;
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif // CRYPTOPP_ARM_PMULL_AVAILABLE
|
||||
|
||||
#endif // CRYPTOPP_ARM_SIMD_H
|
||||
+717
@@ -0,0 +1,717 @@
|
||||
// asn.cpp - originally written and placed in the public domain by Wei Dai
|
||||
// CryptoPP::Test namespace added by JW in February 2017
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "asn.h"
|
||||
#include "misc.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <time.h>
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
size_t DERLengthEncode(BufferedTransformation &bt, lword length)
|
||||
{
|
||||
size_t i=0;
|
||||
if (length <= 0x7f)
|
||||
{
|
||||
bt.Put(byte(length));
|
||||
i++;
|
||||
}
|
||||
else
|
||||
{
|
||||
bt.Put(byte(BytePrecision(length) | 0x80));
|
||||
i++;
|
||||
for (int j=BytePrecision(length); j; --j)
|
||||
{
|
||||
bt.Put(byte(length >> (j-1)*8));
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
bool BERLengthDecode(BufferedTransformation &bt, lword &length, bool &definiteLength)
|
||||
{
|
||||
byte b;
|
||||
|
||||
if (!bt.Get(b))
|
||||
return false;
|
||||
|
||||
if (!(b & 0x80))
|
||||
{
|
||||
definiteLength = true;
|
||||
length = b;
|
||||
}
|
||||
else
|
||||
{
|
||||
unsigned int lengthBytes = b & 0x7f;
|
||||
|
||||
if (lengthBytes == 0)
|
||||
{
|
||||
definiteLength = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
definiteLength = true;
|
||||
length = 0;
|
||||
while (lengthBytes--)
|
||||
{
|
||||
if (length >> (8*(sizeof(length)-1)))
|
||||
BERDecodeError(); // length about to overflow
|
||||
|
||||
if (!bt.Get(b))
|
||||
return false;
|
||||
|
||||
length = (length << 8) | b;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BERLengthDecode(BufferedTransformation &bt, size_t &length)
|
||||
{
|
||||
lword lw = 0;
|
||||
bool definiteLength = false;
|
||||
if (!BERLengthDecode(bt, lw, definiteLength))
|
||||
BERDecodeError();
|
||||
if (!SafeConvert(lw, length))
|
||||
BERDecodeError();
|
||||
return definiteLength;
|
||||
}
|
||||
|
||||
void DEREncodeNull(BufferedTransformation &out)
|
||||
{
|
||||
out.Put(TAG_NULL);
|
||||
out.Put(0);
|
||||
}
|
||||
|
||||
void BERDecodeNull(BufferedTransformation &in)
|
||||
{
|
||||
byte b;
|
||||
if (!in.Get(b) || b != TAG_NULL)
|
||||
BERDecodeError();
|
||||
size_t length;
|
||||
if (!BERLengthDecode(in, length) || length != 0)
|
||||
BERDecodeError();
|
||||
}
|
||||
|
||||
/// ASN Strings
|
||||
size_t DEREncodeOctetString(BufferedTransformation &bt, const byte *str, size_t strLen)
|
||||
{
|
||||
bt.Put(OCTET_STRING);
|
||||
size_t lengthBytes = DERLengthEncode(bt, strLen);
|
||||
bt.Put(str, strLen);
|
||||
return 1+lengthBytes+strLen;
|
||||
}
|
||||
|
||||
size_t DEREncodeOctetString(BufferedTransformation &bt, const SecByteBlock &str)
|
||||
{
|
||||
return DEREncodeOctetString(bt, ConstBytePtr(str), BytePtrSize(str));
|
||||
}
|
||||
|
||||
size_t BERDecodeOctetString(BufferedTransformation &bt, SecByteBlock &str)
|
||||
{
|
||||
byte b;
|
||||
if (!bt.Get(b) || b != OCTET_STRING)
|
||||
BERDecodeError();
|
||||
|
||||
size_t bc;
|
||||
if (!BERLengthDecode(bt, bc))
|
||||
BERDecodeError();
|
||||
if (bc > bt.MaxRetrievable()) // Issue 346
|
||||
BERDecodeError();
|
||||
|
||||
str.New(bc);
|
||||
if (bc != bt.Get(BytePtr(str), bc))
|
||||
BERDecodeError();
|
||||
return bc;
|
||||
}
|
||||
|
||||
size_t BERDecodeOctetString(BufferedTransformation &bt, BufferedTransformation &str)
|
||||
{
|
||||
byte b;
|
||||
if (!bt.Get(b) || b != OCTET_STRING)
|
||||
BERDecodeError();
|
||||
|
||||
size_t bc;
|
||||
if (!BERLengthDecode(bt, bc))
|
||||
BERDecodeError();
|
||||
if (bc > bt.MaxRetrievable()) // Issue 346
|
||||
BERDecodeError();
|
||||
|
||||
bt.TransferTo(str, bc);
|
||||
return bc;
|
||||
}
|
||||
|
||||
size_t DEREncodeTextString(BufferedTransformation &bt, const byte* str, size_t strLen, byte asnTag)
|
||||
{
|
||||
bt.Put(asnTag);
|
||||
size_t lengthBytes = DERLengthEncode(bt, strLen);
|
||||
bt.Put(str, strLen);
|
||||
return 1+lengthBytes+strLen;
|
||||
}
|
||||
|
||||
size_t DEREncodeTextString(BufferedTransformation &bt, const SecByteBlock &str, byte asnTag)
|
||||
{
|
||||
return DEREncodeTextString(bt, ConstBytePtr(str), BytePtrSize(str), asnTag);
|
||||
}
|
||||
|
||||
size_t DEREncodeTextString(BufferedTransformation &bt, const std::string &str, byte asnTag)
|
||||
{
|
||||
return DEREncodeTextString(bt, ConstBytePtr(str), BytePtrSize(str), asnTag);
|
||||
}
|
||||
|
||||
size_t BERDecodeTextString(BufferedTransformation &bt, SecByteBlock &str, byte asnTag)
|
||||
{
|
||||
byte b;
|
||||
if (!bt.Get(b) || b != asnTag)
|
||||
BERDecodeError();
|
||||
|
||||
size_t bc;
|
||||
if (!BERLengthDecode(bt, bc))
|
||||
BERDecodeError();
|
||||
if (bc > bt.MaxRetrievable()) // Issue 346
|
||||
BERDecodeError();
|
||||
|
||||
str.resize(bc);
|
||||
if (bc != bt.Get(BytePtr(str), BytePtrSize(str)))
|
||||
BERDecodeError();
|
||||
|
||||
return bc;
|
||||
}
|
||||
|
||||
size_t BERDecodeTextString(BufferedTransformation &bt, std::string &str, byte asnTag)
|
||||
{
|
||||
byte b;
|
||||
if (!bt.Get(b) || b != asnTag)
|
||||
BERDecodeError();
|
||||
|
||||
size_t bc;
|
||||
if (!BERLengthDecode(bt, bc))
|
||||
BERDecodeError();
|
||||
if (bc > bt.MaxRetrievable()) // Issue 346
|
||||
BERDecodeError();
|
||||
|
||||
str.resize(bc);
|
||||
if (bc != bt.Get(BytePtr(str), BytePtrSize(str)))
|
||||
BERDecodeError();
|
||||
|
||||
return bc;
|
||||
}
|
||||
|
||||
size_t DEREncodeDate(BufferedTransformation &bt, const SecByteBlock &str, byte asnTag)
|
||||
{
|
||||
bt.Put(asnTag);
|
||||
size_t lengthBytes = DERLengthEncode(bt, str.size());
|
||||
bt.Put(ConstBytePtr(str), BytePtrSize(str));
|
||||
return 1+lengthBytes+str.size();
|
||||
}
|
||||
|
||||
size_t BERDecodeDate(BufferedTransformation &bt, SecByteBlock &str, byte asnTag)
|
||||
{
|
||||
byte b;
|
||||
if (!bt.Get(b) || b != asnTag)
|
||||
BERDecodeError();
|
||||
|
||||
size_t bc;
|
||||
if (!BERLengthDecode(bt, bc))
|
||||
BERDecodeError();
|
||||
if (bc > bt.MaxRetrievable()) // Issue 346
|
||||
BERDecodeError();
|
||||
|
||||
str.resize(bc);
|
||||
if (bc != bt.Get(BytePtr(str), BytePtrSize(str)))
|
||||
BERDecodeError();
|
||||
|
||||
return bc;
|
||||
}
|
||||
|
||||
size_t DEREncodeBitString(BufferedTransformation &bt, const byte *str, size_t strLen, unsigned int unusedBits)
|
||||
{
|
||||
bt.Put(BIT_STRING);
|
||||
size_t lengthBytes = DERLengthEncode(bt, strLen+1);
|
||||
bt.Put((byte)unusedBits);
|
||||
bt.Put(str, strLen);
|
||||
return 2+lengthBytes+strLen;
|
||||
}
|
||||
|
||||
size_t BERDecodeBitString(BufferedTransformation &bt, SecByteBlock &str, unsigned int &unusedBits)
|
||||
{
|
||||
byte b;
|
||||
if (!bt.Get(b) || b != BIT_STRING)
|
||||
BERDecodeError();
|
||||
|
||||
size_t bc;
|
||||
if (!BERLengthDecode(bt, bc))
|
||||
BERDecodeError();
|
||||
if (bc == 0)
|
||||
BERDecodeError();
|
||||
if (bc > bt.MaxRetrievable()) // Issue 346
|
||||
BERDecodeError();
|
||||
|
||||
// X.690, 8.6.2.2: "The number [of unused bits] shall be in the range zero to seven"
|
||||
byte unused;
|
||||
if (!bt.Get(unused) || unused > 7)
|
||||
BERDecodeError();
|
||||
unusedBits = unused;
|
||||
str.resize(bc-1);
|
||||
if ((bc-1) != bt.Get(BytePtr(str), bc-1))
|
||||
BERDecodeError();
|
||||
return bc-1;
|
||||
}
|
||||
|
||||
void DERReencode(BufferedTransformation &source, BufferedTransformation &dest)
|
||||
{
|
||||
byte tag;
|
||||
source.Peek(tag);
|
||||
BERGeneralDecoder decoder(source, tag);
|
||||
DERGeneralEncoder encoder(dest, tag);
|
||||
if (decoder.IsDefiniteLength())
|
||||
decoder.TransferTo(encoder, decoder.RemainingLength());
|
||||
else
|
||||
{
|
||||
while (!decoder.EndReached())
|
||||
DERReencode(decoder, encoder);
|
||||
}
|
||||
decoder.MessageEnd();
|
||||
encoder.MessageEnd();
|
||||
}
|
||||
|
||||
size_t BERDecodePeekLength(const BufferedTransformation &bt)
|
||||
{
|
||||
lword count = (std::min)(bt.MaxRetrievable(), static_cast<lword>(16));
|
||||
if (count == 0) return 0;
|
||||
|
||||
ByteQueue tagAndLength;
|
||||
bt.CopyTo(tagAndLength, count);
|
||||
|
||||
// Skip tag
|
||||
tagAndLength.Skip(1);
|
||||
|
||||
// BERLengthDecode fails for indefinite length.
|
||||
size_t length;
|
||||
if (!BERLengthDecode(tagAndLength, length))
|
||||
return 0;
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
void OID::EncodeValue(BufferedTransformation &bt, word32 v)
|
||||
{
|
||||
for (unsigned int i=RoundUpToMultipleOf(STDMAX(7U,BitPrecision(v)), 7U)-7; i != 0; i-=7)
|
||||
bt.Put((byte)(0x80 | ((v >> i) & 0x7f)));
|
||||
bt.Put((byte)(v & 0x7f));
|
||||
}
|
||||
|
||||
size_t OID::DecodeValue(BufferedTransformation &bt, word32 &v)
|
||||
{
|
||||
byte b;
|
||||
size_t i=0;
|
||||
v = 0;
|
||||
while (true)
|
||||
{
|
||||
if (!bt.Get(b))
|
||||
BERDecodeError();
|
||||
i++;
|
||||
if (v >> (8*sizeof(v)-7)) // v about to overflow
|
||||
BERDecodeError();
|
||||
v <<= 7;
|
||||
v += b & 0x7f;
|
||||
if (!(b & 0x80))
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
void OID::DEREncode(BufferedTransformation &bt) const
|
||||
{
|
||||
CRYPTOPP_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++)
|
||||
EncodeValue(temp, m_values[i]);
|
||||
bt.Put(OBJECT_IDENTIFIER);
|
||||
DERLengthEncode(bt, temp.CurrentSize());
|
||||
temp.TransferTo(bt);
|
||||
}
|
||||
|
||||
void OID::BERDecode(BufferedTransformation &bt)
|
||||
{
|
||||
byte b;
|
||||
if (!bt.Get(b) || b != OBJECT_IDENTIFIER)
|
||||
BERDecodeError();
|
||||
|
||||
size_t length;
|
||||
if (!BERLengthDecode(bt, length) || length < 1)
|
||||
BERDecodeError();
|
||||
|
||||
if (!bt.Get(b))
|
||||
BERDecodeError();
|
||||
|
||||
length--;
|
||||
m_values.resize(2);
|
||||
m_values[0] = b / 40;
|
||||
m_values[1] = b % 40;
|
||||
|
||||
while (length > 0)
|
||||
{
|
||||
word32 v;
|
||||
size_t valueLen = DecodeValue(bt, v);
|
||||
if (valueLen > length)
|
||||
BERDecodeError();
|
||||
m_values.push_back(v);
|
||||
length -= valueLen;
|
||||
}
|
||||
}
|
||||
|
||||
void OID::BERDecodeAndCheck(BufferedTransformation &bt) const
|
||||
{
|
||||
OID oid(bt);
|
||||
if (*this != oid)
|
||||
BERDecodeError();
|
||||
}
|
||||
|
||||
std::ostream& OID::Print(std::ostream& out) const
|
||||
{
|
||||
std::ostringstream oss;
|
||||
for (size_t i = 0; i < m_values.size(); ++i)
|
||||
{
|
||||
oss << m_values[i];
|
||||
if (i+1 < m_values.size())
|
||||
oss << ".";
|
||||
}
|
||||
return out << oss.str();
|
||||
}
|
||||
|
||||
inline BufferedTransformation & EncodedObjectFilter::CurrentTarget()
|
||||
{
|
||||
if (m_flags & PUT_OBJECTS)
|
||||
return *AttachedTransformation();
|
||||
else
|
||||
return TheBitBucket();
|
||||
}
|
||||
|
||||
void EncodedObjectFilter::Put(const byte *inString, size_t length)
|
||||
{
|
||||
if (m_nCurrentObject == m_nObjects)
|
||||
{
|
||||
AttachedTransformation()->Put(inString, length);
|
||||
return;
|
||||
}
|
||||
|
||||
LazyPutter lazyPutter(m_queue, inString, length);
|
||||
|
||||
while (m_queue.AnyRetrievable())
|
||||
{
|
||||
switch (m_state)
|
||||
{
|
||||
case IDENTIFIER:
|
||||
if (!m_queue.Get(m_id))
|
||||
return;
|
||||
m_queue.TransferTo(CurrentTarget(), 1);
|
||||
m_state = LENGTH;
|
||||
// fall through
|
||||
case LENGTH:
|
||||
{
|
||||
byte b;
|
||||
if (m_level > 0 && m_id == 0 && m_queue.Peek(b) && b == 0)
|
||||
{
|
||||
m_queue.TransferTo(CurrentTarget(), 1);
|
||||
m_level--;
|
||||
m_state = IDENTIFIER;
|
||||
break;
|
||||
}
|
||||
ByteQueue::Walker walker(m_queue);
|
||||
bool definiteLength = false;
|
||||
if (!BERLengthDecode(walker, m_lengthRemaining, definiteLength))
|
||||
return;
|
||||
m_queue.TransferTo(CurrentTarget(), walker.GetCurrentPosition());
|
||||
if (!((m_id & CONSTRUCTED) || definiteLength))
|
||||
BERDecodeError();
|
||||
if (!definiteLength)
|
||||
{
|
||||
if (!(m_id & CONSTRUCTED))
|
||||
BERDecodeError();
|
||||
m_level++;
|
||||
m_state = IDENTIFIER;
|
||||
break;
|
||||
}
|
||||
m_state = BODY;
|
||||
}
|
||||
// fall through
|
||||
case BODY:
|
||||
m_lengthRemaining -= m_queue.TransferTo(CurrentTarget(), m_lengthRemaining);
|
||||
|
||||
if (m_lengthRemaining == 0)
|
||||
m_state = IDENTIFIER;
|
||||
// fall through
|
||||
case TAIL:
|
||||
case ALL_DONE:
|
||||
default: ;
|
||||
}
|
||||
|
||||
if (m_state == IDENTIFIER && m_level == 0)
|
||||
{
|
||||
// just finished processing a level 0 object
|
||||
++m_nCurrentObject;
|
||||
|
||||
if (m_flags & PUT_MESSANGE_END_AFTER_EACH_OBJECT)
|
||||
AttachedTransformation()->MessageEnd();
|
||||
|
||||
if (m_nCurrentObject == m_nObjects)
|
||||
{
|
||||
if (m_flags & PUT_MESSANGE_END_AFTER_ALL_OBJECTS)
|
||||
AttachedTransformation()->MessageEnd();
|
||||
|
||||
if (m_flags & PUT_MESSANGE_SERIES_END_AFTER_ALL_OBJECTS)
|
||||
AttachedTransformation()->MessageSeriesEnd();
|
||||
|
||||
m_queue.TransferAllTo(*AttachedTransformation());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BERGeneralDecoder::BERGeneralDecoder(BufferedTransformation &inQueue)
|
||||
: m_inQueue(inQueue), m_length(0), m_finished(false)
|
||||
{
|
||||
Init(DefaultTag);
|
||||
}
|
||||
|
||||
BERGeneralDecoder::BERGeneralDecoder(BufferedTransformation &inQueue, byte asnTag)
|
||||
: m_inQueue(inQueue), m_length(0), m_finished(false)
|
||||
{
|
||||
Init(asnTag);
|
||||
}
|
||||
|
||||
BERGeneralDecoder::BERGeneralDecoder(BERGeneralDecoder &inQueue, byte asnTag)
|
||||
: m_inQueue(inQueue), m_length(0), m_finished(false)
|
||||
{
|
||||
Init(asnTag);
|
||||
}
|
||||
|
||||
void BERGeneralDecoder::Init(byte asnTag)
|
||||
{
|
||||
byte b;
|
||||
if (!m_inQueue.Get(b) || b != asnTag)
|
||||
BERDecodeError();
|
||||
|
||||
if (!BERLengthDecode(m_inQueue, m_length, m_definiteLength))
|
||||
BERDecodeError();
|
||||
|
||||
if (!m_definiteLength && !(asnTag & CONSTRUCTED))
|
||||
BERDecodeError(); // cannot be primitive and have indefinite length
|
||||
}
|
||||
|
||||
BERGeneralDecoder::~BERGeneralDecoder()
|
||||
{
|
||||
try // avoid throwing in destructor
|
||||
{
|
||||
if (!m_finished)
|
||||
MessageEnd();
|
||||
}
|
||||
catch (const Exception&)
|
||||
{
|
||||
// CRYPTOPP_ASSERT(0);
|
||||
}
|
||||
}
|
||||
|
||||
bool BERGeneralDecoder::EndReached() const
|
||||
{
|
||||
if (m_definiteLength)
|
||||
return m_length == 0;
|
||||
else
|
||||
{ // check end-of-content octets
|
||||
word16 i;
|
||||
return (m_inQueue.PeekWord16(i)==2 && i==0);
|
||||
}
|
||||
}
|
||||
|
||||
byte BERGeneralDecoder::PeekByte() const
|
||||
{
|
||||
byte b;
|
||||
if (!Peek(b))
|
||||
BERDecodeError();
|
||||
return b;
|
||||
}
|
||||
|
||||
void BERGeneralDecoder::CheckByte(byte check)
|
||||
{
|
||||
byte b;
|
||||
if (!Get(b) || b != check)
|
||||
BERDecodeError();
|
||||
}
|
||||
|
||||
void BERGeneralDecoder::MessageEnd()
|
||||
{
|
||||
m_finished = true;
|
||||
if (m_definiteLength)
|
||||
{
|
||||
if (m_length != 0)
|
||||
BERDecodeError();
|
||||
}
|
||||
else
|
||||
{ // remove end-of-content octets
|
||||
word16 i;
|
||||
if (m_inQueue.GetWord16(i) != 2 || i != 0)
|
||||
BERDecodeError();
|
||||
}
|
||||
}
|
||||
|
||||
size_t BERGeneralDecoder::TransferTo2(BufferedTransformation &target, lword &transferBytes, const std::string &channel, bool blocking)
|
||||
{
|
||||
if (m_definiteLength && transferBytes > m_length)
|
||||
transferBytes = m_length;
|
||||
size_t blockedBytes = m_inQueue.TransferTo2(target, transferBytes, channel, blocking);
|
||||
ReduceLength(transferBytes);
|
||||
return blockedBytes;
|
||||
}
|
||||
|
||||
size_t BERGeneralDecoder::CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end, const std::string &channel, bool blocking) const
|
||||
{
|
||||
if (m_definiteLength)
|
||||
end = STDMIN(m_length, end);
|
||||
return m_inQueue.CopyRangeTo2(target, begin, end, channel, blocking);
|
||||
}
|
||||
|
||||
lword BERGeneralDecoder::ReduceLength(lword delta)
|
||||
{
|
||||
if (m_definiteLength)
|
||||
{
|
||||
if (m_length < delta)
|
||||
BERDecodeError();
|
||||
m_length -= delta;
|
||||
}
|
||||
return delta;
|
||||
}
|
||||
|
||||
DERGeneralEncoder::DERGeneralEncoder(BufferedTransformation &outQueue)
|
||||
: m_outQueue(outQueue), m_asnTag(DefaultTag), m_finished(false)
|
||||
{
|
||||
}
|
||||
|
||||
DERGeneralEncoder::DERGeneralEncoder(BufferedTransformation &outQueue, byte asnTag)
|
||||
: m_outQueue(outQueue), m_asnTag(asnTag), m_finished(false)
|
||||
{
|
||||
}
|
||||
|
||||
DERGeneralEncoder::DERGeneralEncoder(DERGeneralEncoder &outQueue, byte asnTag)
|
||||
: m_outQueue(outQueue), m_asnTag(asnTag), m_finished(false)
|
||||
{
|
||||
}
|
||||
|
||||
DERGeneralEncoder::~DERGeneralEncoder()
|
||||
{
|
||||
try // avoid throwing in constructor
|
||||
{
|
||||
if (!m_finished)
|
||||
MessageEnd();
|
||||
}
|
||||
catch (const Exception&)
|
||||
{
|
||||
CRYPTOPP_ASSERT(0);
|
||||
}
|
||||
}
|
||||
|
||||
void DERGeneralEncoder::MessageEnd()
|
||||
{
|
||||
m_finished = true;
|
||||
lword length = CurrentSize();
|
||||
m_outQueue.Put(m_asnTag);
|
||||
DERLengthEncode(m_outQueue, length);
|
||||
TransferTo(m_outQueue);
|
||||
}
|
||||
|
||||
// *************************************************************
|
||||
|
||||
void X509PublicKey::BERDecode(BufferedTransformation &bt)
|
||||
{
|
||||
BERSequenceDecoder subjectPublicKeyInfo(bt);
|
||||
BERSequenceDecoder algorithm(subjectPublicKeyInfo);
|
||||
GetAlgorithmID().BERDecodeAndCheck(algorithm);
|
||||
bool parametersPresent = algorithm.EndReached() ? false : BERDecodeAlgorithmParameters(algorithm);
|
||||
algorithm.MessageEnd();
|
||||
|
||||
BERGeneralDecoder subjectPublicKey(subjectPublicKeyInfo, BIT_STRING);
|
||||
subjectPublicKey.CheckByte(0); // unused bits
|
||||
BERDecodePublicKey(subjectPublicKey, parametersPresent, (size_t)subjectPublicKey.RemainingLength());
|
||||
subjectPublicKey.MessageEnd();
|
||||
subjectPublicKeyInfo.MessageEnd();
|
||||
}
|
||||
|
||||
void X509PublicKey::DEREncode(BufferedTransformation &bt) const
|
||||
{
|
||||
DERSequenceEncoder subjectPublicKeyInfo(bt);
|
||||
|
||||
DERSequenceEncoder algorithm(subjectPublicKeyInfo);
|
||||
GetAlgorithmID().DEREncode(algorithm);
|
||||
DEREncodeAlgorithmParameters(algorithm);
|
||||
algorithm.MessageEnd();
|
||||
|
||||
DERGeneralEncoder subjectPublicKey(subjectPublicKeyInfo, BIT_STRING);
|
||||
subjectPublicKey.Put(0); // unused bits
|
||||
DEREncodePublicKey(subjectPublicKey);
|
||||
subjectPublicKey.MessageEnd();
|
||||
|
||||
subjectPublicKeyInfo.MessageEnd();
|
||||
}
|
||||
|
||||
void PKCS8PrivateKey::BERDecode(BufferedTransformation &bt)
|
||||
{
|
||||
BERSequenceDecoder privateKeyInfo(bt);
|
||||
word32 version;
|
||||
BERDecodeUnsigned<word32>(privateKeyInfo, version, INTEGER, 0, 0); // check version
|
||||
|
||||
BERSequenceDecoder algorithm(privateKeyInfo);
|
||||
GetAlgorithmID().BERDecodeAndCheck(algorithm);
|
||||
bool parametersPresent = algorithm.EndReached() ? false : BERDecodeAlgorithmParameters(algorithm);
|
||||
algorithm.MessageEnd();
|
||||
|
||||
BERGeneralDecoder octetString(privateKeyInfo, OCTET_STRING);
|
||||
BERDecodePrivateKey(octetString, parametersPresent, (size_t)privateKeyInfo.RemainingLength());
|
||||
octetString.MessageEnd();
|
||||
|
||||
if (!privateKeyInfo.EndReached())
|
||||
BERDecodeOptionalAttributes(privateKeyInfo);
|
||||
privateKeyInfo.MessageEnd();
|
||||
}
|
||||
|
||||
void PKCS8PrivateKey::DEREncode(BufferedTransformation &bt) const
|
||||
{
|
||||
DERSequenceEncoder privateKeyInfo(bt);
|
||||
DEREncodeUnsigned<word32>(privateKeyInfo, 0); // version
|
||||
|
||||
DERSequenceEncoder algorithm(privateKeyInfo);
|
||||
GetAlgorithmID().DEREncode(algorithm);
|
||||
DEREncodeAlgorithmParameters(algorithm);
|
||||
algorithm.MessageEnd();
|
||||
|
||||
DERGeneralEncoder octetString(privateKeyInfo, OCTET_STRING);
|
||||
DEREncodePrivateKey(octetString);
|
||||
octetString.MessageEnd();
|
||||
|
||||
DEREncodeOptionalAttributes(privateKeyInfo);
|
||||
privateKeyInfo.MessageEnd();
|
||||
}
|
||||
|
||||
void PKCS8PrivateKey::BERDecodeOptionalAttributes(BufferedTransformation &bt)
|
||||
{
|
||||
DERReencode(bt, m_optionalAttributes);
|
||||
}
|
||||
|
||||
void PKCS8PrivateKey::DEREncodeOptionalAttributes(BufferedTransformation &bt) const
|
||||
{
|
||||
m_optionalAttributes.CopyTo(bt);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
Vendored
+965
@@ -0,0 +1,965 @@
|
||||
// asn.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file asn.h
|
||||
/// \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 "misc.h"
|
||||
|
||||
#include <iosfwd>
|
||||
|
||||
// Issue 340
|
||||
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
|
||||
# pragma GCC diagnostic push
|
||||
# pragma GCC diagnostic ignored "-Wconversion"
|
||||
# pragma GCC diagnostic ignored "-Wsign-conversion"
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief ASN.1 types
|
||||
/// \note These tags are not complete
|
||||
enum ASNTag
|
||||
{
|
||||
/// \brief ASN.1 Boolean
|
||||
BOOLEAN = 0x01,
|
||||
/// \brief ASN.1 Integer
|
||||
INTEGER = 0x02,
|
||||
/// \brief ASN.1 Bit string
|
||||
BIT_STRING = 0x03,
|
||||
/// \brief ASN.1 Octet string
|
||||
OCTET_STRING = 0x04,
|
||||
/// \brief ASN.1 Null
|
||||
TAG_NULL = 0x05,
|
||||
/// \brief ASN.1 Object identifier
|
||||
OBJECT_IDENTIFIER = 0x06,
|
||||
/// \brief ASN.1 Object descriptor
|
||||
OBJECT_DESCRIPTOR = 0x07,
|
||||
/// \brief ASN.1 External reference
|
||||
EXTERNAL = 0x08,
|
||||
/// \brief ASN.1 Real integer
|
||||
REAL = 0x09,
|
||||
/// \brief ASN.1 Enumerated value
|
||||
ENUMERATED = 0x0a,
|
||||
/// \brief ASN.1 UTF-8 string
|
||||
UTF8_STRING = 0x0c,
|
||||
/// \brief ASN.1 Sequence
|
||||
SEQUENCE = 0x10,
|
||||
/// \brief ASN.1 Set
|
||||
SET = 0x11,
|
||||
/// \brief ASN.1 Numeric string
|
||||
NUMERIC_STRING = 0x12,
|
||||
/// \brief ASN.1 Printable string
|
||||
PRINTABLE_STRING = 0x13,
|
||||
/// \brief ASN.1 T61 string
|
||||
T61_STRING = 0x14,
|
||||
/// \brief ASN.1 Videotext string
|
||||
VIDEOTEXT_STRING = 0x15,
|
||||
/// \brief ASN.1 IA5 string
|
||||
IA5_STRING = 0x16,
|
||||
/// \brief ASN.1 UTC time
|
||||
UTC_TIME = 0x17,
|
||||
/// \brief ASN.1 Generalized time
|
||||
GENERALIZED_TIME = 0x18,
|
||||
/// \brief ASN.1 Graphic string
|
||||
GRAPHIC_STRING = 0x19,
|
||||
/// \brief ASN.1 Visible string
|
||||
VISIBLE_STRING = 0x1a,
|
||||
/// \brief ASN.1 General string
|
||||
GENERAL_STRING = 0x1b,
|
||||
/// \brief ASN.1 Universal string
|
||||
UNIVERSAL_STRING = 0x1c,
|
||||
/// \brief ASN.1 BMP string
|
||||
BMP_STRING = 0x1e
|
||||
};
|
||||
|
||||
/// \brief ASN.1 flags
|
||||
/// \note These flags are not complete
|
||||
enum ASNIdFlag
|
||||
{
|
||||
/// \brief ASN.1 Universal class
|
||||
UNIVERSAL = 0x00,
|
||||
// DATA = 0x01,
|
||||
// HEADER = 0x02,
|
||||
/// \brief ASN.1 Primitive flag
|
||||
PRIMITIVE = 0x00,
|
||||
/// \brief ASN.1 Constructed flag
|
||||
CONSTRUCTED = 0x20,
|
||||
/// \brief ASN.1 Application class
|
||||
APPLICATION = 0x40,
|
||||
/// \brief ASN.1 Context specific class
|
||||
CONTEXT_SPECIFIC = 0x80,
|
||||
/// \brief ASN.1 Private class
|
||||
PRIVATE = 0xc0
|
||||
};
|
||||
|
||||
/// \brief Raises a BERDecodeErr
|
||||
inline void BERDecodeError() {throw BERDecodeErr();}
|
||||
|
||||
/// \brief Exception thrown when an unknown object identifier is encountered
|
||||
class CRYPTOPP_DLL UnknownOID : public BERDecodeErr
|
||||
{
|
||||
public:
|
||||
/// \brief Construct an UnknownOID
|
||||
UnknownOID() : BERDecodeErr("BER decode error: unknown object identifier") {}
|
||||
/// \brief Construct an UnknownOID
|
||||
/// \param err error message to use for the execption
|
||||
UnknownOID(const char *err) : BERDecodeErr(err) {}
|
||||
};
|
||||
|
||||
/// \brief DER encode a length
|
||||
/// \param bt BufferedTransformation object for writing
|
||||
/// \param length the size to encode
|
||||
/// \return the number of octets used for the encoding
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API DERLengthEncode(BufferedTransformation &bt, lword length);
|
||||
|
||||
/// \brief BER decode a length
|
||||
/// \param bt BufferedTransformation object for reading
|
||||
/// \param length the decoded size
|
||||
/// \return true if the value was decoded
|
||||
/// \throw BERDecodeError if the value fails to decode or is too large for size_t
|
||||
/// \details BERLengthDecode() returns false if the encoding is indefinite length.
|
||||
CRYPTOPP_DLL bool CRYPTOPP_API BERLengthDecode(BufferedTransformation &bt, size_t &length);
|
||||
|
||||
/// \brief DER encode NULL
|
||||
/// \param bt BufferedTransformation object for writing
|
||||
CRYPTOPP_DLL void CRYPTOPP_API DEREncodeNull(BufferedTransformation &bt);
|
||||
|
||||
/// \brief BER decode NULL
|
||||
/// \param bt BufferedTransformation object for reading
|
||||
CRYPTOPP_DLL void CRYPTOPP_API BERDecodeNull(BufferedTransformation &bt);
|
||||
|
||||
/// \brief DER encode octet string
|
||||
/// \param bt BufferedTransformation object for writing
|
||||
/// \param str the string to encode
|
||||
/// \param strLen the length of the string
|
||||
/// \return the number of octets used for the encoding
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeOctetString(BufferedTransformation &bt, const byte *str, size_t strLen);
|
||||
|
||||
/// \brief DER encode octet string
|
||||
/// \param bt BufferedTransformation object for reading
|
||||
/// \param str the string to encode
|
||||
/// \return the number of octets used for the encoding
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeOctetString(BufferedTransformation &bt, const SecByteBlock &str);
|
||||
|
||||
/// \brief BER decode octet string
|
||||
/// \param bt BufferedTransformation object for reading
|
||||
/// \param str the decoded string
|
||||
/// \return the number of octets used for the encoding
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeOctetString(BufferedTransformation &bt, SecByteBlock &str);
|
||||
|
||||
/// \brief BER decode octet string
|
||||
/// \param bt BufferedTransformation object for reading
|
||||
/// \param str the decoded string
|
||||
/// \return the number of octets used for the encoding
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeOctetString(BufferedTransformation &bt, BufferedTransformation &str);
|
||||
|
||||
/// \brief DER encode text string
|
||||
/// \param bt BufferedTransformation object for writing
|
||||
/// \param str the string to encode
|
||||
/// \param strLen the length of the string, in bytes
|
||||
/// \param asnTag the ASN.1 identifier
|
||||
/// \return the number of octets used for the encoding
|
||||
/// \details DEREncodeTextString() can be used for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING
|
||||
/// \since Crypto++ 8.3
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeTextString(BufferedTransformation &bt, const byte* str, size_t strLen, byte asnTag);
|
||||
|
||||
/// \brief DER encode text string
|
||||
/// \param bt BufferedTransformation object for writing
|
||||
/// \param str the string to encode
|
||||
/// \param asnTag the ASN.1 identifier
|
||||
/// \return the number of octets used for the encoding
|
||||
/// \details DEREncodeTextString() can be used for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING
|
||||
/// \since Crypto++ 8.3
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeTextString(BufferedTransformation &bt, const SecByteBlock &str, byte asnTag);
|
||||
|
||||
/// \brief DER encode text string
|
||||
/// \param bt BufferedTransformation object for writing
|
||||
/// \param str the string to encode
|
||||
/// \param asnTag the ASN.1 identifier
|
||||
/// \return the number of octets used for the encoding
|
||||
/// \details DEREncodeTextString() can be used for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING
|
||||
/// \since Crypto++ 6.0
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeTextString(BufferedTransformation &bt, const std::string &str, byte asnTag);
|
||||
|
||||
/// \brief BER decode text string
|
||||
/// \param bt BufferedTransformation object for reading
|
||||
/// \param str the string to decode
|
||||
/// \param asnTag the ASN.1 identifier
|
||||
/// \details BERDecodeTextString() can be used for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING
|
||||
/// \since Crypto++ 8.3
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeTextString(BufferedTransformation &bt, SecByteBlock &str, byte asnTag);
|
||||
|
||||
/// \brief BER decode text string
|
||||
/// \param bt BufferedTransformation object for reading
|
||||
/// \param str the string to decode
|
||||
/// \param asnTag the ASN.1 identifier
|
||||
/// \details BERDecodeTextString() can be used for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING
|
||||
/// \since Crypto++ 6.0
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeTextString(BufferedTransformation &bt, std::string &str, byte asnTag);
|
||||
|
||||
/// \brief DER encode date
|
||||
/// \param bt BufferedTransformation object for writing
|
||||
/// \param str the date to encode
|
||||
/// \param asnTag the ASN.1 identifier
|
||||
/// \return the number of octets used for the encoding
|
||||
/// \details BERDecodeDate() can be used for UTC_TIME and GENERALIZED_TIME
|
||||
/// \since Crypto++ 8.3
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeDate(BufferedTransformation &bt, const SecByteBlock &str, byte asnTag);
|
||||
|
||||
/// \brief BER decode date
|
||||
/// \param bt BufferedTransformation object for reading
|
||||
/// \param str the date to decode
|
||||
/// \param asnTag the ASN.1 identifier
|
||||
/// \details BERDecodeDate() can be used for UTC_TIME and GENERALIZED_TIME
|
||||
/// \since Crypto++ 8.3
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeDate(BufferedTransformation &bt, SecByteBlock &str, byte asnTag);
|
||||
|
||||
/// \brief DER encode bit string
|
||||
/// \param bt BufferedTransformation object for writing
|
||||
/// \param str the string to encode
|
||||
/// \param strLen the length of the string
|
||||
/// \param unusedBits the number of unused bits
|
||||
/// \return the number of octets used for the encoding
|
||||
/// \details The caller is responsible for shifting octets if unusedBits is
|
||||
/// not 0. For example, to DER encode a web server X.509 key usage, the 101b
|
||||
/// bit mask is often used (digitalSignature and keyEncipherment). In this
|
||||
/// case <tt>str</tt> is one octet with a value=0xa0 and unusedBits=5. The
|
||||
/// value 0xa0 is <tt>101b << 5</tt>.
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeBitString(BufferedTransformation &bt, const byte *str, size_t strLen, unsigned int unusedBits=0);
|
||||
|
||||
/// \brief DER decode bit string
|
||||
/// \param bt BufferedTransformation object for reading
|
||||
/// \param str the decoded string
|
||||
/// \param unusedBits the number of unused bits
|
||||
/// \details The caller is responsible for shifting octets if unusedBits is
|
||||
/// not 0. For example, to DER encode a web server X.509 key usage, the 101b
|
||||
/// bit mask is often used (digitalSignature and keyEncipherment). In this
|
||||
/// case <tt>str</tt> is one octet with a value=0xa0 and unusedBits=5. The
|
||||
/// value 0xa0 is <tt>101b << 5</tt>.
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeBitString(BufferedTransformation &bt, SecByteBlock &str, unsigned int &unusedBits);
|
||||
|
||||
/// \brief BER decode and DER re-encode
|
||||
/// \param bt BufferedTransformation object for writing
|
||||
/// \param dest BufferedTransformation object
|
||||
CRYPTOPP_DLL void CRYPTOPP_API DERReencode(BufferedTransformation &bt, BufferedTransformation &dest);
|
||||
|
||||
/// \brief BER decode size
|
||||
/// \param bt BufferedTransformation object for reading
|
||||
/// \return the length of the ASN.1 value, in bytes
|
||||
/// \details BERDecodePeekLength() determines the length of a value without
|
||||
/// consuming octets in the stream. The stream must use definite length encoding.
|
||||
/// If indefinite length encoding is used or an error occurs, then 0 is returned.
|
||||
/// \since Crypto++ 8.3
|
||||
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodePeekLength(const BufferedTransformation &bt);
|
||||
|
||||
/// \brief Object Identifier
|
||||
class CRYPTOPP_DLL OID
|
||||
{
|
||||
public:
|
||||
virtual ~OID() {}
|
||||
|
||||
/// \brief Construct an OID
|
||||
OID() {}
|
||||
|
||||
/// \brief Construct an OID
|
||||
/// \param v value to initialize the OID
|
||||
OID(word32 v) : m_values(1, v) {}
|
||||
|
||||
/// \brief Construct an OID
|
||||
/// \param bt BufferedTransformation object
|
||||
OID(BufferedTransformation &bt) {
|
||||
BERDecode(bt);
|
||||
}
|
||||
|
||||
/// \brief Append a value to an OID
|
||||
/// \param rhs the value to append
|
||||
inline OID & operator+=(word32 rhs) {
|
||||
m_values.push_back(rhs); return *this;
|
||||
}
|
||||
|
||||
/// \brief DER encode this OID
|
||||
/// \param bt BufferedTransformation object
|
||||
void DEREncode(BufferedTransformation &bt) const;
|
||||
|
||||
/// \brief BER decode an OID
|
||||
/// \param bt BufferedTransformation object
|
||||
void BERDecode(BufferedTransformation &bt);
|
||||
|
||||
/// \brief BER decode an OID
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \throw BERDecodeErr() if decoded value doesn't match an expected OID
|
||||
/// \details BERDecodeAndCheck() can be used to parse an OID and verify it matches an expected.
|
||||
/// <pre>
|
||||
/// BERSequenceDecoder key(bt);
|
||||
/// ...
|
||||
/// BERSequenceDecoder algorithm(key);
|
||||
/// GetAlgorithmID().BERDecodeAndCheck(algorithm);
|
||||
/// </pre>
|
||||
void BERDecodeAndCheck(BufferedTransformation &bt) const;
|
||||
|
||||
/// \brief Determine if OID is empty
|
||||
/// \return true if OID has 0 elements, false otherwise
|
||||
/// \since Crypto++ 8.0
|
||||
bool Empty() const {
|
||||
return m_values.empty();
|
||||
}
|
||||
|
||||
/// \brief Retrieve OID value array
|
||||
/// \return OID value vector
|
||||
/// \since Crypto++ 8.0
|
||||
const std::vector<word32>& GetValues() const {
|
||||
return m_values;
|
||||
}
|
||||
|
||||
/// \brief Print an OID
|
||||
/// \param out ostream object
|
||||
/// \return ostream reference
|
||||
/// \details Print() writes the OID in a customary format, like
|
||||
/// 1.2.840.113549.1.1.11. The caller is reposnsible to convert the
|
||||
/// OID to a friendly name, like sha256WithRSAEncryption.
|
||||
/// \since Crypto++ 8.3
|
||||
std::ostream& Print(std::ostream& out) const;
|
||||
|
||||
protected:
|
||||
friend bool operator==(const OID &lhs, const OID &rhs);
|
||||
friend bool operator!=(const OID &lhs, const OID &rhs);
|
||||
friend bool operator<(const OID &lhs, const OID &rhs);
|
||||
friend bool operator<=(const OID &lhs, const OID &rhs);
|
||||
friend bool operator>=(const OID &lhs, const OID &rhs);
|
||||
|
||||
std::vector<word32> m_values;
|
||||
|
||||
private:
|
||||
static void EncodeValue(BufferedTransformation &bt, word32 v);
|
||||
static size_t DecodeValue(BufferedTransformation &bt, word32 &v);
|
||||
};
|
||||
|
||||
/// \brief ASN.1 encoded object filter
|
||||
class EncodedObjectFilter : public Filter
|
||||
{
|
||||
public:
|
||||
enum Flag {PUT_OBJECTS=1, PUT_MESSANGE_END_AFTER_EACH_OBJECT=2, PUT_MESSANGE_END_AFTER_ALL_OBJECTS=4, PUT_MESSANGE_SERIES_END_AFTER_ALL_OBJECTS=8};
|
||||
enum State {IDENTIFIER, LENGTH, BODY, TAIL, ALL_DONE} m_state;
|
||||
|
||||
virtual ~EncodedObjectFilter() {}
|
||||
|
||||
/// \brief Construct an EncodedObjectFilter
|
||||
/// \param attachment a BufferedTrasformation to attach to this object
|
||||
/// \param nObjects the number of objects
|
||||
/// \param flags bitwise OR of EncodedObjectFilter::Flag
|
||||
EncodedObjectFilter(BufferedTransformation *attachment = NULLPTR, unsigned int nObjects = 1, word32 flags = 0);
|
||||
|
||||
/// \brief Input a byte buffer for processing
|
||||
/// \param inString the byte buffer to process
|
||||
/// \param length the size of the string, in bytes
|
||||
void Put(const byte *inString, size_t length);
|
||||
|
||||
unsigned int GetNumberOfCompletedObjects() const {return m_nCurrentObject;}
|
||||
unsigned long GetPositionOfObject(unsigned int i) const {return m_positions[i];}
|
||||
|
||||
private:
|
||||
BufferedTransformation & CurrentTarget();
|
||||
|
||||
ByteQueue m_queue;
|
||||
std::vector<unsigned int> m_positions;
|
||||
lword m_lengthRemaining;
|
||||
word32 m_nObjects, m_nCurrentObject, m_level, m_flags;
|
||||
byte m_id;
|
||||
};
|
||||
|
||||
/// \brief BER General Decoder
|
||||
class CRYPTOPP_DLL BERGeneralDecoder : public Store
|
||||
{
|
||||
public:
|
||||
/// \brief Default ASN.1 tag
|
||||
enum {DefaultTag = SEQUENCE | CONSTRUCTED};
|
||||
|
||||
virtual ~BERGeneralDecoder();
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \details BERGeneralDecoder uses DefaultTag
|
||||
explicit BERGeneralDecoder(BufferedTransformation &inQueue);
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit BERGeneralDecoder(BufferedTransformation &inQueue, byte asnTag);
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit BERGeneralDecoder(BERGeneralDecoder &inQueue, byte asnTag);
|
||||
|
||||
/// \brief Determine length encoding
|
||||
/// \return true if the ASN.1 object is definite length encoded, false otherwise
|
||||
bool IsDefiniteLength() const {
|
||||
return m_definiteLength;
|
||||
}
|
||||
|
||||
/// \brief Determine remaining length
|
||||
/// \return number of octets that remain to be consumed
|
||||
/// \details RemainingLength() is only valid if IsDefiniteLength()
|
||||
/// returns true.
|
||||
lword RemainingLength() const {
|
||||
CRYPTOPP_ASSERT(m_definiteLength);
|
||||
return IsDefiniteLength() ? m_length : 0;
|
||||
}
|
||||
|
||||
/// \brief Determine end of stream
|
||||
/// \return true if all octets have been consumed, false otherwise
|
||||
bool EndReached() const;
|
||||
|
||||
/// \brief Determine next octet
|
||||
/// \return next octet in the stream
|
||||
/// \details PeekByte does not consume the octet.
|
||||
/// \throw BERDecodeError if there are no octets remaining
|
||||
byte PeekByte() const;
|
||||
|
||||
/// \brief Determine next octet
|
||||
/// \details CheckByte reads the next byte in the stream and verifies
|
||||
/// the octet matches b.
|
||||
/// \throw BERDecodeError if the next octet is not b
|
||||
void CheckByte(byte b);
|
||||
|
||||
/// \brief Transfer bytes to another BufferedTransformation
|
||||
/// \param target the destination BufferedTransformation
|
||||
/// \param transferBytes the number of bytes to transfer
|
||||
/// \param channel the channel on which the transfer should occur
|
||||
/// \param blocking specifies whether the object should block when
|
||||
/// processing input
|
||||
/// \return the number of bytes that remain in the transfer block
|
||||
/// (i.e., bytes not transferred)
|
||||
/// \details TransferTo2() removes bytes and moves
|
||||
/// them to the destination. Transfer begins at the index position
|
||||
/// in the current stream, and not from an absolute position in the
|
||||
/// stream.
|
||||
/// \details transferBytes is an \a IN and \a OUT parameter. When
|
||||
/// the call is made, transferBytes is the requested size of the
|
||||
/// transfer. When the call returns, transferBytes is the number
|
||||
/// of bytes that were transferred.
|
||||
size_t TransferTo2(BufferedTransformation &target, lword &transferBytes, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
|
||||
|
||||
/// \brief Copy bytes to another BufferedTransformation
|
||||
/// \param target the destination BufferedTransformation
|
||||
/// \param begin the 0-based index of the first byte to copy in
|
||||
/// the stream
|
||||
/// \param end the 0-based index of the last byte to copy in
|
||||
/// the stream
|
||||
/// \param channel the channel on which the transfer should occur
|
||||
/// \param blocking specifies whether the object should block when
|
||||
/// processing input
|
||||
/// \return the number of bytes that remain in the copy block
|
||||
/// (i.e., bytes not copied)
|
||||
/// \details CopyRangeTo2 copies bytes to the
|
||||
/// destination. The bytes are not removed from this object. Copying
|
||||
/// begins at the index position in the current stream, and not from
|
||||
/// an absolute position in the stream.
|
||||
/// \details begin is an \a IN and \a OUT parameter. When the call is
|
||||
/// made, begin is the starting position of the copy. When the call
|
||||
/// returns, begin is the position of the first byte that was \a not
|
||||
/// copied (which may be different than end). begin can be used for
|
||||
/// subsequent calls to CopyRangeTo2().
|
||||
size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const;
|
||||
|
||||
/// \brief Signals the end of messages to the object
|
||||
/// \details Call this to denote end of sequence
|
||||
void MessageEnd();
|
||||
|
||||
protected:
|
||||
BufferedTransformation &m_inQueue;
|
||||
lword m_length;
|
||||
bool m_finished, m_definiteLength;
|
||||
|
||||
private:
|
||||
void Init(byte asnTag);
|
||||
void StoreInitialize(const NameValuePairs ¶meters)
|
||||
{CRYPTOPP_UNUSED(parameters); CRYPTOPP_ASSERT(false);}
|
||||
lword ReduceLength(lword delta);
|
||||
};
|
||||
|
||||
/// \brief DER General Encoder
|
||||
class CRYPTOPP_DLL DERGeneralEncoder : public ByteQueue
|
||||
{
|
||||
public:
|
||||
/// \brief Default ASN.1 tag
|
||||
enum {DefaultTag = SEQUENCE | CONSTRUCTED};
|
||||
|
||||
virtual ~DERGeneralEncoder();
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \details DERGeneralEncoder uses DefaultTag
|
||||
explicit DERGeneralEncoder(BufferedTransformation &outQueue);
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit DERGeneralEncoder(BufferedTransformation &outQueue, byte asnTag);
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit DERGeneralEncoder(DERGeneralEncoder &outQueue, byte asnTag);
|
||||
|
||||
/// \brief Signals the end of messages to the object
|
||||
/// \details Call this to denote end of sequence
|
||||
void MessageEnd();
|
||||
|
||||
private:
|
||||
BufferedTransformation &m_outQueue;
|
||||
byte m_asnTag;
|
||||
bool m_finished;
|
||||
};
|
||||
|
||||
/// \brief BER Sequence Decoder
|
||||
class CRYPTOPP_DLL BERSequenceDecoder : public BERGeneralDecoder
|
||||
{
|
||||
public:
|
||||
/// \brief Default ASN.1 tag
|
||||
enum {DefaultTag = SEQUENCE | CONSTRUCTED};
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \details BERSequenceDecoder uses DefaultTag
|
||||
explicit BERSequenceDecoder(BufferedTransformation &inQueue)
|
||||
: BERGeneralDecoder(inQueue, DefaultTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit BERSequenceDecoder(BufferedTransformation &inQueue, byte asnTag)
|
||||
: BERGeneralDecoder(inQueue, asnTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \details BERSequenceDecoder uses DefaultTag
|
||||
explicit BERSequenceDecoder(BERSequenceDecoder &inQueue)
|
||||
: BERGeneralDecoder(inQueue, DefaultTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit BERSequenceDecoder(BERSequenceDecoder &inQueue, byte asnTag)
|
||||
: BERGeneralDecoder(inQueue, asnTag) {}
|
||||
};
|
||||
|
||||
/// \brief DER Sequence Encoder
|
||||
class CRYPTOPP_DLL DERSequenceEncoder : public DERGeneralEncoder
|
||||
{
|
||||
public:
|
||||
/// \brief Default ASN.1 tag
|
||||
enum {DefaultTag = SEQUENCE | CONSTRUCTED};
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \details DERSequenceEncoder uses DefaultTag
|
||||
explicit DERSequenceEncoder(BufferedTransformation &outQueue)
|
||||
: DERGeneralEncoder(outQueue, DefaultTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit DERSequenceEncoder(BufferedTransformation &outQueue, byte asnTag)
|
||||
: DERGeneralEncoder(outQueue, asnTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \details DERSequenceEncoder uses DefaultTag
|
||||
explicit DERSequenceEncoder(DERSequenceEncoder &outQueue)
|
||||
: DERGeneralEncoder(outQueue, DefaultTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit DERSequenceEncoder(DERSequenceEncoder &outQueue, byte asnTag)
|
||||
: DERGeneralEncoder(outQueue, asnTag) {}
|
||||
};
|
||||
|
||||
/// \brief BER Set Decoder
|
||||
class CRYPTOPP_DLL BERSetDecoder : public BERGeneralDecoder
|
||||
{
|
||||
public:
|
||||
/// \brief Default ASN.1 tag
|
||||
enum {DefaultTag = SET | CONSTRUCTED};
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \details BERSetDecoder uses DefaultTag
|
||||
explicit BERSetDecoder(BufferedTransformation &inQueue)
|
||||
: BERGeneralDecoder(inQueue, DefaultTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit BERSetDecoder(BufferedTransformation &inQueue, byte asnTag)
|
||||
: BERGeneralDecoder(inQueue, asnTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \details BERSetDecoder uses DefaultTag
|
||||
explicit BERSetDecoder(BERSetDecoder &inQueue)
|
||||
: BERGeneralDecoder(inQueue, DefaultTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 decoder
|
||||
/// \param inQueue input byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit BERSetDecoder(BERSetDecoder &inQueue, byte asnTag)
|
||||
: BERGeneralDecoder(inQueue, asnTag) {}
|
||||
};
|
||||
|
||||
/// \brief DER Set Encoder
|
||||
class CRYPTOPP_DLL DERSetEncoder : public DERGeneralEncoder
|
||||
{
|
||||
public:
|
||||
/// \brief Default ASN.1 tag
|
||||
enum {DefaultTag = SET | CONSTRUCTED};
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \details DERSetEncoder uses DefaultTag
|
||||
explicit DERSetEncoder(BufferedTransformation &outQueue)
|
||||
: DERGeneralEncoder(outQueue, DefaultTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit DERSetEncoder(BufferedTransformation &outQueue, byte asnTag)
|
||||
: DERGeneralEncoder(outQueue, asnTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \details DERSetEncoder uses DefaultTag
|
||||
explicit DERSetEncoder(DERSetEncoder &outQueue)
|
||||
: DERGeneralEncoder(outQueue, DefaultTag) {}
|
||||
|
||||
/// \brief Construct an ASN.1 encoder
|
||||
/// \param outQueue output byte queue
|
||||
/// \param asnTag ASN.1 tag
|
||||
explicit DERSetEncoder(DERSetEncoder &outQueue, byte asnTag)
|
||||
: DERGeneralEncoder(outQueue, asnTag) {}
|
||||
};
|
||||
|
||||
/// \brief Optional data encoder and decoder
|
||||
/// \tparam T class or type
|
||||
template <class T>
|
||||
class ASNOptional : public member_ptr<T>
|
||||
{
|
||||
public:
|
||||
/// \brief BER decode optional data
|
||||
/// \param seqDecoder sequence with the optional ASN.1 data
|
||||
/// \param tag ASN.1 tag to match as optional data
|
||||
/// \param mask the mask to apply when matching the tag
|
||||
/// \sa ASNTag and ASNIdFlag
|
||||
void BERDecode(BERSequenceDecoder &seqDecoder, byte tag, byte mask = ~CONSTRUCTED)
|
||||
{
|
||||
byte b;
|
||||
if (seqDecoder.Peek(b) && (b & mask) == tag)
|
||||
reset(new T(seqDecoder));
|
||||
}
|
||||
|
||||
/// \brief DER encode optional data
|
||||
/// \param out BufferedTransformation object
|
||||
void DEREncode(BufferedTransformation &out)
|
||||
{
|
||||
if (this->get() != NULLPTR)
|
||||
this->get()->DEREncode(out);
|
||||
}
|
||||
};
|
||||
|
||||
/// \brief Encode and decode ASN.1 objects with additional information
|
||||
/// \tparam BASE base class or type
|
||||
/// \details Encodes and decodes public keys, private keys and group
|
||||
/// parameters with OID identifying the algorithm or scheme.
|
||||
template <class BASE>
|
||||
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1CryptoMaterial : public ASN1Object, public BASE
|
||||
{
|
||||
public:
|
||||
/// \brief DER encode ASN.1 object
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \details Save() will write the OID associated with algorithm or scheme.
|
||||
/// In the case of public and private keys, this function writes the
|
||||
/// subjectPubicKeyInfo and privateKeyInfo parts.
|
||||
void Save(BufferedTransformation &bt) const
|
||||
{BEREncode(bt);}
|
||||
|
||||
/// \brief BER decode ASN.1 object
|
||||
/// \param bt BufferedTransformation object
|
||||
void Load(BufferedTransformation &bt)
|
||||
{BERDecode(bt);}
|
||||
};
|
||||
|
||||
/// \brief Encodes and decodes subjectPublicKeyInfo
|
||||
class CRYPTOPP_DLL X509PublicKey : public ASN1CryptoMaterial<PublicKey>
|
||||
{
|
||||
public:
|
||||
virtual ~X509PublicKey() {}
|
||||
|
||||
void BERDecode(BufferedTransformation &bt);
|
||||
void DEREncode(BufferedTransformation &bt) const;
|
||||
|
||||
/// \brief Retrieves the OID of the algorithm
|
||||
/// \return OID of the algorithm
|
||||
virtual OID GetAlgorithmID() const =0;
|
||||
|
||||
/// \brief Decode algorithm parameters
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \sa BERDecodePublicKey, <A HREF="http://www.ietf.org/rfc/rfc2459.txt">RFC
|
||||
/// 2459, section 7.3.1</A>
|
||||
virtual bool BERDecodeAlgorithmParameters(BufferedTransformation &bt)
|
||||
{BERDecodeNull(bt); return false;}
|
||||
|
||||
/// \brief Encode algorithm parameters
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \sa DEREncodePublicKey, <A HREF="http://www.ietf.org/rfc/rfc2459.txt">RFC
|
||||
/// 2459, section 7.3.1</A>
|
||||
virtual bool DEREncodeAlgorithmParameters(BufferedTransformation &bt) const
|
||||
{DEREncodeNull(bt); return false;}
|
||||
|
||||
/// \brief Decode subjectPublicKey part of subjectPublicKeyInfo
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \param parametersPresent flag indicating if algorithm parameters are present
|
||||
/// \param size number of octets to read for the parameters, in bytes
|
||||
/// \details BERDecodePublicKey() the decodes subjectPublicKey part of
|
||||
/// subjectPublicKeyInfo, without the BIT STRING header.
|
||||
/// \details When <tt>parametersPresent = true</tt> then BERDecodePublicKey() calls
|
||||
/// BERDecodeAlgorithmParameters() to parse algorithm parameters.
|
||||
/// \sa BERDecodeAlgorithmParameters
|
||||
virtual void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size) =0;
|
||||
|
||||
/// \brief Encode subjectPublicKey part of subjectPublicKeyInfo
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \details DEREncodePublicKey() encodes the subjectPublicKey part of
|
||||
/// subjectPublicKeyInfo, without the BIT STRING header.
|
||||
/// \sa DEREncodeAlgorithmParameters
|
||||
virtual void DEREncodePublicKey(BufferedTransformation &bt) const =0;
|
||||
};
|
||||
|
||||
/// \brief Encodes and Decodes privateKeyInfo
|
||||
class CRYPTOPP_DLL PKCS8PrivateKey : public ASN1CryptoMaterial<PrivateKey>
|
||||
{
|
||||
public:
|
||||
virtual ~PKCS8PrivateKey() {}
|
||||
|
||||
void BERDecode(BufferedTransformation &bt);
|
||||
void DEREncode(BufferedTransformation &bt) const;
|
||||
|
||||
/// \brief Retrieves the OID of the algorithm
|
||||
/// \return OID of the algorithm
|
||||
virtual OID GetAlgorithmID() const =0;
|
||||
|
||||
/// \brief Decode optional parameters
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \sa BERDecodePrivateKey, <A HREF="http://www.ietf.org/rfc/rfc2459.txt">RFC
|
||||
/// 2459, section 7.3.1</A>
|
||||
virtual bool BERDecodeAlgorithmParameters(BufferedTransformation &bt)
|
||||
{BERDecodeNull(bt); return false;}
|
||||
|
||||
/// \brief Encode optional parameters
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \sa DEREncodePrivateKey, <A HREF="http://www.ietf.org/rfc/rfc2459.txt">RFC
|
||||
/// 2459, section 7.3.1</A>
|
||||
virtual bool DEREncodeAlgorithmParameters(BufferedTransformation &bt) const
|
||||
{DEREncodeNull(bt); return false;}
|
||||
|
||||
/// \brief Decode privateKey part of privateKeyInfo
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \param parametersPresent flag indicating if algorithm parameters are present
|
||||
/// \param size number of octets to read for the parameters, in bytes
|
||||
/// \details BERDecodePrivateKey() the decodes privateKey part of privateKeyInfo,
|
||||
/// without the OCTET STRING header.
|
||||
/// \details When <tt>parametersPresent = true</tt> then BERDecodePrivateKey() calls
|
||||
/// BERDecodeAlgorithmParameters() to parse algorithm parameters.
|
||||
/// \sa BERDecodeAlgorithmParameters
|
||||
virtual void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size) =0;
|
||||
|
||||
/// \brief Encode privateKey part of privateKeyInfo
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \details DEREncodePrivateKey() encodes the privateKey part of privateKeyInfo,
|
||||
/// without the OCTET STRING header.
|
||||
/// \sa DEREncodeAlgorithmParameters
|
||||
virtual void DEREncodePrivateKey(BufferedTransformation &bt) const =0;
|
||||
|
||||
/// \brief Decode optional attributes
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \details BERDecodeOptionalAttributes() decodes optional attributes including
|
||||
/// context-specific tag.
|
||||
/// \sa BERDecodeAlgorithmParameters, DEREncodeOptionalAttributes
|
||||
/// \note default implementation stores attributes to be output using
|
||||
/// DEREncodeOptionalAttributes
|
||||
virtual void BERDecodeOptionalAttributes(BufferedTransformation &bt);
|
||||
|
||||
/// \brief Encode optional attributes
|
||||
/// \param bt BufferedTransformation object
|
||||
/// \details DEREncodeOptionalAttributes() encodes optional attributes including
|
||||
/// context-specific tag.
|
||||
/// \sa BERDecodeAlgorithmParameters
|
||||
virtual void DEREncodeOptionalAttributes(BufferedTransformation &bt) const;
|
||||
|
||||
protected:
|
||||
ByteQueue m_optionalAttributes;
|
||||
};
|
||||
|
||||
// ********************************************************
|
||||
|
||||
/// \brief DER Encode unsigned value
|
||||
/// \tparam T class or type
|
||||
/// \param out BufferedTransformation object
|
||||
/// \param w unsigned value to encode
|
||||
/// \param asnTag the ASN.1 identifier
|
||||
/// \details DEREncodeUnsigned() can be used with INTEGER, BOOLEAN, and ENUM
|
||||
template <class T>
|
||||
size_t DEREncodeUnsigned(BufferedTransformation &out, T w, byte asnTag = INTEGER)
|
||||
{
|
||||
byte buf[sizeof(w)+1];
|
||||
unsigned int bc;
|
||||
if (asnTag == BOOLEAN)
|
||||
{
|
||||
buf[sizeof(w)] = w ? 0xff : 0;
|
||||
bc = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
buf[0] = 0;
|
||||
for (unsigned int i=0; i<sizeof(w); i++)
|
||||
buf[i+1] = byte(w >> (sizeof(w)-1-i)*8);
|
||||
bc = sizeof(w);
|
||||
while (bc > 1 && buf[sizeof(w)+1-bc] == 0)
|
||||
--bc;
|
||||
if (buf[sizeof(w)+1-bc] & 0x80)
|
||||
++bc;
|
||||
}
|
||||
out.Put(asnTag);
|
||||
size_t lengthBytes = DERLengthEncode(out, bc);
|
||||
out.Put(buf+sizeof(w)+1-bc, bc);
|
||||
return 1+lengthBytes+bc;
|
||||
}
|
||||
|
||||
/// \brief BER Decode unsigned value
|
||||
/// \tparam T fundamental C++ type
|
||||
/// \param in BufferedTransformation object
|
||||
/// \param w the decoded value
|
||||
/// \param asnTag the ASN.1 identifier
|
||||
/// \param minValue the minimum expected value
|
||||
/// \param maxValue the maximum expected value
|
||||
/// \throw BERDecodeErr() if the value cannot be parsed or the decoded value is not within range.
|
||||
/// \details DEREncodeUnsigned() can be used with INTEGER, BOOLEAN, and ENUM
|
||||
template <class T>
|
||||
void BERDecodeUnsigned(BufferedTransformation &in, T &w, byte asnTag = INTEGER,
|
||||
T minValue = 0, T maxValue = T(0xffffffff))
|
||||
{
|
||||
byte b;
|
||||
if (!in.Get(b) || b != asnTag)
|
||||
BERDecodeError();
|
||||
|
||||
size_t bc;
|
||||
bool definite = BERLengthDecode(in, bc);
|
||||
if (!definite)
|
||||
BERDecodeError();
|
||||
if (bc > in.MaxRetrievable()) // Issue 346
|
||||
BERDecodeError();
|
||||
if (asnTag == BOOLEAN && bc != 1) // X.690, 8.2.1
|
||||
BERDecodeError();
|
||||
if ((asnTag == INTEGER || asnTag == ENUMERATED) && bc == 0) // X.690, 8.3.1 and 8.4
|
||||
BERDecodeError();
|
||||
|
||||
SecByteBlock buf(bc);
|
||||
|
||||
if (bc != in.Get(buf, bc))
|
||||
BERDecodeError();
|
||||
|
||||
// This consumes leading 0 octets. According to X.690, 8.3.2, it could be non-conforming behavior.
|
||||
// X.690, 8.3.2 says "the bits of the first octet and bit 8 of the second octet ... (a) shall
|
||||
// not all be ones and (b) shall not all be zeros ... These rules ensure that an integer value
|
||||
// is always encoded in the smallest possible number of octet".
|
||||
// We invented AER (Alternate Encoding Rules), which is more relaxed than BER, CER, and DER.
|
||||
const byte *ptr = buf;
|
||||
while (bc > sizeof(w) && *ptr == 0)
|
||||
{
|
||||
bc--;
|
||||
ptr++;
|
||||
}
|
||||
if (bc > sizeof(w))
|
||||
BERDecodeError();
|
||||
|
||||
w = 0;
|
||||
for (unsigned int i=0; i<bc; i++)
|
||||
w = (w << 8) | ptr[i];
|
||||
|
||||
if (w < minValue || w > maxValue)
|
||||
BERDecodeError();
|
||||
}
|
||||
|
||||
#ifdef CRYPTOPP_DOXYGEN_PROCESSING
|
||||
/// \brief Compare two OIDs for equality
|
||||
/// \param lhs the first OID
|
||||
/// \param rhs the second OID
|
||||
/// \return true if the OIDs are equal, false otherwise
|
||||
inline bool operator==(const OID &lhs, const OID &rhs);
|
||||
/// \brief Compare two OIDs for inequality
|
||||
/// \param lhs the first OID
|
||||
/// \param rhs the second OID
|
||||
/// \return true if the OIDs are not equal, false otherwise
|
||||
inline bool operator!=(const OID &lhs, const OID &rhs);
|
||||
/// \brief Compare two OIDs for ordering
|
||||
/// \param lhs the first OID
|
||||
/// \param rhs the second OID
|
||||
/// \return true if the first OID is less than the second OID, false otherwise
|
||||
/// \details operator<() calls std::lexicographical_compare() on each element in the array of values.
|
||||
inline bool operator<(const OID &lhs, const OID &rhs);
|
||||
/// \brief Compare two OIDs for ordering
|
||||
/// \param lhs the first OID
|
||||
/// \param rhs the second OID
|
||||
/// \return true if the first OID is less than or equal to the second OID, false otherwise
|
||||
/// \details operator<=() is implemented in terms of operator==() and operator<().
|
||||
/// \since Crypto++ 8.3
|
||||
inline bool operator<=(const OID &lhs, const OID &rhs);
|
||||
/// \brief Compare two OIDs for ordering
|
||||
/// \param lhs the first OID
|
||||
/// \param rhs the second OID
|
||||
/// \return true if the first OID is greater than or equal to the second OID, false otherwise
|
||||
/// \details operator>=() is implemented in terms of operator<().
|
||||
/// \since Crypto++ 8.3
|
||||
inline bool operator>=(const OID &lhs, const OID &rhs);
|
||||
/// \brief Append a value to an OID
|
||||
/// \param lhs the OID
|
||||
/// \param rhs the value to append
|
||||
inline OID operator+(const OID &lhs, unsigned long rhs);
|
||||
/// \brief Print a OID value
|
||||
/// \param out the output stream
|
||||
/// \param oid the OID
|
||||
inline std::ostream& operator<<(std::ostream& out, const OID &oid)
|
||||
{ return oid.Print(out); }
|
||||
#else
|
||||
inline bool operator==(const ::CryptoPP::OID &lhs, const ::CryptoPP::OID &rhs)
|
||||
{return lhs.m_values == rhs.m_values;}
|
||||
inline bool operator!=(const ::CryptoPP::OID &lhs, const ::CryptoPP::OID &rhs)
|
||||
{return lhs.m_values != rhs.m_values;}
|
||||
inline bool operator<(const ::CryptoPP::OID &lhs, const ::CryptoPP::OID &rhs)
|
||||
{return std::lexicographical_compare(lhs.m_values.begin(), lhs.m_values.end(), rhs.m_values.begin(), rhs.m_values.end());}
|
||||
inline bool operator<=(const ::CryptoPP::OID &lhs, const ::CryptoPP::OID &rhs)
|
||||
{return lhs<rhs || lhs==rhs;}
|
||||
inline bool operator>=(const ::CryptoPP::OID &lhs, const ::CryptoPP::OID &rhs)
|
||||
{return ! (lhs<rhs);}
|
||||
inline ::CryptoPP::OID operator+(const ::CryptoPP::OID &lhs, unsigned long rhs)
|
||||
{return ::CryptoPP::OID(lhs)+=rhs;}
|
||||
inline std::ostream& operator<<(std::ostream& out, const OID &oid)
|
||||
{ return oid.Print(out); }
|
||||
#endif
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
// Issue 340
|
||||
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
|
||||
# pragma GCC diagnostic pop
|
||||
#endif
|
||||
|
||||
#endif
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
// authenc.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
#include "authenc.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
void AuthenticatedSymmetricCipherBase::AuthenticateData(const byte *input, size_t len)
|
||||
{
|
||||
// UBsan finding with -std=c++03 using memcpy
|
||||
CRYPTOPP_ASSERT(input && len);
|
||||
if(!input || !len) return;
|
||||
|
||||
unsigned int blockSize = AuthenticationBlockSize();
|
||||
unsigned int &num = m_bufferedDataLength;
|
||||
byte* data = m_buffer.begin();
|
||||
|
||||
if (data && num) // process left over data
|
||||
{
|
||||
if (num+len >= blockSize)
|
||||
{
|
||||
memcpy(data+num, input, blockSize-num);
|
||||
AuthenticateBlocks(data, blockSize);
|
||||
input += (blockSize-num);
|
||||
len -= (blockSize-num);
|
||||
num = 0;
|
||||
// drop through and do the rest
|
||||
}
|
||||
else
|
||||
{
|
||||
memcpy(data+num, input, len);
|
||||
num += (unsigned int)len;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// now process the input data in blocks of blockSize bytes and save the leftovers to m_data
|
||||
if (len >= blockSize)
|
||||
{
|
||||
size_t leftOver = AuthenticateBlocks(input, len);
|
||||
input += (len - leftOver);
|
||||
len = leftOver;
|
||||
}
|
||||
|
||||
if (data && len)
|
||||
memcpy(data, input, len);
|
||||
num = (unsigned int)len;
|
||||
}
|
||||
|
||||
void AuthenticatedSymmetricCipherBase::SetKey(const byte *userKey, size_t keylength, const NameValuePairs ¶ms)
|
||||
{
|
||||
m_bufferedDataLength = 0;
|
||||
m_state = State_Start;
|
||||
|
||||
this->SetKeyWithoutResync(userKey, keylength, params);
|
||||
m_state = State_KeySet;
|
||||
|
||||
size_t length;
|
||||
const byte *iv = GetIVAndThrowIfInvalid(params, length);
|
||||
if (iv)
|
||||
Resynchronize(iv, (int)length);
|
||||
}
|
||||
|
||||
void AuthenticatedSymmetricCipherBase::Resynchronize(const byte *iv, int length)
|
||||
{
|
||||
if (m_state < State_KeySet)
|
||||
throw BadState(AlgorithmName(), "Resynchronize", "key is set");
|
||||
|
||||
m_bufferedDataLength = 0;
|
||||
m_totalHeaderLength = m_totalMessageLength = m_totalFooterLength = 0;
|
||||
m_state = State_KeySet;
|
||||
|
||||
Resync(iv, this->ThrowIfInvalidIVLength(length));
|
||||
m_state = State_IVSet;
|
||||
}
|
||||
|
||||
void AuthenticatedSymmetricCipherBase::Update(const byte *input, size_t length)
|
||||
{
|
||||
// Part of original authenc.cpp code. Don't remove it.
|
||||
if (length == 0) {return;}
|
||||
|
||||
switch (m_state)
|
||||
{
|
||||
case State_Start:
|
||||
case State_KeySet:
|
||||
throw BadState(AlgorithmName(), "Update", "setting key and IV");
|
||||
case State_IVSet:
|
||||
AuthenticateData(input, length);
|
||||
m_totalHeaderLength += length;
|
||||
break;
|
||||
case State_AuthUntransformed:
|
||||
case State_AuthTransformed:
|
||||
AuthenticateLastConfidentialBlock();
|
||||
m_bufferedDataLength = 0;
|
||||
m_state = State_AuthFooter;
|
||||
// fall through
|
||||
case State_AuthFooter:
|
||||
AuthenticateData(input, length);
|
||||
m_totalFooterLength += length;
|
||||
break;
|
||||
default:
|
||||
CRYPTOPP_ASSERT(false);
|
||||
}
|
||||
}
|
||||
|
||||
void AuthenticatedSymmetricCipherBase::ProcessData(byte *outString, const byte *inString, size_t length)
|
||||
{
|
||||
if (m_state >= State_IVSet && length > MaxMessageLength()-m_totalMessageLength)
|
||||
throw InvalidArgument(AlgorithmName() + ": message length exceeds maximum");
|
||||
m_totalMessageLength += length;
|
||||
|
||||
reswitch:
|
||||
switch (m_state)
|
||||
{
|
||||
case State_Start:
|
||||
case State_KeySet:
|
||||
throw BadState(AlgorithmName(), "ProcessData", "setting key and IV");
|
||||
case State_AuthFooter:
|
||||
throw BadState(AlgorithmName(), "ProcessData was called after footer input has started");
|
||||
case State_IVSet:
|
||||
AuthenticateLastHeaderBlock();
|
||||
m_bufferedDataLength = 0;
|
||||
m_state = AuthenticationIsOnPlaintext()==IsForwardTransformation() ? State_AuthUntransformed : State_AuthTransformed;
|
||||
goto reswitch;
|
||||
case State_AuthUntransformed:
|
||||
AuthenticateData(inString, length);
|
||||
AccessSymmetricCipher().ProcessData(outString, inString, length);
|
||||
break;
|
||||
case State_AuthTransformed:
|
||||
AccessSymmetricCipher().ProcessData(outString, inString, length);
|
||||
AuthenticateData(outString, length);
|
||||
break;
|
||||
default:
|
||||
CRYPTOPP_ASSERT(false);
|
||||
}
|
||||
}
|
||||
|
||||
void AuthenticatedSymmetricCipherBase::TruncatedFinal(byte *mac, size_t macSize)
|
||||
{
|
||||
// https://github.com/weidai11/cryptopp/issues/954
|
||||
this->ThrowIfInvalidTruncatedSize(macSize);
|
||||
|
||||
if (m_totalHeaderLength > MaxHeaderLength())
|
||||
throw InvalidArgument(AlgorithmName() + ": header length of " + IntToString(m_totalHeaderLength) + " exceeds the maximum of " + IntToString(MaxHeaderLength()));
|
||||
|
||||
if (m_totalFooterLength > MaxFooterLength())
|
||||
{
|
||||
if (MaxFooterLength() == 0)
|
||||
throw InvalidArgument(AlgorithmName() + ": additional authenticated data (AAD) cannot be input after data to be encrypted or decrypted");
|
||||
else
|
||||
throw InvalidArgument(AlgorithmName() + ": footer length of " + IntToString(m_totalFooterLength) + " exceeds the maximum of " + IntToString(MaxFooterLength()));
|
||||
}
|
||||
|
||||
switch (m_state)
|
||||
{
|
||||
case State_Start:
|
||||
case State_KeySet:
|
||||
throw BadState(AlgorithmName(), "TruncatedFinal", "setting key and IV");
|
||||
|
||||
case State_IVSet:
|
||||
AuthenticateLastHeaderBlock();
|
||||
m_bufferedDataLength = 0;
|
||||
// fall through
|
||||
|
||||
case State_AuthUntransformed:
|
||||
case State_AuthTransformed:
|
||||
AuthenticateLastConfidentialBlock();
|
||||
m_bufferedDataLength = 0;
|
||||
// fall through
|
||||
|
||||
case State_AuthFooter:
|
||||
AuthenticateLastFooterBlock(mac, macSize);
|
||||
m_bufferedDataLength = 0;
|
||||
break;
|
||||
|
||||
default:
|
||||
CRYPTOPP_ASSERT(false);
|
||||
}
|
||||
|
||||
m_state = State_KeySet;
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
// authenc.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file
|
||||
/// \brief Classes for authenticated encryption modes of operation
|
||||
/// \details Authenticated encryption (AE) schemes combine confidentiality and authenticity
|
||||
/// into a single mode of operation They gained traction in the early 2000's because manually
|
||||
/// combining them was error prone for the typical developer. Around that time, the desire to
|
||||
/// authenticate but not ecrypt additional data (AAD) was also identified. When both features
|
||||
/// are available from a scheme, the system is referred to as an AEAD scheme.
|
||||
/// \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM
|
||||
/// and OCB mode. All modes derive from AuthenticatedSymmetricCipherBase() and the
|
||||
/// motivation for the API, like calling AAD a "header", can be found in Bellare,
|
||||
/// Rogaway and Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX
|
||||
/// Mode of Operation</A>. The EAX paper suggested a basic API to help standardize AEAD
|
||||
/// schemes in software and promote adoption of the modes.
|
||||
/// \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated
|
||||
/// Encryption</A> on the Crypto++ wiki.
|
||||
/// \since Crypto++ 5.6.0
|
||||
|
||||
#ifndef CRYPTOPP_AUTHENC_H
|
||||
#define CRYPTOPP_AUTHENC_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "secblock.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief Base class for authenticated encryption modes of operation
|
||||
/// \details AuthenticatedSymmetricCipherBase() serves as a base implementation for one direction
|
||||
/// (encryption or decryption) of a stream cipher or block cipher mode with authentication.
|
||||
/// \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM
|
||||
/// and OCB mode. All modes derive from AuthenticatedSymmetricCipherBase() and the
|
||||
/// motivation for the API, like calling AAD a "header", can be found in Bellare,
|
||||
/// Rogaway and Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX
|
||||
/// Mode of Operation</A>. The EAX paper suggested a basic API to help standardize AEAD
|
||||
/// schemes in software and promote adoption of the modes.
|
||||
/// \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated
|
||||
/// Encryption</A> on the Crypto++ wiki.
|
||||
/// \since Crypto++ 5.6.0
|
||||
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipherBase : public AuthenticatedSymmetricCipher
|
||||
{
|
||||
public:
|
||||
AuthenticatedSymmetricCipherBase() : m_totalHeaderLength(0), m_totalMessageLength(0),
|
||||
m_totalFooterLength(0), m_bufferedDataLength(0), m_state(State_Start) {}
|
||||
|
||||
// StreamTransformation interface
|
||||
bool IsRandomAccess() const {return false;}
|
||||
bool IsSelfInverting() const {return true;}
|
||||
|
||||
void SetKey(const byte *userKey, size_t keylength, const NameValuePairs ¶ms);
|
||||
void Restart() {if (m_state > State_KeySet) m_state = State_KeySet;}
|
||||
void Resynchronize(const byte *iv, int length=-1);
|
||||
void Update(const byte *input, size_t length);
|
||||
void ProcessData(byte *outString, const byte *inString, size_t length);
|
||||
void TruncatedFinal(byte *mac, size_t macSize);
|
||||
|
||||
protected:
|
||||
void UncheckedSetKey(const byte * key, unsigned int length,const CryptoPP::NameValuePairs ¶ms)
|
||||
{CRYPTOPP_UNUSED(key), CRYPTOPP_UNUSED(length), CRYPTOPP_UNUSED(params); CRYPTOPP_ASSERT(false);}
|
||||
|
||||
void AuthenticateData(const byte *data, size_t len);
|
||||
const SymmetricCipher & GetSymmetricCipher() const
|
||||
{return const_cast<AuthenticatedSymmetricCipherBase *>(this)->AccessSymmetricCipher();}
|
||||
|
||||
virtual SymmetricCipher & AccessSymmetricCipher() =0;
|
||||
virtual bool AuthenticationIsOnPlaintext() const =0;
|
||||
virtual unsigned int AuthenticationBlockSize() const =0;
|
||||
virtual void SetKeyWithoutResync(const byte *userKey, size_t keylength, const NameValuePairs ¶ms) =0;
|
||||
virtual void Resync(const byte *iv, size_t len) =0;
|
||||
virtual size_t AuthenticateBlocks(const byte *data, size_t len) =0;
|
||||
virtual void AuthenticateLastHeaderBlock() =0;
|
||||
virtual void AuthenticateLastConfidentialBlock() {}
|
||||
virtual void AuthenticateLastFooterBlock(byte *mac, size_t macSize) =0;
|
||||
|
||||
// State_AuthUntransformed: authentication is applied to plain text (Authenticate-then-Encrypt)
|
||||
// State_AuthTransformed: authentication is applied to cipher text (Encrypt-then-Authenticate)
|
||||
enum State {State_Start, State_KeySet, State_IVSet, State_AuthUntransformed, State_AuthTransformed, State_AuthFooter};
|
||||
|
||||
AlignedSecByteBlock m_buffer;
|
||||
lword m_totalHeaderLength, m_totalMessageLength, m_totalFooterLength;
|
||||
unsigned int m_bufferedDataLength;
|
||||
State m_state;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
// base32.cpp - written and placed in the public domain by Frank Palazzolo, based on hex.cpp by Wei Dai
|
||||
// extended hex alphabet added by JW in November, 2017.
|
||||
|
||||
#include "pch.h"
|
||||
#include "base32.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
ANONYMOUS_NAMESPACE_BEGIN
|
||||
|
||||
const byte s_stdUpper[] = "ABCDEFGHIJKMNPQRSTUVWXYZ23456789";
|
||||
const byte s_stdLower[] = "abcdefghijkmnpqrstuvwxyz23456789";
|
||||
const byte s_hexUpper[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
|
||||
const byte s_hexLower[] = "0123456789abcdefghijklmnopqrstuv";
|
||||
|
||||
const int s_array[256] = {
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, 24, 25, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1,
|
||||
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1, 11, 12, -1,
|
||||
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, -1, -1, -1, -1, -1,
|
||||
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1, 11, 12, -1,
|
||||
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
|
||||
};
|
||||
|
||||
const int s_hexArray[256] = {
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
|
||||
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
|
||||
25, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
|
||||
25, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
|
||||
};
|
||||
|
||||
ANONYMOUS_NAMESPACE_END
|
||||
|
||||
void Base32Encoder::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
bool uppercase = parameters.GetValueWithDefault(Name::Uppercase(), true);
|
||||
m_filter->Initialize(CombinedNameValuePairs(
|
||||
parameters,
|
||||
MakeParameters(Name::EncodingLookupArray(), uppercase ? &s_stdUpper[0] : &s_stdLower[0], false)(Name::Log2Base(), 5, true)));
|
||||
}
|
||||
|
||||
void Base32Decoder::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
BaseN_Decoder::IsolatedInitialize(CombinedNameValuePairs(
|
||||
parameters,
|
||||
MakeParameters(Name::DecodingLookupArray(), GetDefaultDecodingLookupArray(), false)(Name::Log2Base(), 5, true)));
|
||||
}
|
||||
|
||||
// Unrolled initialization, http://github.com/weidai11/cryptopp/issues/376
|
||||
const int *Base32Decoder::GetDefaultDecodingLookupArray()
|
||||
{
|
||||
return s_array;
|
||||
}
|
||||
|
||||
void Base32HexEncoder::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
bool uppercase = parameters.GetValueWithDefault(Name::Uppercase(), true);
|
||||
m_filter->Initialize(CombinedNameValuePairs(
|
||||
parameters,
|
||||
MakeParameters(Name::EncodingLookupArray(), uppercase ? &s_hexUpper[0] : &s_hexLower[0], false)(Name::Log2Base(), 5, true)));
|
||||
}
|
||||
|
||||
void Base32HexDecoder::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
BaseN_Decoder::IsolatedInitialize(CombinedNameValuePairs(
|
||||
parameters,
|
||||
MakeParameters(Name::DecodingLookupArray(), GetDefaultDecodingLookupArray(), false)(Name::Log2Base(), 5, true)));
|
||||
}
|
||||
|
||||
// Unrolled initialization, http://github.com/weidai11/cryptopp/issues/376
|
||||
const int *Base32HexDecoder::GetDefaultDecodingLookupArray()
|
||||
{
|
||||
return s_hexArray;
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
// base32.h - written and placed in the public domain by Frank Palazzolo, based on hex.cpp by Wei Dai
|
||||
// extended hex alphabet added by JW in November, 2017.
|
||||
|
||||
/// \file base32.h
|
||||
/// \brief Classes for Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
|
||||
|
||||
#ifndef CRYPTOPP_BASE32_H
|
||||
#define CRYPTOPP_BASE32_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "basecode.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief Base32 encodes data using DUDE encoding
|
||||
/// \details Converts data to base32 using DUDE encoding. The default code is based on <A HREF="http://www.ietf.org/proceedings/51/I-D/draft-ietf-idn-dude-02.txt">Differential Unicode Domain Encoding (DUDE) (draft-ietf-idn-dude-02.txt)</A>.
|
||||
/// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
|
||||
class Base32Encoder : public SimpleProxyFilter
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a Base32Encoder
|
||||
/// \param attachment a BufferedTrasformation to attach to this object
|
||||
/// \param uppercase a flag indicating uppercase output
|
||||
/// \param groupSize the size of the grouping
|
||||
/// \param separator the separator to use between groups
|
||||
/// \param terminator the terminator appeand after processing
|
||||
/// \details Base32Encoder() constructs a default encoder. The constructor lacks fields for padding and
|
||||
/// line breaks. You must use IsolatedInitialize() to change the default padding character or suppress it.
|
||||
/// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
|
||||
Base32Encoder(BufferedTransformation *attachment = NULLPTR, bool uppercase = true, int groupSize = 0, const std::string &separator = ":", const std::string &terminator = "")
|
||||
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
|
||||
{
|
||||
IsolatedInitialize(MakeParameters(Name::Uppercase(), uppercase)(Name::GroupSize(), groupSize)(Name::Separator(), ConstByteArrayParameter(separator))(Name::Terminator(), ConstByteArrayParameter(terminator)));
|
||||
}
|
||||
|
||||
/// \brief Initialize or reinitialize this object, without signal propagation
|
||||
/// \param parameters a set of NameValuePairs used to initialize this object
|
||||
/// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
|
||||
/// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
|
||||
/// transformations. If initialization should be propagated, then use the Initialize() function.
|
||||
/// \details The following code modifies the padding and line break parameters for an encoder:
|
||||
/// <pre>
|
||||
/// Base32Encoder encoder;
|
||||
/// AlgorithmParameters params = MakeParameters(Pad(), false)(InsertLineBreaks(), false);
|
||||
/// encoder.IsolatedInitialize(params);</pre>
|
||||
/// \details You can change the encoding to <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base
|
||||
/// 32 Encoding with Extended Hex Alphabet</A> by performing the following:
|
||||
/// <pre>
|
||||
/// Base32Encoder encoder;
|
||||
/// const byte ALPHABET[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
|
||||
/// AlgorithmParameters params = MakeParameters(Name::EncodingLookupArray(),(const byte *)ALPHABET);
|
||||
/// encoder.IsolatedInitialize(params);</pre>
|
||||
/// \details If you change the encoding alphabet, then you will need to change the decoding alphabet \a and
|
||||
/// the decoder's lookup table.
|
||||
/// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
};
|
||||
|
||||
/// \brief Base32 decodes data using DUDE encoding
|
||||
/// \details Converts data from base32 using DUDE encoding. The default code is based on <A HREF="http://www.ietf.org/proceedings/51/I-D/draft-ietf-idn-dude-02.txt">Differential Unicode Domain Encoding (DUDE) (draft-ietf-idn-dude-02.txt)</A>.
|
||||
/// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
|
||||
class Base32Decoder : public BaseN_Decoder
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a Base32Decoder
|
||||
/// \param attachment a BufferedTrasformation to attach to this object
|
||||
/// \sa IsolatedInitialize() for an example of modifying a Base32Decoder after construction.
|
||||
Base32Decoder(BufferedTransformation *attachment = NULLPTR)
|
||||
: BaseN_Decoder(GetDefaultDecodingLookupArray(), 5, attachment) {}
|
||||
|
||||
/// \brief Initialize or reinitialize this object, without signal propagation
|
||||
/// \param parameters a set of NameValuePairs used to initialize this object
|
||||
/// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
|
||||
/// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
|
||||
/// transformations. If initialization should be propagated, then use the Initialize() function.
|
||||
/// \details You can change the encoding to <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base
|
||||
/// 32 Encoding with Extended Hex Alphabet</A> by performing the following:
|
||||
/// <pre>
|
||||
/// int lookup[256];
|
||||
/// const byte ALPHABET[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
|
||||
/// Base32Decoder::InitializeDecodingLookupArray(lookup, ALPHABET, 32, true /*insensitive*/);
|
||||
///
|
||||
/// Base32Decoder decoder;
|
||||
/// AlgorithmParameters params = MakeParameters(Name::DecodingLookupArray(),(const int *)lookup);
|
||||
/// decoder.IsolatedInitialize(params);</pre>
|
||||
/// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
|
||||
private:
|
||||
/// \brief Provides the default decoding lookup table
|
||||
/// \return default decoding lookup table
|
||||
static const int * CRYPTOPP_API GetDefaultDecodingLookupArray();
|
||||
};
|
||||
|
||||
/// \brief Base32 encodes data using extended hex
|
||||
/// \details Converts data to base32 using extended hex alphabet. The alphabet is different than Base32Encoder.
|
||||
/// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder, <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base 32 Encoding with Extended Hex Alphabet</A>.
|
||||
/// \since Crypto++ 6.0
|
||||
class Base32HexEncoder : public SimpleProxyFilter
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a Base32HexEncoder
|
||||
/// \param attachment a BufferedTrasformation to attach to this object
|
||||
/// \param uppercase a flag indicating uppercase output
|
||||
/// \param groupSize the size of the grouping
|
||||
/// \param separator the separator to use between groups
|
||||
/// \param terminator the terminator appeand after processing
|
||||
/// \details Base32HexEncoder() constructs a default encoder. The constructor lacks fields for padding and
|
||||
/// line breaks. You must use IsolatedInitialize() to change the default padding character or suppress it.
|
||||
/// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
|
||||
Base32HexEncoder(BufferedTransformation *attachment = NULLPTR, bool uppercase = true, int groupSize = 0, const std::string &separator = ":", const std::string &terminator = "")
|
||||
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
|
||||
{
|
||||
IsolatedInitialize(MakeParameters(Name::Uppercase(), uppercase)(Name::GroupSize(), groupSize)(Name::Separator(), ConstByteArrayParameter(separator))(Name::Terminator(), ConstByteArrayParameter(terminator)));
|
||||
}
|
||||
|
||||
/// \brief Initialize or reinitialize this object, without signal propagation
|
||||
/// \param parameters a set of NameValuePairs used to initialize this object
|
||||
/// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
|
||||
/// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
|
||||
/// transformations. If initialization should be propagated, then use the Initialize() function.
|
||||
/// \details The following code modifies the padding and line break parameters for an encoder:
|
||||
/// <pre>
|
||||
/// Base32HexEncoder encoder;
|
||||
/// AlgorithmParameters params = MakeParameters(Pad(), false)(InsertLineBreaks(), false);
|
||||
/// encoder.IsolatedInitialize(params);</pre>
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
};
|
||||
|
||||
/// \brief Base32 decodes data using extended hex
|
||||
/// \details Converts data from base32 using extended hex alphabet. The alphabet is different than Base32Decoder.
|
||||
/// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder, <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base 32 Encoding with Extended Hex Alphabet</A>.
|
||||
/// \since Crypto++ 6.0
|
||||
class Base32HexDecoder : public BaseN_Decoder
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a Base32HexDecoder
|
||||
/// \param attachment a BufferedTrasformation to attach to this object
|
||||
/// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
|
||||
Base32HexDecoder(BufferedTransformation *attachment = NULLPTR)
|
||||
: BaseN_Decoder(GetDefaultDecodingLookupArray(), 5, attachment) {}
|
||||
|
||||
/// \brief Initialize or reinitialize this object, without signal propagation
|
||||
/// \param parameters a set of NameValuePairs used to initialize this object
|
||||
/// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
|
||||
/// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
|
||||
/// transformations. If initialization should be propagated, then use the Initialize() function.
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
|
||||
private:
|
||||
/// \brief Provides the default decoding lookup table
|
||||
/// \return default decoding lookup table
|
||||
static const int * CRYPTOPP_API GetDefaultDecodingLookupArray();
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
// base64.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
#include "base64.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
ANONYMOUS_NAMESPACE_BEGIN
|
||||
|
||||
const byte s_stdVec[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
const byte s_urlVec[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
const byte s_padding = '=';
|
||||
const int s_stdArray[256] = {
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
|
||||
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
|
||||
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
|
||||
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
|
||||
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
|
||||
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
|
||||
};
|
||||
const int s_urlArray[256] = {
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1,
|
||||
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
|
||||
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
|
||||
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63,
|
||||
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
|
||||
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
|
||||
};
|
||||
|
||||
ANONYMOUS_NAMESPACE_END
|
||||
|
||||
void Base64Encoder::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
bool insertLineBreaks = parameters.GetValueWithDefault(Name::InsertLineBreaks(), true);
|
||||
int maxLineLength = parameters.GetIntValueWithDefault(Name::MaxLineLength(), 72);
|
||||
|
||||
const char *lineBreak = insertLineBreaks ? "\n" : "";
|
||||
|
||||
m_filter->Initialize(CombinedNameValuePairs(
|
||||
parameters,
|
||||
MakeParameters(Name::EncodingLookupArray(), &s_stdVec[0], false)
|
||||
(Name::PaddingByte(), s_padding)
|
||||
(Name::GroupSize(), insertLineBreaks ? maxLineLength : 0)
|
||||
(Name::Separator(), ConstByteArrayParameter(lineBreak))
|
||||
(Name::Terminator(), ConstByteArrayParameter(lineBreak))
|
||||
(Name::Log2Base(), 6, true)));
|
||||
}
|
||||
|
||||
void Base64URLEncoder::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
bool insertLineBreaks = parameters.GetValueWithDefault(Name::InsertLineBreaks(), true);
|
||||
int maxLineLength = parameters.GetIntValueWithDefault(Name::MaxLineLength(), 72);
|
||||
|
||||
const char *lineBreak = insertLineBreaks ? "\n" : "";
|
||||
|
||||
m_filter->Initialize(CombinedNameValuePairs(
|
||||
parameters,
|
||||
MakeParameters(Name::EncodingLookupArray(), &s_urlVec[0], false)
|
||||
(Name::PaddingByte(), s_padding)
|
||||
(Name::GroupSize(), insertLineBreaks ? maxLineLength : 0)
|
||||
(Name::Separator(), ConstByteArrayParameter(lineBreak))
|
||||
(Name::Terminator(), ConstByteArrayParameter(lineBreak))
|
||||
(Name::Log2Base(), 6, true)));
|
||||
}
|
||||
|
||||
void Base64Decoder::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
BaseN_Decoder::IsolatedInitialize(CombinedNameValuePairs(
|
||||
parameters,
|
||||
MakeParameters(Name::DecodingLookupArray(), GetDecodingLookupArray(), false)(Name::Log2Base(), 6, true)));
|
||||
}
|
||||
|
||||
const int *Base64Decoder::GetDecodingLookupArray()
|
||||
{
|
||||
return s_stdArray;
|
||||
}
|
||||
|
||||
void Base64URLDecoder::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
BaseN_Decoder::IsolatedInitialize(CombinedNameValuePairs(
|
||||
parameters,
|
||||
MakeParameters(Name::DecodingLookupArray(), GetDecodingLookupArray(), false)(Name::Log2Base(), 6, true)));
|
||||
}
|
||||
|
||||
// Unrolled initialization, http://github.com/weidai11/cryptopp/issues/376
|
||||
const int *Base64URLDecoder::GetDecodingLookupArray()
|
||||
{
|
||||
return s_urlArray;
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
// base64.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file base64.h
|
||||
/// \brief Classes for the Base64Encoder, Base64Decoder, Base64URLEncoder and Base64URLDecoder
|
||||
|
||||
#ifndef CRYPTOPP_BASE64_H
|
||||
#define CRYPTOPP_BASE64_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "basecode.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief Base64 encodes data using DUDE
|
||||
/// \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648, Base 64 Encoding</A>.
|
||||
class Base64Encoder : public SimpleProxyFilter
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a Base64Encoder
|
||||
/// \param attachment a BufferedTrasformation to attach to this object
|
||||
/// \param insertLineBreaks a BufferedTrasformation to attach to this object
|
||||
/// \param maxLineLength the length of a line if line breaks are used
|
||||
/// \details Base64Encoder constructs a default encoder. The constructor lacks a parameter for padding, and you must
|
||||
/// use IsolatedInitialize() to modify the Base64Encoder after construction.
|
||||
/// \sa IsolatedInitialize() for an example of modifying an encoder after construction.
|
||||
Base64Encoder(BufferedTransformation *attachment = NULLPTR, bool insertLineBreaks = true, int maxLineLength = 72)
|
||||
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
|
||||
{
|
||||
IsolatedInitialize(MakeParameters(Name::InsertLineBreaks(), insertLineBreaks)(Name::MaxLineLength(), maxLineLength));
|
||||
}
|
||||
|
||||
/// \brief Initialize or reinitialize this object, without signal propagation
|
||||
/// \param parameters a set of NameValuePairs used to initialize this object
|
||||
/// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
|
||||
/// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
|
||||
/// transformations. If initialization should be propagated, then use the Initialize() function.
|
||||
/// \details The following code modifies the padding and line break parameters for an encoder:
|
||||
/// <pre>
|
||||
/// Base64Encoder encoder;
|
||||
/// AlgorithmParameters params = MakeParameters(Pad(), false)(InsertLineBreaks(), false);
|
||||
/// encoder.IsolatedInitialize(params);</pre>
|
||||
/// \details You can change the encoding to RFC 4648 web safe alphabet by performing the following:
|
||||
/// <pre>
|
||||
/// Base64Encoder encoder;
|
||||
/// const byte ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
/// AlgorithmParameters params = MakeParameters(Name::EncodingLookupArray(),(const byte *)ALPHABET);
|
||||
/// encoder.IsolatedInitialize(params);</pre>
|
||||
/// \details If you change the encoding alphabet, then you will need to change the decoding alphabet \a and
|
||||
/// the decoder's lookup table.
|
||||
/// \sa Base64URLEncoder for an encoder that provides the web safe alphabet, and Base64Decoder::IsolatedInitialize()
|
||||
/// for an example of modifying a decoder's lookup table after construction.
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
};
|
||||
|
||||
/// \brief Base64 decodes data using DUDE
|
||||
/// \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648, Base 64 Encoding</A>.
|
||||
class Base64Decoder : public BaseN_Decoder
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a Base64Decoder
|
||||
/// \param attachment a BufferedTrasformation to attach to this object
|
||||
/// \sa IsolatedInitialize() for an example of modifying an encoder after construction.
|
||||
Base64Decoder(BufferedTransformation *attachment = NULLPTR)
|
||||
: BaseN_Decoder(GetDecodingLookupArray(), 6, attachment) {}
|
||||
|
||||
/// \brief Initialize or reinitialize this object, without signal propagation
|
||||
/// \param parameters a set of NameValuePairs used to initialize this object
|
||||
/// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
|
||||
/// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
|
||||
/// transformations. If initialization should be propagated, then use the Initialize() function.
|
||||
/// \details The default decoding alpahbet is RFC 4868. You can change the to RFC 4868 web safe alphabet
|
||||
/// by performing the following:
|
||||
/// <pre>
|
||||
/// int lookup[256];
|
||||
/// const byte ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
/// Base64Decoder::InitializeDecodingLookupArray(lookup, ALPHABET, 64, false);
|
||||
///
|
||||
/// Base64Decoder decoder;
|
||||
/// AlgorithmParameters params = MakeParameters(Name::DecodingLookupArray(),(const int *)lookup);
|
||||
/// decoder.IsolatedInitialize(params);</pre>
|
||||
/// \sa Base64URLDecoder for a decoder that provides the web safe alphabet, and Base64Encoder::IsolatedInitialize()
|
||||
/// for an example of modifying an encoder's alphabet after construction.
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
|
||||
private:
|
||||
/// \brief Provides the default decoding lookup table
|
||||
/// \return default decoding lookup table
|
||||
static const int * CRYPTOPP_API GetDecodingLookupArray();
|
||||
};
|
||||
|
||||
/// \brief Base64 encodes data using a web safe alphabet
|
||||
/// \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648, Base 64 Encoding
|
||||
/// with URL and Filename Safe Alphabet</A>.
|
||||
class Base64URLEncoder : public SimpleProxyFilter
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a Base64URLEncoder
|
||||
/// \param attachment a BufferedTrasformation to attach to this object
|
||||
/// \param insertLineBreaks a BufferedTrasformation to attach to this object
|
||||
/// \param maxLineLength the length of a line if line breaks are used
|
||||
/// \details Base64URLEncoder() constructs a default encoder using a web safe alphabet. The constructor ignores
|
||||
/// insertLineBreaks and maxLineLength because the web and URL safe specifications don't use them. They are
|
||||
/// present in the constructor for API compatibility with Base64Encoder so it is a drop-in replacement. The
|
||||
/// constructor also disables padding on the encoder for the same reason.
|
||||
/// \details If you need line breaks or padding, then you must use IsolatedInitialize() to set them
|
||||
/// after constructing a Base64URLEncoder.
|
||||
/// \sa Base64Encoder for an encoder that provides a classic alphabet, and Base64URLEncoder::IsolatedInitialize
|
||||
/// for an example of modifying an encoder after construction.
|
||||
Base64URLEncoder(BufferedTransformation *attachment = NULLPTR, bool insertLineBreaks = false, int maxLineLength = -1)
|
||||
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
|
||||
{
|
||||
CRYPTOPP_UNUSED(insertLineBreaks), CRYPTOPP_UNUSED(maxLineLength);
|
||||
IsolatedInitialize(MakeParameters(Name::InsertLineBreaks(), false)(Name::MaxLineLength(), -1)(Name::Pad(),false));
|
||||
}
|
||||
|
||||
/// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
|
||||
/// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
|
||||
/// transformations. If initialization should be propagated, then use the Initialize() function.
|
||||
/// \details The following code modifies the padding and line break parameters for an encoder:
|
||||
/// <pre>
|
||||
/// Base64URLEncoder encoder;
|
||||
/// AlgorithmParameters params = MakeParameters(Name::Pad(), true)(Name::InsertLineBreaks(), true);
|
||||
/// encoder.IsolatedInitialize(params);</pre>
|
||||
/// \sa Base64Encoder for an encoder that provides a classic alphabet.
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
};
|
||||
|
||||
/// \brief Base64 decodes data using a web safe alphabet
|
||||
/// \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648, Base 64 Encoding
|
||||
/// with URL and Filename Safe Alphabet</A>.
|
||||
class Base64URLDecoder : public BaseN_Decoder
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a Base64URLDecoder
|
||||
/// \param attachment a BufferedTrasformation to attach to this object
|
||||
/// \details Base64URLDecoder() constructs a default decoder using a web safe alphabet.
|
||||
/// \sa Base64Decoder for a decoder that provides a classic alphabet.
|
||||
Base64URLDecoder(BufferedTransformation *attachment = NULLPTR)
|
||||
: BaseN_Decoder(GetDecodingLookupArray(), 6, attachment) {}
|
||||
|
||||
/// \brief Initialize or reinitialize this object, without signal propagation
|
||||
/// \param parameters a set of NameValuePairs used to initialize this object
|
||||
/// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
|
||||
/// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on
|
||||
/// attached transformations. If initialization should be propagated, then use the Initialize() function.
|
||||
/// \sa Base64Decoder for a decoder that provides a classic alphabet, and Base64URLEncoder::IsolatedInitialize
|
||||
/// for an example of modifying an encoder after construction.
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
|
||||
private:
|
||||
/// \brief Provides the default decoding lookup table
|
||||
/// \return default decoding lookup table
|
||||
static const int * CRYPTOPP_API GetDecodingLookupArray();
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
// basecode.cpp - originally 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 <ctype.h>
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
void BaseN_Encoder::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
parameters.GetRequiredParameter("BaseN_Encoder", Name::EncodingLookupArray(), m_alphabet);
|
||||
|
||||
parameters.GetRequiredIntParameter("BaseN_Encoder", Name::Log2Base(), m_bitsPerChar);
|
||||
if (m_bitsPerChar <= 0 || m_bitsPerChar >= 8)
|
||||
throw InvalidArgument("BaseN_Encoder: Log2Base must be between 1 and 7 inclusive");
|
||||
|
||||
byte padding;
|
||||
bool pad;
|
||||
if (parameters.GetValue(Name::PaddingByte(), padding))
|
||||
pad = parameters.GetValueWithDefault(Name::Pad(), true);
|
||||
else
|
||||
pad = false;
|
||||
m_padding = pad ? padding : -1;
|
||||
|
||||
m_bytePos = m_bitPos = 0;
|
||||
|
||||
int i = 8;
|
||||
while (i%m_bitsPerChar != 0)
|
||||
i += 8;
|
||||
m_outputBlockSize = i/m_bitsPerChar;
|
||||
|
||||
m_outBuf.New(m_outputBlockSize);
|
||||
}
|
||||
|
||||
size_t BaseN_Encoder::Put2(const byte *begin, size_t length, int messageEnd, bool blocking)
|
||||
{
|
||||
FILTER_BEGIN;
|
||||
while (m_inputPosition < length)
|
||||
{
|
||||
if (m_bytePos == 0)
|
||||
memset(m_outBuf, 0, m_outputBlockSize);
|
||||
|
||||
{
|
||||
unsigned int b = begin[m_inputPosition++], bitsLeftInSource = 8;
|
||||
while (true)
|
||||
{
|
||||
CRYPTOPP_ASSERT(m_bitsPerChar-m_bitPos >= 0);
|
||||
unsigned int bitsLeftInTarget = (unsigned int)(m_bitsPerChar-m_bitPos);
|
||||
m_outBuf[m_bytePos] |= b >> (8-bitsLeftInTarget);
|
||||
if (bitsLeftInSource >= bitsLeftInTarget)
|
||||
{
|
||||
m_bitPos = 0;
|
||||
++m_bytePos;
|
||||
bitsLeftInSource -= bitsLeftInTarget;
|
||||
if (bitsLeftInSource == 0)
|
||||
break;
|
||||
b <<= bitsLeftInTarget;
|
||||
b &= 0xff;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_bitPos += bitsLeftInSource;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CRYPTOPP_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));
|
||||
m_outBuf[i] = m_alphabet[m_outBuf[i]];
|
||||
}
|
||||
FILTER_OUTPUT(1, m_outBuf, m_outputBlockSize, 0);
|
||||
|
||||
m_bytePos = m_bitPos = 0;
|
||||
}
|
||||
}
|
||||
if (messageEnd)
|
||||
{
|
||||
if (m_bitPos > 0)
|
||||
++m_bytePos;
|
||||
|
||||
int i;
|
||||
for (i=0; i<m_bytePos; i++)
|
||||
m_outBuf[i] = m_alphabet[m_outBuf[i]];
|
||||
|
||||
if (m_padding != -1 && m_bytePos > 0)
|
||||
{
|
||||
memset(m_outBuf+m_bytePos, m_padding, m_outputBlockSize-m_bytePos);
|
||||
m_bytePos = m_outputBlockSize;
|
||||
}
|
||||
FILTER_OUTPUT(2, m_outBuf, m_bytePos, messageEnd);
|
||||
m_bytePos = m_bitPos = 0;
|
||||
}
|
||||
FILTER_END_NO_MESSAGE_END;
|
||||
}
|
||||
|
||||
void BaseN_Decoder::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
parameters.GetRequiredParameter("BaseN_Decoder", Name::DecodingLookupArray(), m_lookup);
|
||||
|
||||
parameters.GetRequiredIntParameter("BaseN_Decoder", Name::Log2Base(), m_bitsPerChar);
|
||||
if (m_bitsPerChar <= 0 || m_bitsPerChar >= 8)
|
||||
throw InvalidArgument("BaseN_Decoder: Log2Base must be between 1 and 7 inclusive");
|
||||
|
||||
m_bytePos = m_bitPos = 0;
|
||||
|
||||
int i = m_bitsPerChar;
|
||||
while (i%8 != 0)
|
||||
i += m_bitsPerChar;
|
||||
m_outputBlockSize = i/8;
|
||||
|
||||
m_outBuf.New(m_outputBlockSize);
|
||||
}
|
||||
|
||||
size_t BaseN_Decoder::Put2(const byte *begin, size_t length, int messageEnd, bool blocking)
|
||||
{
|
||||
FILTER_BEGIN;
|
||||
while (m_inputPosition < length)
|
||||
{
|
||||
unsigned int value;
|
||||
value = m_lookup[begin[m_inputPosition++]];
|
||||
if (value >= 256)
|
||||
continue;
|
||||
|
||||
if (m_bytePos == 0 && m_bitPos == 0)
|
||||
memset(m_outBuf, 0, m_outputBlockSize);
|
||||
|
||||
{
|
||||
int newBitPos = m_bitPos + m_bitsPerChar;
|
||||
if (newBitPos <= 8)
|
||||
m_outBuf[m_bytePos] |= value << (8-newBitPos);
|
||||
else
|
||||
{
|
||||
m_outBuf[m_bytePos] |= value >> (newBitPos-8);
|
||||
m_outBuf[m_bytePos+1] |= value << (16-newBitPos);
|
||||
}
|
||||
|
||||
m_bitPos = newBitPos;
|
||||
while (m_bitPos >= 8)
|
||||
{
|
||||
m_bitPos -= 8;
|
||||
++m_bytePos;
|
||||
}
|
||||
}
|
||||
|
||||
if (m_bytePos == m_outputBlockSize)
|
||||
{
|
||||
FILTER_OUTPUT(1, m_outBuf, m_outputBlockSize, 0);
|
||||
m_bytePos = m_bitPos = 0;
|
||||
}
|
||||
}
|
||||
if (messageEnd)
|
||||
{
|
||||
FILTER_OUTPUT(2, m_outBuf, m_bytePos, messageEnd);
|
||||
m_bytePos = m_bitPos = 0;
|
||||
}
|
||||
FILTER_END_NO_MESSAGE_END;
|
||||
}
|
||||
|
||||
void BaseN_Decoder::InitializeDecodingLookupArray(int *lookup, const byte *alphabet, unsigned int base, bool caseInsensitive)
|
||||
{
|
||||
std::fill(lookup, lookup+256, -1);
|
||||
|
||||
for (unsigned int i=0; i<base; i++)
|
||||
{
|
||||
// Debug asserts for 'lookup[alphabet[i]] == -1' removed because the self tests
|
||||
// have unusal tests that try to break the encoders and decoders. Tests include
|
||||
// a string of the same characters. I.,e., a string of stars like '********...'.
|
||||
if (caseInsensitive && isalpha(alphabet[i]))
|
||||
{
|
||||
lookup[toupper(alphabet[i])] = i;
|
||||
lookup[tolower(alphabet[i])] = i;
|
||||
}
|
||||
else
|
||||
{
|
||||
lookup[alphabet[i]] = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Grouper::IsolatedInitialize(const NameValuePairs ¶meters)
|
||||
{
|
||||
m_groupSize = parameters.GetIntValueWithDefault(Name::GroupSize(), 0);
|
||||
ConstByteArrayParameter separator, terminator;
|
||||
if (m_groupSize)
|
||||
parameters.GetRequiredParameter("Grouper", Name::Separator(), separator);
|
||||
else
|
||||
parameters.GetValue(Name::Separator(), separator);
|
||||
parameters.GetValue(Name::Terminator(), terminator);
|
||||
|
||||
m_separator.Assign(separator.begin(), separator.size());
|
||||
m_terminator.Assign(terminator.begin(), terminator.size());
|
||||
m_counter = 0;
|
||||
}
|
||||
|
||||
size_t Grouper::Put2(const byte *begin, size_t length, int messageEnd, bool blocking)
|
||||
{
|
||||
FILTER_BEGIN;
|
||||
if (m_groupSize)
|
||||
{
|
||||
while (m_inputPosition < length)
|
||||
{
|
||||
if (m_counter == m_groupSize)
|
||||
{
|
||||
FILTER_OUTPUT(1, m_separator, m_separator.size(), 0);
|
||||
m_counter = 0;
|
||||
}
|
||||
|
||||
size_t len;
|
||||
FILTER_OUTPUT2(2, len = STDMIN(length-m_inputPosition, m_groupSize-m_counter),
|
||||
begin+m_inputPosition, len, 0);
|
||||
m_inputPosition += len;
|
||||
m_counter += len;
|
||||
}
|
||||
}
|
||||
else
|
||||
FILTER_OUTPUT(3, begin, length, 0);
|
||||
|
||||
if (messageEnd)
|
||||
{
|
||||
FILTER_OUTPUT(4, m_terminator, m_terminator.size(), messageEnd);
|
||||
m_counter = 0;
|
||||
}
|
||||
FILTER_END_NO_MESSAGE_END
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
// basecode.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file
|
||||
/// \brief Base classes 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)
|
||||
|
||||
/// \brief Encoder for bases that are a power of 2
|
||||
class CRYPTOPP_DLL BaseN_Encoder : public Unflushable<Filter>
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a BaseN_Encoder
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
BaseN_Encoder(BufferedTransformation *attachment=NULLPTR)
|
||||
: m_alphabet(NULLPTR), m_padding(0), m_bitsPerChar(0)
|
||||
, m_outputBlockSize(0), m_bytePos(0), m_bitPos(0)
|
||||
{Detach(attachment);}
|
||||
|
||||
/// \brief Construct a BaseN_Encoder
|
||||
/// \param alphabet table of ASCII characters to use as the alphabet
|
||||
/// \param log2base the log<sub>2</sub>base
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
/// \param padding the character to use as padding
|
||||
/// \pre log2base must be between 1 and 7 inclusive
|
||||
/// \throw InvalidArgument if log2base is not between 1 and 7
|
||||
BaseN_Encoder(const byte *alphabet, int log2base, BufferedTransformation *attachment=NULLPTR, int padding=-1)
|
||||
: m_alphabet(NULLPTR), m_padding(0), m_bitsPerChar(0)
|
||||
, m_outputBlockSize(0), m_bytePos(0), m_bitPos(0)
|
||||
{
|
||||
Detach(attachment);
|
||||
BaseN_Encoder::IsolatedInitialize(
|
||||
MakeParameters
|
||||
(Name::EncodingLookupArray(), alphabet)
|
||||
(Name::Log2Base(), log2base)
|
||||
(Name::Pad(), padding != -1)
|
||||
(Name::PaddingByte(), byte(padding)));
|
||||
}
|
||||
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
size_t Put2(const byte *begin, size_t length, int messageEnd, bool blocking);
|
||||
|
||||
private:
|
||||
const byte *m_alphabet;
|
||||
int m_padding, m_bitsPerChar, m_outputBlockSize;
|
||||
int m_bytePos, m_bitPos;
|
||||
SecByteBlock m_outBuf;
|
||||
};
|
||||
|
||||
/// \brief Decoder for bases that are a power of 2
|
||||
class CRYPTOPP_DLL BaseN_Decoder : public Unflushable<Filter>
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a BaseN_Decoder
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
/// \details padding is set to -1, which means use default padding. If not
|
||||
/// required, then the value must be set via IsolatedInitialize().
|
||||
BaseN_Decoder(BufferedTransformation *attachment=NULLPTR)
|
||||
: m_lookup(NULLPTR), m_bitsPerChar(0)
|
||||
, m_outputBlockSize(0), m_bytePos(0), m_bitPos(0)
|
||||
{Detach(attachment);}
|
||||
|
||||
/// \brief Construct a BaseN_Decoder
|
||||
/// \param lookup table of values
|
||||
/// \param log2base the log<sub>2</sub>base
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
/// \details log2base is the exponent (like 5 in 2<sup>5</sup>), and not
|
||||
/// the number of elements (like 32).
|
||||
/// \details padding is set to -1, which means use default padding. If not
|
||||
/// required, then the value must be set via IsolatedInitialize().
|
||||
BaseN_Decoder(const int *lookup, int log2base, BufferedTransformation *attachment=NULLPTR)
|
||||
: m_lookup(NULLPTR), m_bitsPerChar(0)
|
||||
, m_outputBlockSize(0), m_bytePos(0), m_bitPos(0)
|
||||
{
|
||||
Detach(attachment);
|
||||
BaseN_Decoder::IsolatedInitialize(
|
||||
MakeParameters
|
||||
(Name::DecodingLookupArray(), lookup)
|
||||
(Name::Log2Base(), log2base));
|
||||
}
|
||||
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
size_t Put2(const byte *begin, size_t length, int messageEnd, bool blocking);
|
||||
|
||||
/// \brief Initializes BaseN lookup array
|
||||
/// \param lookup table of values
|
||||
/// \param alphabet table of ASCII characters
|
||||
/// \param base the base for the encoder
|
||||
/// \param caseInsensitive flag indicating whether the alphabet is case sensitivie
|
||||
/// \pre COUNTOF(lookup) == 256
|
||||
/// \pre COUNTOF(alphabet) == base
|
||||
/// \details Internally, the function sets the first 256 elements in the lookup table to
|
||||
/// their value from the alphabet array or -1. base is the number of element (like 32),
|
||||
/// and not an exponent (like 5 in 2<sup>5</sup>)
|
||||
static void CRYPTOPP_API InitializeDecodingLookupArray(int *lookup, const byte *alphabet, unsigned int base, bool caseInsensitive);
|
||||
|
||||
private:
|
||||
const int *m_lookup;
|
||||
int m_bitsPerChar, m_outputBlockSize;
|
||||
int m_bytePos, m_bitPos;
|
||||
SecByteBlock m_outBuf;
|
||||
};
|
||||
|
||||
/// \brief Filter that breaks input stream into groups of fixed size
|
||||
class CRYPTOPP_DLL Grouper : public Bufferless<Filter>
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a Grouper
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
Grouper(BufferedTransformation *attachment=NULLPTR)
|
||||
: m_groupSize(0), m_counter(0) {Detach(attachment);}
|
||||
|
||||
/// \brief Construct a Grouper
|
||||
/// \param groupSize the size of the grouping
|
||||
/// \param separator the separator to use between groups
|
||||
/// \param terminator the terminator appeand after processing
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
Grouper(int groupSize, const std::string &separator, const std::string &terminator, BufferedTransformation *attachment=NULLPTR)
|
||||
: m_groupSize(0), m_counter(0)
|
||||
{
|
||||
Detach(attachment);
|
||||
Grouper::IsolatedInitialize(
|
||||
MakeParameters
|
||||
(Name::GroupSize(), groupSize)
|
||||
(Name::Separator(), ConstByteArrayParameter(separator))
|
||||
(Name::Terminator(), ConstByteArrayParameter(terminator)));
|
||||
}
|
||||
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters);
|
||||
size_t Put2(const byte *begin, size_t length, int messageEnd, bool blocking);
|
||||
|
||||
private:
|
||||
SecByteBlock m_separator, m_terminator;
|
||||
size_t m_groupSize, m_counter;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
// bench.h - originally written and placed in the public domain by Wei Dai
|
||||
// CryptoPP::Test namespace added by JW in February 2017
|
||||
|
||||
#ifndef CRYPTOPP_BENCH_H
|
||||
#define CRYPTOPP_BENCH_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <cmath>
|
||||
#include <ctime>
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
NAMESPACE_BEGIN(Test)
|
||||
|
||||
// More granular control over benchmarks
|
||||
enum TestClass {
|
||||
/// \brief Random number generators
|
||||
UnkeyedRNG=(1<<0),
|
||||
/// \brief Message digests
|
||||
UnkeyedHash=(1<<1),
|
||||
/// \brief Other unkeyed algorithms
|
||||
UnkeyedOther=(1<<2),
|
||||
|
||||
/// \brief Message authentication codes
|
||||
SharedKeyMAC=(1<<3),
|
||||
/// \brief Stream ciphers
|
||||
SharedKeyStream=(1<<4),
|
||||
/// \brief Block ciphers ciphers
|
||||
SharedKeyBlock=(1<<5),
|
||||
/// \brief Other shared key algorithms
|
||||
SharedKeyOther=(1<<6),
|
||||
|
||||
/// \brief Key agreement algorithms over integers
|
||||
PublicKeyAgreement=(1<<7),
|
||||
/// \brief Encryption algorithms over integers
|
||||
PublicKeyEncryption=(1<<8),
|
||||
/// \brief Signature algorithms over integers
|
||||
PublicKeySignature=(1<<9),
|
||||
/// \brief Other public key algorithms over integers
|
||||
PublicKeyOther=(1<<10),
|
||||
|
||||
/// \brief Key agreement algorithms over EC
|
||||
PublicKeyAgreementEC=(1<<11),
|
||||
/// \brief Encryption algorithms over EC
|
||||
PublicKeyEncryptionEC=(1<<12),
|
||||
/// \brief Signature algorithms over EC
|
||||
PublicKeySignatureEC=(1<<13),
|
||||
/// \brief Other public key algorithms over EC
|
||||
PublicKeyOtherEC=(1<<14),
|
||||
|
||||
Unkeyed=UnkeyedRNG|UnkeyedHash|UnkeyedOther,
|
||||
SharedKey=SharedKeyMAC|SharedKeyStream|SharedKeyBlock|SharedKeyOther,
|
||||
PublicKey=PublicKeyAgreement|PublicKeyEncryption|PublicKeySignature|PublicKeyOther,
|
||||
PublicKeyEC=PublicKeyAgreementEC|PublicKeyEncryptionEC|PublicKeySignatureEC|PublicKeyOtherEC,
|
||||
|
||||
All=Unkeyed|SharedKey|PublicKey|PublicKeyEC,
|
||||
|
||||
TestFirst=(0), TestLast=(1<<15)
|
||||
};
|
||||
|
||||
extern const double CLOCK_TICKS_PER_SECOND;
|
||||
extern double g_allocatedTime;
|
||||
extern double g_hertz;
|
||||
extern double g_logTotal;
|
||||
extern unsigned int g_logCount;
|
||||
extern const byte defaultKey[];
|
||||
|
||||
// Test book keeping
|
||||
extern time_t g_testBegin;
|
||||
extern time_t g_testEnd;
|
||||
|
||||
// Benchmark command handler
|
||||
void BenchmarkWithCommand(int argc, const char* const argv[]);
|
||||
// Top level, prints preamble and postamble
|
||||
void Benchmark(Test::TestClass suites, double t, double hertz);
|
||||
// Unkeyed systems
|
||||
void BenchmarkUnkeyedAlgorithms(double t, double hertz);
|
||||
// Shared key systems
|
||||
void BenchmarkSharedKeyedAlgorithms(double t, double hertz);
|
||||
// Public key systems over integers
|
||||
void BenchmarkPublicKeyAlgorithms(double t, double hertz);
|
||||
// Public key systems over elliptic curves
|
||||
void BenchmarkEllipticCurveAlgorithms(double t, double hertz);
|
||||
|
||||
// These are defined in bench1.cpp
|
||||
extern void OutputResultKeying(double iterations, double timeTaken);
|
||||
extern void OutputResultBytes(const char *name, const char *provider, double length, double timeTaken);
|
||||
extern void OutputResultOperations(const char *name, const char *provider, const char *operation, bool pc, unsigned long iterations, double timeTaken);
|
||||
|
||||
// These are defined in bench1.cpp
|
||||
extern void BenchMark(const char *name, BufferedTransformation &bt, double timeTotal);
|
||||
extern void BenchMark(const char *name, StreamTransformation &cipher, double timeTotal);
|
||||
extern void BenchMark(const char *name, HashTransformation &ht, double timeTotal);
|
||||
extern void BenchMark(const char *name, RandomNumberGenerator &rng, double timeTotal);
|
||||
|
||||
// These are defined in bench2.cpp
|
||||
extern void BenchMarkKeying(SimpleKeyingInterface &c, size_t keyLength, const NameValuePairs ¶ms);
|
||||
extern void BenchMark(const char *name, AuthenticatedSymmetricCipher &cipher, double timeTotal);
|
||||
|
||||
NAMESPACE_END // Test
|
||||
NAMESPACE_END // CryptoPP
|
||||
|
||||
#endif
|
||||
+518
@@ -0,0 +1,518 @@
|
||||
// bench1.cpp - originally written and placed in the public domain by Wei Dai
|
||||
// CryptoPP::Test namespace added by JW in February 2017
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "bench.h"
|
||||
#include "validate.h"
|
||||
|
||||
#include "cpu.h"
|
||||
#include "factory.h"
|
||||
#include "algparam.h"
|
||||
#include "argnames.h"
|
||||
#include "smartptr.h"
|
||||
#include "stdcpp.h"
|
||||
|
||||
#include "osrng.h"
|
||||
#include "drbg.h"
|
||||
#include "darn.h"
|
||||
#include "mersenne.h"
|
||||
#include "rdrand.h"
|
||||
#include "padlkrng.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(disable: 4355)
|
||||
#endif
|
||||
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(disable: 4505 4355)
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
NAMESPACE_BEGIN(Test)
|
||||
|
||||
#ifdef CLOCKS_PER_SEC
|
||||
const double CLOCK_TICKS_PER_SECOND = (double)CLOCKS_PER_SEC;
|
||||
#elif defined(CLK_TCK)
|
||||
const double CLOCK_TICKS_PER_SECOND = (double)CLK_TCK;
|
||||
#else
|
||||
const double CLOCK_TICKS_PER_SECOND = 1000000.0;
|
||||
#endif
|
||||
|
||||
extern const byte defaultKey[] = "0123456789" // 168 + NULL
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
"00000000000000000000000000000000000000000000000000000"
|
||||
"00000000000000000000000000000000000000000000000000000";
|
||||
|
||||
double g_allocatedTime = 0.0, g_hertz = 0.0, g_logTotal = 0.0;
|
||||
unsigned int g_logCount = 0;
|
||||
time_t g_testBegin, g_testEnd;
|
||||
|
||||
inline std::string HertzToString(double hertz)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss.precision(3);
|
||||
|
||||
if (hertz >= 0.999e+9)
|
||||
oss << hertz / 1e+9 << " GHz";
|
||||
else if (hertz >= 0.999e+6)
|
||||
oss << hertz / 1e+6 << " MHz";
|
||||
else if (hertz >= 0.999e+3)
|
||||
oss << hertz / 1e+3 << " KHz";
|
||||
else
|
||||
oss << hertz << " Hz";
|
||||
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
void OutputResultBytes(const char *name, const char *provider, double length, double timeTaken)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
|
||||
// Coverity finding
|
||||
if (length < 0.000001f) length = 0.000001f;
|
||||
if (timeTaken < 0.000001f) timeTaken = 0.000001f;
|
||||
|
||||
double mbs = length / timeTaken / (1024*1024);
|
||||
oss << "\n<TR><TD>" << name << "<TD>" << provider;
|
||||
oss << std::setiosflags(std::ios::fixed);
|
||||
oss << "<TD>" << std::setprecision(0) << std::setiosflags(std::ios::fixed) << mbs;
|
||||
if (g_hertz > 1.0f)
|
||||
{
|
||||
const double cpb = timeTaken * g_hertz / length;
|
||||
if (cpb < 24.0f)
|
||||
oss << "<TD>" << std::setprecision(2) << std::setiosflags(std::ios::fixed) << cpb;
|
||||
else
|
||||
oss << "<TD>" << std::setprecision(1) << std::setiosflags(std::ios::fixed) << cpb;
|
||||
}
|
||||
g_logTotal += log(mbs);
|
||||
g_logCount++;
|
||||
|
||||
std::cout << oss.str();
|
||||
}
|
||||
|
||||
void OutputResultKeying(double iterations, double timeTaken)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
|
||||
// Coverity finding
|
||||
if (iterations < 0.000001f) iterations = 0.000001f;
|
||||
if (timeTaken < 0.000001f) timeTaken = 0.000001f;
|
||||
|
||||
oss << "<TD>" << std::setprecision(3) << std::setiosflags(std::ios::fixed) << (1000*1000*timeTaken/iterations);
|
||||
|
||||
// Coverity finding
|
||||
if (g_hertz > 1.0f)
|
||||
oss << "<TD>" << std::setprecision(0) << std::setiosflags(std::ios::fixed) << timeTaken * g_hertz / iterations;
|
||||
|
||||
std::cout << oss.str();
|
||||
}
|
||||
|
||||
void OutputResultOperations(const char *name, const char *provider, const char *operation, bool pc, unsigned long iterations, double timeTaken)
|
||||
{
|
||||
CRYPTOPP_UNUSED(provider);
|
||||
std::ostringstream oss;
|
||||
|
||||
// Coverity finding
|
||||
if (!iterations) iterations++;
|
||||
if (timeTaken < 0.000001f) timeTaken = 0.000001f;
|
||||
|
||||
oss << "\n<TR><TD>" << name << " " << operation << (pc ? " with precomputation" : "");
|
||||
//oss << "<TD>" << provider;
|
||||
oss << "<TD>" << std::setprecision(3) << std::setiosflags(std::ios::fixed) << (1000*timeTaken/iterations);
|
||||
|
||||
// Coverity finding
|
||||
if (g_hertz > 1.0f)
|
||||
{
|
||||
const double t = timeTaken * g_hertz / iterations / 1000000;
|
||||
oss << "<TD>" << std::setprecision(3) << std::setiosflags(std::ios::fixed) << t;
|
||||
}
|
||||
|
||||
g_logTotal += log(iterations/timeTaken);
|
||||
g_logCount++;
|
||||
|
||||
std::cout << oss.str();
|
||||
}
|
||||
|
||||
/*
|
||||
void BenchMark(const char *name, BlockTransformation &cipher, double timeTotal)
|
||||
{
|
||||
const int BUF_SIZE = RoundUpToMultipleOf(2048U, cipher.OptimalNumberOfParallelBlocks() * cipher.BlockSize());
|
||||
AlignedSecByteBlock buf(BUF_SIZE);
|
||||
buf.SetMark(16);
|
||||
|
||||
const int nBlocks = BUF_SIZE / cipher.BlockSize();
|
||||
unsigned long i=0, blocks=1;
|
||||
double timeTaken;
|
||||
|
||||
clock_t start = ::clock();
|
||||
do
|
||||
{
|
||||
blocks *= 2;
|
||||
for (; i<blocks; i++)
|
||||
cipher.ProcessAndXorMultipleBlocks(buf, NULLPTR, buf, nBlocks);
|
||||
timeTaken = double(::clock() - start) / CLOCK_TICKS_PER_SECOND;
|
||||
}
|
||||
while (timeTaken < 2.0/3*timeTotal);
|
||||
|
||||
OutputResultBytes(name, double(blocks) * BUF_SIZE, timeTaken);
|
||||
}
|
||||
*/
|
||||
|
||||
void BenchMark(const char *name, StreamTransformation &cipher, double timeTotal)
|
||||
{
|
||||
const int BUF_SIZE=RoundUpToMultipleOf(2048U, cipher.OptimalBlockSize());
|
||||
AlignedSecByteBlock buf(BUF_SIZE);
|
||||
Test::GlobalRNG().GenerateBlock(buf, BUF_SIZE);
|
||||
buf.SetMark(16);
|
||||
|
||||
unsigned long i=0, blocks=1;
|
||||
double timeTaken;
|
||||
|
||||
clock_t start = ::clock();
|
||||
do
|
||||
{
|
||||
blocks *= 2;
|
||||
for (; i<blocks; i++)
|
||||
cipher.ProcessString(buf, BUF_SIZE);
|
||||
timeTaken = double(::clock() - start) / CLOCK_TICKS_PER_SECOND;
|
||||
}
|
||||
while (timeTaken < 2.0/3*timeTotal);
|
||||
|
||||
std::string provider = cipher.AlgorithmProvider();
|
||||
OutputResultBytes(name, provider.c_str(), double(blocks) * BUF_SIZE, timeTaken);
|
||||
}
|
||||
|
||||
void BenchMark(const char *name, HashTransformation &ht, double timeTotal)
|
||||
{
|
||||
const int BUF_SIZE=2048U;
|
||||
AlignedSecByteBlock buf(BUF_SIZE);
|
||||
Test::GlobalRNG().GenerateBlock(buf, BUF_SIZE);
|
||||
buf.SetMark(16);
|
||||
|
||||
unsigned long i=0, blocks=1;
|
||||
double timeTaken;
|
||||
|
||||
clock_t start = ::clock();
|
||||
do
|
||||
{
|
||||
blocks *= 2;
|
||||
for (; i<blocks; i++)
|
||||
ht.Update(buf, BUF_SIZE);
|
||||
timeTaken = double(::clock() - start) / CLOCK_TICKS_PER_SECOND;
|
||||
}
|
||||
while (timeTaken < 2.0/3*timeTotal);
|
||||
|
||||
std::string provider = ht.AlgorithmProvider();
|
||||
OutputResultBytes(name, provider.c_str(), double(blocks) * BUF_SIZE, timeTaken);
|
||||
}
|
||||
|
||||
void BenchMark(const char *name, BufferedTransformation &bt, double timeTotal)
|
||||
{
|
||||
const int BUF_SIZE=2048U;
|
||||
AlignedSecByteBlock buf(BUF_SIZE);
|
||||
Test::GlobalRNG().GenerateBlock(buf, BUF_SIZE);
|
||||
buf.SetMark(16);
|
||||
|
||||
unsigned long i=0, blocks=1;
|
||||
double timeTaken;
|
||||
|
||||
clock_t start = ::clock();
|
||||
do
|
||||
{
|
||||
blocks *= 2;
|
||||
for (; i<blocks; i++)
|
||||
bt.Put(buf, BUF_SIZE);
|
||||
timeTaken = double(::clock() - start) / CLOCK_TICKS_PER_SECOND;
|
||||
}
|
||||
while (timeTaken < 2.0/3*timeTotal);
|
||||
|
||||
std::string provider = bt.AlgorithmProvider();
|
||||
OutputResultBytes(name, provider.c_str(), double(blocks) * BUF_SIZE, timeTaken);
|
||||
}
|
||||
|
||||
void BenchMark(const char *name, RandomNumberGenerator &rng, double timeTotal)
|
||||
{
|
||||
const int BUF_SIZE = 2048U;
|
||||
AlignedSecByteBlock buf(BUF_SIZE);
|
||||
Test::GlobalRNG().GenerateBlock(buf, BUF_SIZE);
|
||||
buf.SetMark(16);
|
||||
|
||||
SymmetricCipher * cipher = dynamic_cast<SymmetricCipher*>(&rng);
|
||||
if (cipher != NULLPTR)
|
||||
{
|
||||
const size_t size = cipher->DefaultKeyLength();
|
||||
if (cipher->IsResynchronizable())
|
||||
cipher->SetKeyWithIV(buf, size, buf+size);
|
||||
else
|
||||
cipher->SetKey(buf, size);
|
||||
}
|
||||
|
||||
unsigned long long blocks = 1;
|
||||
double timeTaken;
|
||||
|
||||
clock_t start = ::clock();
|
||||
do
|
||||
{
|
||||
rng.GenerateBlock(buf, buf.size());
|
||||
blocks++;
|
||||
timeTaken = double(::clock() - start) / CLOCK_TICKS_PER_SECOND;
|
||||
} while (timeTaken < timeTotal);
|
||||
|
||||
std::string provider = rng.AlgorithmProvider();
|
||||
OutputResultBytes(name, provider.c_str(), double(blocks) * BUF_SIZE, timeTaken);
|
||||
}
|
||||
|
||||
// Hack, but we probably need a KeyedRandomNumberGenerator interface
|
||||
// and a few methods to generalize keying a RNG. X917RNG, Hash_DRBG,
|
||||
// HMAC_DRBG, AES/CFB RNG and a few others could use it. "A few others"
|
||||
// includes BLAKE2, ChaCha and Poly1305 when used as a RNG.
|
||||
void BenchMark(const char *name, NIST_DRBG &rng, double timeTotal)
|
||||
{
|
||||
const int BUF_SIZE = 2048U;
|
||||
AlignedSecByteBlock buf(BUF_SIZE);
|
||||
Test::GlobalRNG().GenerateBlock(buf, BUF_SIZE);
|
||||
buf.SetMark(16);
|
||||
|
||||
rng.IncorporateEntropy(buf, rng.MinEntropyLength());
|
||||
unsigned long long blocks = 1;
|
||||
double timeTaken;
|
||||
|
||||
clock_t start = ::clock();
|
||||
do
|
||||
{
|
||||
rng.GenerateBlock(buf, buf.size());
|
||||
blocks++;
|
||||
timeTaken = double(::clock() - start) / CLOCK_TICKS_PER_SECOND;
|
||||
} while (timeTaken < timeTotal);
|
||||
|
||||
std::string provider = rng.AlgorithmProvider();
|
||||
OutputResultBytes(name, provider.c_str(), double(blocks) * BUF_SIZE, timeTaken);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
void BenchMarkByNameKeyLess(const char *factoryName, const char *displayName = NULLPTR, const NameValuePairs ¶ms = g_nullNameValuePairs)
|
||||
{
|
||||
CRYPTOPP_UNUSED(params);
|
||||
std::string name = factoryName;
|
||||
if (displayName)
|
||||
name = displayName;
|
||||
|
||||
member_ptr<T> obj(ObjectFactoryRegistry<T>::Registry().CreateObject(factoryName));
|
||||
BenchMark(name.c_str(), *obj, g_allocatedTime);
|
||||
}
|
||||
|
||||
void AddHtmlHeader()
|
||||
{
|
||||
std::ostringstream oss;
|
||||
|
||||
// HTML5
|
||||
oss << "<!DOCTYPE HTML>";
|
||||
oss << "\n<HTML lang=\"en\">";
|
||||
|
||||
oss << "\n<HEAD>";
|
||||
oss << "\n<META charset=\"UTF-8\">";
|
||||
oss << "\n<TITLE>Speed Comparison of Popular Crypto Algorithms</TITLE>";
|
||||
oss << "\n<STYLE>\n table {border-collapse: collapse;}";
|
||||
oss << "\n table, th, td, tr {border: 1px solid black;}\n</STYLE>";
|
||||
oss << "\n</HEAD>";
|
||||
|
||||
oss << "\n<BODY>";
|
||||
|
||||
oss << "\n<H1><A href=\"http://www.cryptopp.com\">Crypto++</A> " << CRYPTOPP_VERSION / 100;
|
||||
oss << '.' << (CRYPTOPP_VERSION % 100) / 10 << '.' << CRYPTOPP_VERSION % 10 << " Benchmarks</H1>";
|
||||
|
||||
oss << "\n<P>Here are speed benchmarks for some commonly used cryptographic algorithms.</P>";
|
||||
|
||||
if (g_hertz > 1.0f)
|
||||
oss << "\n<P>CPU frequency of the test platform is " << HertzToString(g_hertz) << ".</P>";
|
||||
else
|
||||
oss << "\n<P>CPU frequency of the test platform was not provided.</P>" << std::endl;
|
||||
|
||||
std::cout << oss.str();
|
||||
}
|
||||
|
||||
void AddHtmlFooter()
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "\n</BODY>\n</HTML>\n";
|
||||
std::cout << oss.str();
|
||||
}
|
||||
|
||||
void BenchmarkWithCommand(int argc, const char* const argv[])
|
||||
{
|
||||
std::string command(argv[1]);
|
||||
float runningTime(argc >= 3 ? Test::StringToValue<float, true>(argv[2]) : 1.0f);
|
||||
float cpuFreq(argc >= 4 ? Test::StringToValue<float, true>(argv[3])*float(1e9) : 0.0f);
|
||||
std::string algoName(argc >= 5 ? argv[4] : "");
|
||||
|
||||
// https://github.com/weidai11/cryptopp/issues/983
|
||||
if (runningTime > 10.0f)
|
||||
runningTime = 10.0f;
|
||||
|
||||
if (command == "b") // All benchmarks
|
||||
Benchmark(Test::All, runningTime, cpuFreq);
|
||||
else if (command == "b4") // Public key algorithms over EC
|
||||
Test::Benchmark(Test::PublicKeyEC, runningTime, cpuFreq);
|
||||
else if (command == "b3") // Public key algorithms
|
||||
Test::Benchmark(Test::PublicKey, runningTime, cpuFreq);
|
||||
else if (command == "b2") // Shared key algorithms
|
||||
Test::Benchmark(Test::SharedKey, runningTime, cpuFreq);
|
||||
else if (command == "b1") // Unkeyed algorithms
|
||||
Test::Benchmark(Test::Unkeyed, runningTime, cpuFreq);
|
||||
}
|
||||
|
||||
void Benchmark(Test::TestClass suites, double t, double hertz)
|
||||
{
|
||||
g_allocatedTime = t;
|
||||
g_hertz = hertz;
|
||||
|
||||
// Add <br> in between tables
|
||||
size_t count_breaks = 0;
|
||||
|
||||
AddHtmlHeader();
|
||||
|
||||
g_testBegin = ::time(NULLPTR);
|
||||
|
||||
if (static_cast<int>(suites) == 0 || static_cast<int>(suites) > TestLast)
|
||||
suites = Test::All;
|
||||
|
||||
// Unkeyed algorithms
|
||||
if (suites & Test::Unkeyed)
|
||||
{
|
||||
if (count_breaks)
|
||||
std::cout << "\n<BR>";
|
||||
count_breaks++;
|
||||
|
||||
BenchmarkUnkeyedAlgorithms(t, hertz);
|
||||
}
|
||||
|
||||
// Shared key algorithms
|
||||
if (suites & Test::SharedKey)
|
||||
{
|
||||
if (count_breaks)
|
||||
std::cout << "\n<BR>";
|
||||
count_breaks++;
|
||||
|
||||
BenchmarkSharedKeyedAlgorithms(t, hertz);
|
||||
}
|
||||
|
||||
// Public key algorithms
|
||||
if (suites & Test::PublicKey)
|
||||
{
|
||||
if (count_breaks)
|
||||
std::cout << "\n<BR>";
|
||||
count_breaks++;
|
||||
|
||||
BenchmarkPublicKeyAlgorithms(t, hertz);
|
||||
}
|
||||
|
||||
// Public key algorithms over EC
|
||||
if (suites & Test::PublicKeyEC)
|
||||
{
|
||||
if (count_breaks)
|
||||
std::cout << "\n<BR>";
|
||||
count_breaks++;
|
||||
|
||||
BenchmarkEllipticCurveAlgorithms(t, hertz);
|
||||
}
|
||||
|
||||
g_testEnd = ::time(NULLPTR);
|
||||
|
||||
std::ostringstream oss;
|
||||
oss << "\n<P>Throughput Geometric Average: " << std::setiosflags(std::ios::fixed);
|
||||
oss << std::exp(g_logTotal/(g_logCount > 0.0f ? g_logCount : 1.0f)) << std::endl;
|
||||
|
||||
oss << "\n<P>Test started at " << TimeToString(g_testBegin);
|
||||
oss << "\n<BR>Test ended at " << TimeToString(g_testEnd);
|
||||
oss << "\n";
|
||||
std::cout << oss.str();
|
||||
|
||||
AddHtmlFooter();
|
||||
}
|
||||
|
||||
void BenchmarkUnkeyedAlgorithms(double t, double hertz)
|
||||
{
|
||||
g_allocatedTime = t;
|
||||
g_hertz = hertz;
|
||||
|
||||
const char *cpb;
|
||||
if (g_hertz > 1.0f)
|
||||
cpb = "<TH>Cycles/Byte";
|
||||
else
|
||||
cpb = "";
|
||||
|
||||
std::cout << "\n<TABLE>";
|
||||
|
||||
std::cout << "\n<COLGROUP><COL style=\"text-align: left;\"><COL style=\"text-align: right;\">";
|
||||
std::cout << "<COL style=\"text-align: right;\">";
|
||||
std::cout << "\n<THEAD style=\"background: #F0F0F0\">";
|
||||
std::cout << "\n<TR><TH>Algorithm<TH>Provider<TH>MiB/Second" << cpb;
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: white;\">";
|
||||
{
|
||||
#ifdef NONBLOCKING_RNG_AVAILABLE
|
||||
BenchMarkByNameKeyLess<RandomNumberGenerator>("NonblockingRng");
|
||||
#endif
|
||||
#ifdef OS_RNG_AVAILABLE
|
||||
BenchMarkByNameKeyLess<RandomNumberGenerator>("AutoSeededRandomPool");
|
||||
BenchMarkByNameKeyLess<RandomNumberGenerator>("AutoSeededX917RNG(AES)");
|
||||
#endif
|
||||
BenchMarkByNameKeyLess<RandomNumberGenerator>("MT19937");
|
||||
#if (CRYPTOPP_BOOL_X86) && !defined(CRYPTOPP_DISABLE_ASM)
|
||||
if (HasPadlockRNG())
|
||||
BenchMarkByNameKeyLess<RandomNumberGenerator>("PadlockRNG");
|
||||
#endif
|
||||
#if (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64) && !defined(CRYPTOPP_DISABLE_ASM)
|
||||
if (HasRDRAND())
|
||||
BenchMarkByNameKeyLess<RandomNumberGenerator>("RDRAND");
|
||||
if (HasRDSEED())
|
||||
BenchMarkByNameKeyLess<RandomNumberGenerator>("RDSEED");
|
||||
#endif
|
||||
#if (CRYPTOPP_BOOL_PPC32 || CRYPTOPP_BOOL_PPC64) && !defined(CRYPTOPP_DISABLE_ASM)
|
||||
if (HasDARN())
|
||||
BenchMarkByNameKeyLess<RandomNumberGenerator>("DARN");
|
||||
#endif
|
||||
BenchMarkByNameKeyLess<RandomNumberGenerator>("AES/OFB RNG");
|
||||
BenchMarkByNameKeyLess<NIST_DRBG>("Hash_DRBG(SHA1)");
|
||||
BenchMarkByNameKeyLess<NIST_DRBG>("Hash_DRBG(SHA256)");
|
||||
BenchMarkByNameKeyLess<NIST_DRBG>("HMAC_DRBG(SHA1)");
|
||||
BenchMarkByNameKeyLess<NIST_DRBG>("HMAC_DRBG(SHA256)");
|
||||
}
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: yellow;\">";
|
||||
{
|
||||
BenchMarkByNameKeyLess<HashTransformation>("CRC32");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("CRC32C");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("Adler32");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("MD5");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("SHA-1");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("SHA-256");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("SHA-512");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("SHA3-224");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("SHA3-256");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("SHA3-384");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("SHA3-512");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("Keccak-224");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("Keccak-256");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("Keccak-384");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("Keccak-512");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("Tiger");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("Whirlpool");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("RIPEMD-160");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("RIPEMD-320");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("RIPEMD-128");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("RIPEMD-256");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("SM3");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("BLAKE2s");
|
||||
BenchMarkByNameKeyLess<HashTransformation>("BLAKE2b");
|
||||
}
|
||||
|
||||
std::cout << "\n</TABLE>" << std::endl;
|
||||
}
|
||||
|
||||
NAMESPACE_END // Test
|
||||
NAMESPACE_END // CryptoPP
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
// bench2.cpp - originally written and placed in the public domain by Wei Dai
|
||||
// CryptoPP::Test namespace added by JW in February 2017
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "bench.h"
|
||||
#include "validate.h"
|
||||
|
||||
#include "cpu.h"
|
||||
#include "factory.h"
|
||||
#include "algparam.h"
|
||||
#include "argnames.h"
|
||||
#include "smartptr.h"
|
||||
#include "stdcpp.h"
|
||||
|
||||
#include "vmac.h"
|
||||
#include "hmac.h"
|
||||
#include "ttmac.h"
|
||||
#include "cmac.h"
|
||||
#include "dmac.h"
|
||||
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(disable: 4355)
|
||||
#endif
|
||||
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(disable: 4505 4355)
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
NAMESPACE_BEGIN(Test)
|
||||
|
||||
void BenchMarkKeying(SimpleKeyingInterface &c, size_t keyLength, const NameValuePairs ¶ms)
|
||||
{
|
||||
unsigned long iterations = 0;
|
||||
double timeTaken;
|
||||
|
||||
clock_t start = ::clock();
|
||||
do
|
||||
{
|
||||
for (unsigned int i=0; i<1024; i++)
|
||||
c.SetKey(defaultKey, keyLength, params);
|
||||
timeTaken = double(::clock() - start) / CLOCK_TICKS_PER_SECOND;
|
||||
iterations += 1024;
|
||||
}
|
||||
while (timeTaken < g_allocatedTime);
|
||||
|
||||
OutputResultKeying(iterations, timeTaken);
|
||||
}
|
||||
|
||||
void BenchMark(const char *name, AuthenticatedSymmetricCipher &cipher, double timeTotal)
|
||||
{
|
||||
if (cipher.NeedsPrespecifiedDataLengths())
|
||||
cipher.SpecifyDataLengths(0, cipher.MaxMessageLength(), 0);
|
||||
|
||||
BenchMark(name, static_cast<StreamTransformation &>(cipher), timeTotal);
|
||||
}
|
||||
|
||||
template <class T_FactoryOutput, class T_Interface>
|
||||
void BenchMarkByName2(const char *factoryName, size_t keyLength=0, const char *displayName=NULLPTR, const NameValuePairs ¶ms = g_nullNameValuePairs)
|
||||
{
|
||||
std::string name(factoryName ? factoryName : "");
|
||||
member_ptr<T_FactoryOutput> obj(ObjectFactoryRegistry<T_FactoryOutput>::Registry().CreateObject(name.c_str()));
|
||||
|
||||
if (keyLength == 0)
|
||||
keyLength = obj->DefaultKeyLength();
|
||||
|
||||
if (displayName != NULLPTR)
|
||||
name = displayName;
|
||||
else if (keyLength != 0)
|
||||
name += " (" + IntToString(keyLength * 8) + "-bit key)";
|
||||
|
||||
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(defaultKey, obj->IVSize()), false)));
|
||||
}
|
||||
|
||||
template <class T_FactoryOutput>
|
||||
void BenchMarkByName(const char *factoryName, size_t keyLength=0, const char *displayName=NULLPTR, const NameValuePairs ¶ms = g_nullNameValuePairs)
|
||||
{
|
||||
BenchMarkByName2<T_FactoryOutput,T_FactoryOutput>(factoryName, keyLength, displayName, params);
|
||||
}
|
||||
|
||||
void BenchmarkSharedKeyedAlgorithms(double t, double hertz)
|
||||
{
|
||||
g_allocatedTime = t;
|
||||
g_hertz = hertz;
|
||||
|
||||
const char *cpb, *cpk;
|
||||
if (g_hertz > 1.0f)
|
||||
{
|
||||
cpb = "<TH>Cycles/Byte";
|
||||
cpk = "<TH>Cycles to<BR>Setup Key and IV";
|
||||
}
|
||||
else
|
||||
{
|
||||
cpb = cpk = "";
|
||||
}
|
||||
|
||||
std::cout << "\n<TABLE>";
|
||||
std::cout << "\n<COLGROUP><COL style=\"text-align: left;\"><COL style=\"text-align: right;\"><COL style=";
|
||||
std::cout << "\"text-align: right;\"><COL style=\"text-align: right;\"><COL style=\"text-align: right;\">";
|
||||
std::cout << "\n<THEAD style=\"background: #F0F0F0\">";
|
||||
std::cout << "\n<TR><TH>Algorithm<TH>Provider<TH>MiB/Second" << cpb;
|
||||
std::cout << "<TH>Microseconds to<BR>Setup Key and IV" << cpk;
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: white;\">";
|
||||
{
|
||||
#if CRYPTOPP_AESNI_AVAILABLE
|
||||
if (HasCLMUL())
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES)");
|
||||
else
|
||||
#elif CRYPTOPP_ARM_PMULL_AVAILABLE
|
||||
if (HasPMULL())
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES)");
|
||||
else
|
||||
#elif CRYPTOPP_POWER8_VMULL_AVAILABLE
|
||||
if (HasPMULL())
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES)");
|
||||
else
|
||||
#endif
|
||||
{
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES) (2K tables)", MakeParameters(Name::TableSize(), 2048));
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES) (64K tables)", MakeParameters(Name::TableSize(), 64 * 1024));
|
||||
}
|
||||
|
||||
BenchMarkByName<MessageAuthenticationCode>("VMAC(AES)-64");
|
||||
BenchMarkByName<MessageAuthenticationCode>("VMAC(AES)-128");
|
||||
BenchMarkByName<MessageAuthenticationCode>("HMAC(SHA-1)");
|
||||
BenchMarkByName<MessageAuthenticationCode>("HMAC(SHA-256)");
|
||||
BenchMarkByName<MessageAuthenticationCode>("Two-Track-MAC");
|
||||
BenchMarkByName<MessageAuthenticationCode>("CMAC(AES)");
|
||||
BenchMarkByName<MessageAuthenticationCode>("DMAC(AES)");
|
||||
BenchMarkByName<MessageAuthenticationCode>("Poly1305(AES)");
|
||||
BenchMarkByName<MessageAuthenticationCode>("Poly1305TLS");
|
||||
BenchMarkByName<MessageAuthenticationCode>("BLAKE2s");
|
||||
BenchMarkByName<MessageAuthenticationCode>("BLAKE2b");
|
||||
BenchMarkByName<MessageAuthenticationCode>("SipHash-2-4");
|
||||
BenchMarkByName<MessageAuthenticationCode>("SipHash-4-8");
|
||||
}
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: yellow;\">";
|
||||
{
|
||||
BenchMarkByName<SymmetricCipher>("Panama-LE");
|
||||
BenchMarkByName<SymmetricCipher>("Panama-BE");
|
||||
BenchMarkByName<SymmetricCipher>("Salsa20", 0, "Salsa20");
|
||||
BenchMarkByName<SymmetricCipher>("Salsa20", 0, "Salsa20/12", MakeParameters(Name::Rounds(), 12));
|
||||
BenchMarkByName<SymmetricCipher>("Salsa20", 0, "Salsa20/8", MakeParameters(Name::Rounds(), 8));
|
||||
BenchMarkByName<SymmetricCipher>("ChaCha", 0, "ChaCha20");
|
||||
BenchMarkByName<SymmetricCipher>("ChaCha", 0, "ChaCha12", MakeParameters(Name::Rounds(), 12));
|
||||
BenchMarkByName<SymmetricCipher>("ChaCha", 0, "ChaCha8", MakeParameters(Name::Rounds(), 8));
|
||||
BenchMarkByName<SymmetricCipher>("ChaChaTLS");
|
||||
BenchMarkByName<SymmetricCipher>("Sosemanuk");
|
||||
BenchMarkByName<SymmetricCipher>("Rabbit");
|
||||
BenchMarkByName<SymmetricCipher>("RabbitWithIV");
|
||||
BenchMarkByName<SymmetricCipher>("HC-128");
|
||||
BenchMarkByName<SymmetricCipher>("HC-256");
|
||||
BenchMarkByName<SymmetricCipher>("MARC4");
|
||||
BenchMarkByName<SymmetricCipher>("SEAL-3.0-LE");
|
||||
BenchMarkByName<SymmetricCipher>("WAKE-OFB-LE");
|
||||
}
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: white;\">";
|
||||
{
|
||||
BenchMarkByName<SymmetricCipher>("AES/CTR", 16);
|
||||
BenchMarkByName<SymmetricCipher>("AES/CTR", 24);
|
||||
BenchMarkByName<SymmetricCipher>("AES/CTR", 32);
|
||||
BenchMarkByName<SymmetricCipher>("AES/CBC", 16);
|
||||
BenchMarkByName<SymmetricCipher>("AES/CBC", 24);
|
||||
BenchMarkByName<SymmetricCipher>("AES/CBC", 32);
|
||||
BenchMarkByName<SymmetricCipher>("AES/XTS", 32);
|
||||
BenchMarkByName<SymmetricCipher>("AES/XTS", 48);
|
||||
BenchMarkByName<SymmetricCipher>("AES/XTS", 64);
|
||||
BenchMarkByName<SymmetricCipher>("AES/OFB", 16);
|
||||
BenchMarkByName<SymmetricCipher>("AES/CFB", 16);
|
||||
BenchMarkByName<SymmetricCipher>("AES/ECB", 16);
|
||||
BenchMarkByName<SymmetricCipher>("ARIA/CTR", 16);
|
||||
BenchMarkByName<SymmetricCipher>("ARIA/CTR", 32);
|
||||
BenchMarkByName<SymmetricCipher>("HIGHT/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("Camellia/CTR", 16);
|
||||
BenchMarkByName<SymmetricCipher>("Camellia/CTR", 32);
|
||||
BenchMarkByName<SymmetricCipher>("Twofish/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("Threefish-256(256)/CTR", 32);
|
||||
BenchMarkByName<SymmetricCipher>("Threefish-512(512)/CTR", 64);
|
||||
BenchMarkByName<SymmetricCipher>("Threefish-1024(1024)/CTR", 128);
|
||||
BenchMarkByName<SymmetricCipher>("Serpent/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("CAST-128/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("CAST-256/CTR", 32);
|
||||
BenchMarkByName<SymmetricCipher>("RC6/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("MARS/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("SHACAL-2/CTR", 16);
|
||||
BenchMarkByName<SymmetricCipher>("SHACAL-2/CTR", 64);
|
||||
BenchMarkByName<SymmetricCipher>("DES/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("DES-XEX3/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("DES-EDE3/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("IDEA/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("RC5/CTR", 0, "RC5 (r=16)");
|
||||
BenchMarkByName<SymmetricCipher>("Blowfish/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("SKIPJACK/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("SEED/CTR", 0, "SEED/CTR (1/2 K table)");
|
||||
BenchMarkByName<SymmetricCipher>("SM4/CTR");
|
||||
|
||||
BenchMarkByName<SymmetricCipher>("Kalyna-128/CTR", 16, "Kalyna-128(128)/CTR (128-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("Kalyna-128/CTR", 32, "Kalyna-128(256)/CTR (256-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("Kalyna-256/CTR", 32, "Kalyna-256(256)/CTR (256-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("Kalyna-256/CTR", 64, "Kalyna-256(512)/CTR (512-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("Kalyna-512/CTR", 64, "Kalyna-512(512)/CTR (512-bit key)");
|
||||
}
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: yellow;\">";
|
||||
{
|
||||
BenchMarkByName<SymmetricCipher>("CHAM-64/CTR", 16, "CHAM-64(128)/CTR (128-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("CHAM-128/CTR", 16, "CHAM-128(128)/CTR (128-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("CHAM-128/CTR", 32, "CHAM-128(256)/CTR (256-bit key)");
|
||||
|
||||
BenchMarkByName<SymmetricCipher>("LEA-128/CTR", 16, "LEA-128(128)/CTR (128-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("LEA-128/CTR", 24, "LEA-128(192)/CTR (192-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("LEA-128/CTR", 32, "LEA-128(256)/CTR (256-bit key)");
|
||||
|
||||
BenchMarkByName<SymmetricCipher>("SIMECK-32/CTR", 8, "SIMECK-32(64)/CTR (64-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("SIMECK-64/CTR", 16, "SIMECK-64(128)/CTR (128-bit key)");
|
||||
|
||||
BenchMarkByName<SymmetricCipher>("SIMON-64/CTR", 12, "SIMON-64(96)/CTR (96-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("SIMON-64/CTR", 16, "SIMON-64(128)/CTR (128-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("SIMON-128/CTR", 16, "SIMON-128(128)/CTR (128-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("SIMON-128/CTR", 24, "SIMON-128(192)/CTR (192-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("SIMON-128/CTR", 32, "SIMON-128(256)/CTR (256-bit key)");
|
||||
|
||||
BenchMarkByName<SymmetricCipher>("SPECK-64/CTR", 12, "SPECK-64(96)/CTR (96-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("SPECK-64/CTR", 16, "SPECK-64(128)/CTR (128-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("SPECK-128/CTR", 16, "SPECK-128(128)/CTR (128-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("SPECK-128/CTR", 24, "SPECK-128(192)/CTR (192-bit key)");
|
||||
BenchMarkByName<SymmetricCipher>("SPECK-128/CTR", 32, "SPECK-128(256)/CTR (256-bit key)");
|
||||
|
||||
BenchMarkByName<SymmetricCipher>("TEA/CTR");
|
||||
BenchMarkByName<SymmetricCipher>("XTEA/CTR");
|
||||
}
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: white;\">";
|
||||
{
|
||||
#if CRYPTOPP_AESNI_AVAILABLE
|
||||
if (HasCLMUL())
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM");
|
||||
else
|
||||
#elif CRYPTOPP_ARM_PMULL_AVAILABLE
|
||||
if (HasPMULL())
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM");
|
||||
else
|
||||
#elif CRYPTOPP_POWER8_VMULL_AVAILABLE
|
||||
if (HasPMULL())
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM");
|
||||
else
|
||||
#endif
|
||||
{
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM (2K tables)", MakeParameters(Name::TableSize(), 2048));
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM (64K tables)", MakeParameters(Name::TableSize(), 64 * 1024));
|
||||
}
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/CCM");
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/EAX");
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("ChaCha20/Poly1305");
|
||||
BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("XChaCha20/Poly1305");
|
||||
}
|
||||
|
||||
std::cout << "\n</TABLE>" << std::endl;
|
||||
}
|
||||
|
||||
NAMESPACE_END // Test
|
||||
NAMESPACE_END // CryptoPP
|
||||
+480
@@ -0,0 +1,480 @@
|
||||
// bench3.cpp - originally written and placed in the public domain by Wei Dai
|
||||
// CryptoPP::Test namespace added by JW in February 2017
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "bench.h"
|
||||
#include "validate.h"
|
||||
|
||||
#include "cpu.h"
|
||||
#include "factory.h"
|
||||
#include "algparam.h"
|
||||
#include "argnames.h"
|
||||
#include "smartptr.h"
|
||||
#include "stdcpp.h"
|
||||
|
||||
#include "pubkey.h"
|
||||
#include "gfpcrypt.h"
|
||||
#include "eccrypto.h"
|
||||
#include "pkcspad.h"
|
||||
|
||||
#include "files.h"
|
||||
#include "filters.h"
|
||||
#include "hex.h"
|
||||
#include "rsa.h"
|
||||
#include "nr.h"
|
||||
#include "dsa.h"
|
||||
#include "luc.h"
|
||||
#include "rw.h"
|
||||
#include "ecp.h"
|
||||
#include "ec2n.h"
|
||||
#include "asn.h"
|
||||
#include "dh.h"
|
||||
#include "mqv.h"
|
||||
#include "hmqv.h"
|
||||
#include "fhmqv.h"
|
||||
#include "xed25519.h"
|
||||
#include "xtrcrypt.h"
|
||||
#include "esign.h"
|
||||
#include "pssr.h"
|
||||
#include "oids.h"
|
||||
#include "randpool.h"
|
||||
#include "stdcpp.h"
|
||||
#include "hrtimer.h"
|
||||
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(disable: 4505 4355)
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
NAMESPACE_BEGIN(Test)
|
||||
|
||||
void BenchMarkEncryption(const char *name, PK_Encryptor &key, double timeTotal, bool pc = false)
|
||||
{
|
||||
unsigned int len = 16;
|
||||
SecByteBlock plaintext(len), ciphertext(key.CiphertextLength(len));
|
||||
Test::GlobalRNG().GenerateBlock(plaintext, len);
|
||||
|
||||
unsigned int i = 0;
|
||||
double timeTaken;
|
||||
|
||||
ThreadUserTimer timer;
|
||||
timer.StartTimer();
|
||||
|
||||
do
|
||||
{
|
||||
key.Encrypt(Test::GlobalRNG(), plaintext, len, ciphertext);
|
||||
++i; timeTaken = timer.ElapsedTimeAsDouble();
|
||||
}
|
||||
while (timeTaken < timeTotal);
|
||||
|
||||
std::string provider = key.AlgorithmProvider();
|
||||
OutputResultOperations(name, provider.c_str(), "Encryption", pc, i, timeTaken);
|
||||
|
||||
if (!pc && key.GetMaterial().SupportsPrecomputation())
|
||||
{
|
||||
key.AccessMaterial().Precompute(16);
|
||||
BenchMarkEncryption(name, key, timeTotal, true);
|
||||
}
|
||||
}
|
||||
|
||||
void BenchMarkDecryption(const char *name, PK_Decryptor &priv, PK_Encryptor &pub, double timeTotal)
|
||||
{
|
||||
unsigned int len = 16;
|
||||
SecByteBlock ciphertext(pub.CiphertextLength(len));
|
||||
SecByteBlock plaintext(pub.MaxPlaintextLength(ciphertext.size()));
|
||||
Test::GlobalRNG().GenerateBlock(plaintext, len);
|
||||
pub.Encrypt(Test::GlobalRNG(), plaintext, len, ciphertext);
|
||||
|
||||
unsigned int i = 0;
|
||||
double timeTaken;
|
||||
|
||||
ThreadUserTimer timer;
|
||||
timer.StartTimer();
|
||||
|
||||
do
|
||||
{
|
||||
priv.Decrypt(Test::GlobalRNG(), ciphertext, ciphertext.size(), plaintext);
|
||||
++i; timeTaken = timer.ElapsedTimeAsDouble();
|
||||
}
|
||||
while (timeTaken < timeTotal);
|
||||
|
||||
std::string provider = priv.AlgorithmProvider();
|
||||
OutputResultOperations(name, provider.c_str(), "Decryption", false, i, timeTaken);
|
||||
}
|
||||
|
||||
void BenchMarkSigning(const char *name, PK_Signer &key, double timeTotal, bool pc=false)
|
||||
{
|
||||
unsigned int len = 16;
|
||||
AlignedSecByteBlock message(len), signature(key.SignatureLength());
|
||||
Test::GlobalRNG().GenerateBlock(message, len);
|
||||
|
||||
unsigned int i = 0;
|
||||
double timeTaken;
|
||||
|
||||
ThreadUserTimer timer;
|
||||
timer.StartTimer();
|
||||
|
||||
do
|
||||
{
|
||||
(void)key.SignMessage(Test::GlobalRNG(), message, len, signature);
|
||||
++i; timeTaken = timer.ElapsedTimeAsDouble();
|
||||
}
|
||||
while (timeTaken < timeTotal);
|
||||
|
||||
std::string provider = key.AlgorithmProvider();
|
||||
OutputResultOperations(name, provider.c_str(), "Signature", pc, i, timeTaken);
|
||||
|
||||
if (!pc && key.GetMaterial().SupportsPrecomputation())
|
||||
{
|
||||
key.AccessMaterial().Precompute(16);
|
||||
BenchMarkSigning(name, key, timeTotal, true);
|
||||
}
|
||||
}
|
||||
|
||||
void BenchMarkVerification(const char *name, const PK_Signer &priv, PK_Verifier &pub, double timeTotal, bool pc=false)
|
||||
{
|
||||
unsigned int len = 16;
|
||||
AlignedSecByteBlock message(len), signature(pub.SignatureLength());
|
||||
Test::GlobalRNG().GenerateBlock(message, len);
|
||||
priv.SignMessage(Test::GlobalRNG(), message, len, signature);
|
||||
|
||||
unsigned int i = 0;
|
||||
double timeTaken;
|
||||
|
||||
ThreadUserTimer timer;
|
||||
timer.StartTimer();
|
||||
|
||||
do
|
||||
{
|
||||
(void)pub.VerifyMessage(message, len, signature, signature.size());
|
||||
++i; timeTaken = timer.ElapsedTimeAsDouble();
|
||||
}
|
||||
while (timeTaken < timeTotal);
|
||||
|
||||
std::string provider = pub.AlgorithmProvider();
|
||||
OutputResultOperations(name, provider.c_str(), "Verification", pc, i, timeTaken);
|
||||
|
||||
if (!pc && pub.GetMaterial().SupportsPrecomputation())
|
||||
{
|
||||
pub.AccessMaterial().Precompute(16);
|
||||
BenchMarkVerification(name, priv, pub, timeTotal, true);
|
||||
}
|
||||
}
|
||||
|
||||
void BenchMarkKeyGen(const char *name, SimpleKeyAgreementDomain &d, double timeTotal, bool pc=false)
|
||||
{
|
||||
SecByteBlock priv(d.PrivateKeyLength()), pub(d.PublicKeyLength());
|
||||
|
||||
unsigned int i = 0;
|
||||
double timeTaken;
|
||||
|
||||
ThreadUserTimer timer;
|
||||
timer.StartTimer();
|
||||
|
||||
do
|
||||
{
|
||||
d.GenerateKeyPair(Test::GlobalRNG(), priv, pub);
|
||||
++i; timeTaken = timer.ElapsedTimeAsDouble();
|
||||
}
|
||||
while (timeTaken < timeTotal);
|
||||
|
||||
std::string provider = d.AlgorithmProvider();
|
||||
OutputResultOperations(name, provider.c_str(), "Key-Pair Generation", pc, i, timeTaken);
|
||||
|
||||
if (!pc && d.GetMaterial().SupportsPrecomputation())
|
||||
{
|
||||
d.AccessMaterial().Precompute(16);
|
||||
BenchMarkKeyGen(name, d, timeTotal, true);
|
||||
}
|
||||
}
|
||||
|
||||
void BenchMarkKeyGen(const char *name, AuthenticatedKeyAgreementDomain &d, double timeTotal, bool pc=false)
|
||||
{
|
||||
SecByteBlock priv(d.EphemeralPrivateKeyLength()), pub(d.EphemeralPublicKeyLength());
|
||||
|
||||
unsigned int i = 0;
|
||||
double timeTaken;
|
||||
|
||||
ThreadUserTimer timer;
|
||||
timer.StartTimer();
|
||||
|
||||
do
|
||||
{
|
||||
d.GenerateEphemeralKeyPair(Test::GlobalRNG(), priv, pub);
|
||||
++i; timeTaken = timer.ElapsedTimeAsDouble();
|
||||
}
|
||||
while (timeTaken < timeTotal);
|
||||
|
||||
std::string provider = d.AlgorithmProvider();
|
||||
OutputResultOperations(name, provider.c_str(), "Key-Pair Generation", pc, i, timeTaken);
|
||||
|
||||
if (!pc && d.GetMaterial().SupportsPrecomputation())
|
||||
{
|
||||
d.AccessMaterial().Precompute(16);
|
||||
BenchMarkKeyGen(name, d, timeTotal, true);
|
||||
}
|
||||
}
|
||||
|
||||
void BenchMarkAgreement(const char *name, SimpleKeyAgreementDomain &d, double timeTotal, bool pc=false)
|
||||
{
|
||||
SecByteBlock priv1(d.PrivateKeyLength()), priv2(d.PrivateKeyLength());
|
||||
SecByteBlock pub1(d.PublicKeyLength()), pub2(d.PublicKeyLength());
|
||||
d.GenerateKeyPair(Test::GlobalRNG(), priv1, pub1);
|
||||
d.GenerateKeyPair(Test::GlobalRNG(), priv2, pub2);
|
||||
SecByteBlock val(d.AgreedValueLength());
|
||||
|
||||
unsigned int i = 0;
|
||||
double timeTaken;
|
||||
|
||||
ThreadUserTimer timer;
|
||||
timer.StartTimer();
|
||||
|
||||
do
|
||||
{
|
||||
d.Agree(val, priv1, pub2);
|
||||
d.Agree(val, priv2, pub1);
|
||||
i+=2; timeTaken = timer.ElapsedTimeAsDouble();
|
||||
}
|
||||
while (timeTaken < timeTotal);
|
||||
|
||||
std::string provider = d.AlgorithmProvider();
|
||||
OutputResultOperations(name, provider.c_str(), "Key Agreement", pc, i, timeTaken);
|
||||
}
|
||||
|
||||
void BenchMarkAgreement(const char *name, AuthenticatedKeyAgreementDomain &d, double timeTotal, bool pc=false)
|
||||
{
|
||||
SecByteBlock spriv1(d.StaticPrivateKeyLength()), spriv2(d.StaticPrivateKeyLength());
|
||||
SecByteBlock epriv1(d.EphemeralPrivateKeyLength()), epriv2(d.EphemeralPrivateKeyLength());
|
||||
SecByteBlock spub1(d.StaticPublicKeyLength()), spub2(d.StaticPublicKeyLength());
|
||||
SecByteBlock epub1(d.EphemeralPublicKeyLength()), epub2(d.EphemeralPublicKeyLength());
|
||||
d.GenerateStaticKeyPair(Test::GlobalRNG(), spriv1, spub1);
|
||||
d.GenerateStaticKeyPair(Test::GlobalRNG(), spriv2, spub2);
|
||||
d.GenerateEphemeralKeyPair(Test::GlobalRNG(), epriv1, epub1);
|
||||
d.GenerateEphemeralKeyPair(Test::GlobalRNG(), epriv2, epub2);
|
||||
SecByteBlock val(d.AgreedValueLength());
|
||||
|
||||
unsigned int i = 0;
|
||||
double timeTaken;
|
||||
|
||||
ThreadUserTimer timer;
|
||||
timer.StartTimer();
|
||||
|
||||
do
|
||||
{
|
||||
d.Agree(val, spriv1, epriv1, spub2, epub2);
|
||||
d.Agree(val, spriv2, epriv2, spub1, epub1);
|
||||
i+=2; timeTaken = timer.ElapsedTimeAsDouble();
|
||||
}
|
||||
while (timeTaken < timeTotal);
|
||||
|
||||
std::string provider = d.AlgorithmProvider();
|
||||
OutputResultOperations(name, provider.c_str(), "Key Agreement", pc, i, timeTaken);
|
||||
}
|
||||
|
||||
template <class SCHEME>
|
||||
void BenchMarkCrypto(const char *filename, const char *name, double timeTotal)
|
||||
{
|
||||
FileSource f(DataDir(filename).c_str(), true, new HexDecoder);
|
||||
typename SCHEME::Decryptor priv(f);
|
||||
typename SCHEME::Encryptor pub(priv);
|
||||
BenchMarkEncryption(name, pub, timeTotal);
|
||||
BenchMarkDecryption(name, priv, pub, timeTotal);
|
||||
}
|
||||
|
||||
template <class SCHEME>
|
||||
void BenchMarkSignature(const char *filename, const char *name, double timeTotal)
|
||||
{
|
||||
FileSource f(DataDir(filename).c_str(), true, new HexDecoder);
|
||||
typename SCHEME::Signer priv(f);
|
||||
typename SCHEME::Verifier pub(priv);
|
||||
BenchMarkSigning(name, priv, timeTotal);
|
||||
BenchMarkVerification(name, priv, pub, timeTotal);
|
||||
}
|
||||
|
||||
template <class D>
|
||||
void BenchMarkKeyAgreement(const char *filename, const char *name, double timeTotal)
|
||||
{
|
||||
FileSource f(DataDir(filename).c_str(), true, new HexDecoder);
|
||||
D d(f);
|
||||
BenchMarkKeyGen(name, d, timeTotal);
|
||||
BenchMarkAgreement(name, d, timeTotal);
|
||||
}
|
||||
|
||||
void BenchmarkPublicKeyAlgorithms(double t, double hertz)
|
||||
{
|
||||
g_allocatedTime = t;
|
||||
g_hertz = hertz;
|
||||
|
||||
const char *mco;
|
||||
if (g_hertz > 1.0f)
|
||||
mco = "<TH>Megacycles/Operation";
|
||||
else
|
||||
mco = "";
|
||||
|
||||
std::cout << "\n<TABLE>";
|
||||
std::cout << "\n<COLGROUP><COL style=\"text-align: left;\"><COL style=";
|
||||
std::cout << "\"text-align: right;\"><COL style=\"text-align: right;\">";
|
||||
std::cout << "\n<THEAD style=\"background: #F0F0F0\">";
|
||||
std::cout << "\n<TR><TH>Operation<TH>Milliseconds/Operation" << mco;
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: white;\">";
|
||||
{
|
||||
BenchMarkCrypto<RSAES<OAEP<SHA1> > >("TestData/rsa1024.dat", "RSA 1024", t);
|
||||
BenchMarkCrypto<LUCES<OAEP<SHA1> > >("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: yellow;\">";
|
||||
{
|
||||
BenchMarkCrypto<RSAES<OAEP<SHA1> > >("TestData/rsa2048.dat", "RSA 2048", t);
|
||||
BenchMarkCrypto<LUCES<OAEP<SHA1> > >("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: white;\">";
|
||||
{
|
||||
BenchMarkSignature<RSASS<PSSR, SHA1> >("TestData/rsa1024.dat", "RSA 1024", t);
|
||||
BenchMarkSignature<RWSS<PSSR, SHA1> >("TestData/rw1024.dat", "RW 1024", t);
|
||||
BenchMarkSignature<LUCSS<PSSR, SHA1> >("TestData/luc1024.dat", "LUC 1024", t);
|
||||
BenchMarkSignature<NR<SHA1> >("TestData/nr1024.dat", "NR 1024", t);
|
||||
BenchMarkSignature<DSA>("TestData/dsa1024.dat", "DSA 1024", t);
|
||||
BenchMarkSignature<LUC_HMP<SHA1> >("TestData/lucs512.dat", "LUC-HMP 512", t);
|
||||
BenchMarkSignature<ESIGN<SHA1> >("TestData/esig1023.dat", "ESIGN 1023", t);
|
||||
BenchMarkSignature<ESIGN<SHA1> >("TestData/esig1536.dat", "ESIGN 1536", t);
|
||||
}
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: yellow;\">";
|
||||
{
|
||||
BenchMarkSignature<RSASS<PSSR, SHA1> >("TestData/rsa2048.dat", "RSA 2048", t);
|
||||
BenchMarkSignature<RWSS<PSSR, SHA1> >("TestData/rw2048.dat", "RW 2048", t);
|
||||
BenchMarkSignature<LUCSS<PSSR, SHA1> >("TestData/luc2048.dat", "LUC 2048", t);
|
||||
BenchMarkSignature<NR<SHA1> >("TestData/nr2048.dat", "NR 2048", t);
|
||||
BenchMarkSignature<LUC_HMP<SHA1> >("TestData/lucs1024.dat", "LUC-HMP 1024", t);
|
||||
BenchMarkSignature<ESIGN<SHA1> >("TestData/esig2046.dat", "ESIGN 2046", t);
|
||||
}
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: white;\">";
|
||||
{
|
||||
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);
|
||||
BenchMarkKeyAgreement<DH>("TestData/dh2048.dat", "DH 2048", t);
|
||||
BenchMarkKeyAgreement<LUC_DH>("TestData/lucd512.dat", "LUCDIF 512", t);
|
||||
BenchMarkKeyAgreement<LUC_DH>("TestData/lucd1024.dat", "LUCDIF 1024", t);
|
||||
BenchMarkKeyAgreement<MQV>("TestData/mqv1024.dat", "MQV 1024", t);
|
||||
BenchMarkKeyAgreement<MQV>("TestData/mqv2048.dat", "MQV 2048", t);
|
||||
}
|
||||
|
||||
std::cout << "\n</TABLE>" << std::endl;
|
||||
}
|
||||
|
||||
void BenchmarkEllipticCurveAlgorithms(double t, double hertz)
|
||||
{
|
||||
g_allocatedTime = t;
|
||||
g_hertz = hertz;
|
||||
|
||||
const char *mco;
|
||||
if (g_hertz > 1.0f)
|
||||
mco = "<TH>Megacycles/Operation";
|
||||
else
|
||||
mco = "";
|
||||
|
||||
std::cout << "\n<TABLE>";
|
||||
std::cout << "\n<COLGROUP><COL style=\"text-align: left;\"><COL style=";
|
||||
std::cout << "\"text-align: right;\"><COL style=\"text-align: right;\">";
|
||||
std::cout << "\n<THEAD style=\"background: #F0F0F0\">";
|
||||
std::cout << "\n<TR><TH>Operation<TH>Milliseconds/Operation" << mco;
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: white;\">";
|
||||
{
|
||||
ed25519::Signer sign(Test::GlobalRNG());
|
||||
ed25519::Verifier verify(sign);
|
||||
x25519 agree(Test::GlobalRNG());
|
||||
|
||||
BenchMarkSigning("ed25519", sign, t);
|
||||
BenchMarkVerification("ed25519", sign, verify, t);
|
||||
BenchMarkKeyGen("x25519", agree, t);
|
||||
BenchMarkAgreement("x25519", agree, t);
|
||||
}
|
||||
|
||||
#if 0
|
||||
std::cout << "\n<TBODY style=\"background: yellow;\">";
|
||||
{
|
||||
BenchMarkKeyAgreement<ECMQV160>("TestData/mqv160.dat", "MQV P-160", t);
|
||||
BenchMarkKeyAgreement<ECMQV256>("TestData/mqv256.dat", "MQV P-256", t);
|
||||
BenchMarkKeyAgreement<ECMQV384>("TestData/mqv384.dat", "MQV P-384", t);
|
||||
BenchMarkKeyAgreement<ECMQV512>("TestData/mqv512.dat", "MQV P-521", t);
|
||||
|
||||
BenchMarkKeyAgreement<ECHMQV160>("TestData/hmqv160.dat", "HMQV P-160", t);
|
||||
BenchMarkKeyAgreement<ECHMQV256>("TestData/hmqv256.dat", "HMQV P-256", t);
|
||||
BenchMarkKeyAgreement<ECHMQV384>("TestData/hmqv384.dat", "HMQV P-384", t);
|
||||
BenchMarkKeyAgreement<ECHMQV512>("TestData/hmqv512.dat", "HMQV P-521", t);
|
||||
|
||||
BenchMarkKeyAgreement<ECFHMQV160>("TestData/fhmqv160.dat", "FHMQV P-160", t);
|
||||
BenchMarkKeyAgreement<ECFHMQV256>("TestData/fhmqv256.dat", "FHMQV P-256", t);
|
||||
BenchMarkKeyAgreement<ECFHMQV384>("TestData/fhmqv384.dat", "FHMQV P-384", t);
|
||||
BenchMarkKeyAgreement<ECFHMQV512>("TestData/fhmqv512.dat", "FHMQV P-521", t);
|
||||
}
|
||||
#endif
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: yellow;\">";
|
||||
{
|
||||
ECIES<ECP>::Decryptor cpriv(Test::GlobalRNG(), ASN1::secp256k1());
|
||||
ECIES<ECP>::Encryptor cpub(cpriv);
|
||||
ECDSA<ECP, SHA1>::Signer spriv(cpriv);
|
||||
ECDSA<ECP, SHA1>::Verifier spub(spriv);
|
||||
ECDSA_RFC6979<ECP, SHA1>::Signer spriv2(cpriv);
|
||||
ECDSA_RFC6979<ECP, SHA1>::Verifier spub2(spriv);
|
||||
ECGDSA<ECP, SHA1>::Signer spriv3(Test::GlobalRNG(), ASN1::secp256k1());
|
||||
ECGDSA<ECP, SHA1>::Verifier spub3(spriv3);
|
||||
ECDH<ECP>::Domain ecdhc(ASN1::secp256k1());
|
||||
ECMQV<ECP>::Domain ecmqvc(ASN1::secp256k1());
|
||||
|
||||
BenchMarkEncryption("ECIES over GF(p) 256", cpub, t);
|
||||
BenchMarkDecryption("ECIES over GF(p) 256", cpriv, cpub, t);
|
||||
BenchMarkSigning("ECDSA over GF(p) 256", spriv, t);
|
||||
BenchMarkVerification("ECDSA over GF(p) 256", spriv, spub, t);
|
||||
BenchMarkSigning("ECDSA-RFC6979 over GF(p) 256", spriv2, t);
|
||||
BenchMarkVerification("ECDSA-RFC6979 over GF(p) 256", spriv2, spub2, t);
|
||||
BenchMarkSigning("ECGDSA over GF(p) 256", spriv3, t);
|
||||
BenchMarkVerification("ECGDSA over GF(p) 256", spriv3, spub3, t);
|
||||
BenchMarkKeyGen("ECDHC over GF(p) 256", ecdhc, t);
|
||||
BenchMarkAgreement("ECDHC over GF(p) 256", ecdhc, t);
|
||||
BenchMarkKeyGen("ECMQVC over GF(p) 256", ecmqvc, t);
|
||||
BenchMarkAgreement("ECMQVC over GF(p) 256", ecmqvc, t);
|
||||
}
|
||||
|
||||
std::cout << "\n<TBODY style=\"background: white;\">";
|
||||
{
|
||||
ECIES<EC2N>::Decryptor cpriv(Test::GlobalRNG(), ASN1::sect233r1());
|
||||
ECIES<EC2N>::Encryptor cpub(cpriv);
|
||||
ECDSA<EC2N, SHA1>::Signer spriv(cpriv);
|
||||
ECDSA<EC2N, SHA1>::Verifier spub(spriv);
|
||||
ECDSA_RFC6979<EC2N, SHA1>::Signer spriv2(cpriv);
|
||||
ECDSA_RFC6979<EC2N, SHA1>::Verifier spub2(spriv);
|
||||
ECGDSA<EC2N, SHA1>::Signer spriv3(Test::GlobalRNG(), ASN1::sect233r1());
|
||||
ECGDSA<EC2N, SHA1>::Verifier spub3(spriv3);
|
||||
ECDH<EC2N>::Domain ecdhc(ASN1::sect233r1());
|
||||
ECMQV<EC2N>::Domain ecmqvc(ASN1::sect233r1());
|
||||
|
||||
BenchMarkEncryption("ECIES over GF(2^n) 233", cpub, t);
|
||||
BenchMarkDecryption("ECIES over GF(2^n) 233", cpriv, cpub, t);
|
||||
BenchMarkSigning("ECDSA over GF(2^n) 233", spriv, t);
|
||||
BenchMarkVerification("ECDSA over GF(2^n) 233", spriv, spub, t);
|
||||
BenchMarkSigning("ECDSA-RFC6979 over GF(2^n) 233", spriv2, t);
|
||||
BenchMarkVerification("ECDSA-RFC6979 over GF(2^n) 233", spriv2, spub2, t);
|
||||
BenchMarkSigning("ECGDSA over GF(2^n) 233", spriv3, t);
|
||||
BenchMarkVerification("ECGDSA over GF(2^n) 233", spriv3, spub3, t);
|
||||
BenchMarkKeyGen("ECDHC over GF(2^n) 233", ecdhc, t);
|
||||
BenchMarkAgreement("ECDHC over GF(2^n) 233", ecdhc, t);
|
||||
BenchMarkKeyGen("ECMQVC over GF(2^n) 233", ecmqvc, t);
|
||||
BenchMarkAgreement("ECMQVC over GF(2^n) 233", ecmqvc, t);
|
||||
}
|
||||
|
||||
std::cout << "\n</TABLE>" << std::endl;
|
||||
}
|
||||
|
||||
NAMESPACE_END // Test
|
||||
NAMESPACE_END // CryptoPP
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
#include "pch.h"
|
||||
#include "blowfish.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
const word32 Blowfish::Base::p_init[Blowfish::ROUNDS+2] =
|
||||
{
|
||||
608135816U, 2242054355U, 320440878U, 57701188U,
|
||||
2752067618U, 698298832U, 137296536U, 3964562569U,
|
||||
1160258022U, 953160567U, 3193202383U, 887688300U,
|
||||
3232508343U, 3380367581U, 1065670069U, 3041331479U,
|
||||
2450970073U, 2306472731U
|
||||
} ;
|
||||
|
||||
const word32 Blowfish::Base::s_init[4*256] = {
|
||||
3509652390U, 2564797868U, 805139163U, 3491422135U,
|
||||
3101798381U, 1780907670U, 3128725573U, 4046225305U,
|
||||
614570311U, 3012652279U, 134345442U, 2240740374U,
|
||||
1667834072U, 1901547113U, 2757295779U, 4103290238U,
|
||||
227898511U, 1921955416U, 1904987480U, 2182433518U,
|
||||
2069144605U, 3260701109U, 2620446009U, 720527379U,
|
||||
3318853667U, 677414384U, 3393288472U, 3101374703U,
|
||||
2390351024U, 1614419982U, 1822297739U, 2954791486U,
|
||||
3608508353U, 3174124327U, 2024746970U, 1432378464U,
|
||||
3864339955U, 2857741204U, 1464375394U, 1676153920U,
|
||||
1439316330U, 715854006U, 3033291828U, 289532110U,
|
||||
2706671279U, 2087905683U, 3018724369U, 1668267050U,
|
||||
732546397U, 1947742710U, 3462151702U, 2609353502U,
|
||||
2950085171U, 1814351708U, 2050118529U, 680887927U,
|
||||
999245976U, 1800124847U, 3300911131U, 1713906067U,
|
||||
1641548236U, 4213287313U, 1216130144U, 1575780402U,
|
||||
4018429277U, 3917837745U, 3693486850U, 3949271944U,
|
||||
596196993U, 3549867205U, 258830323U, 2213823033U,
|
||||
772490370U, 2760122372U, 1774776394U, 2652871518U,
|
||||
566650946U, 4142492826U, 1728879713U, 2882767088U,
|
||||
1783734482U, 3629395816U, 2517608232U, 2874225571U,
|
||||
1861159788U, 326777828U, 3124490320U, 2130389656U,
|
||||
2716951837U, 967770486U, 1724537150U, 2185432712U,
|
||||
2364442137U, 1164943284U, 2105845187U, 998989502U,
|
||||
3765401048U, 2244026483U, 1075463327U, 1455516326U,
|
||||
1322494562U, 910128902U, 469688178U, 1117454909U,
|
||||
936433444U, 3490320968U, 3675253459U, 1240580251U,
|
||||
122909385U, 2157517691U, 634681816U, 4142456567U,
|
||||
3825094682U, 3061402683U, 2540495037U, 79693498U,
|
||||
3249098678U, 1084186820U, 1583128258U, 426386531U,
|
||||
1761308591U, 1047286709U, 322548459U, 995290223U,
|
||||
1845252383U, 2603652396U, 3431023940U, 2942221577U,
|
||||
3202600964U, 3727903485U, 1712269319U, 422464435U,
|
||||
3234572375U, 1170764815U, 3523960633U, 3117677531U,
|
||||
1434042557U, 442511882U, 3600875718U, 1076654713U,
|
||||
1738483198U, 4213154764U, 2393238008U, 3677496056U,
|
||||
1014306527U, 4251020053U, 793779912U, 2902807211U,
|
||||
842905082U, 4246964064U, 1395751752U, 1040244610U,
|
||||
2656851899U, 3396308128U, 445077038U, 3742853595U,
|
||||
3577915638U, 679411651U, 2892444358U, 2354009459U,
|
||||
1767581616U, 3150600392U, 3791627101U, 3102740896U,
|
||||
284835224U, 4246832056U, 1258075500U, 768725851U,
|
||||
2589189241U, 3069724005U, 3532540348U, 1274779536U,
|
||||
3789419226U, 2764799539U, 1660621633U, 3471099624U,
|
||||
4011903706U, 913787905U, 3497959166U, 737222580U,
|
||||
2514213453U, 2928710040U, 3937242737U, 1804850592U,
|
||||
3499020752U, 2949064160U, 2386320175U, 2390070455U,
|
||||
2415321851U, 4061277028U, 2290661394U, 2416832540U,
|
||||
1336762016U, 1754252060U, 3520065937U, 3014181293U,
|
||||
791618072U, 3188594551U, 3933548030U, 2332172193U,
|
||||
3852520463U, 3043980520U, 413987798U, 3465142937U,
|
||||
3030929376U, 4245938359U, 2093235073U, 3534596313U,
|
||||
375366246U, 2157278981U, 2479649556U, 555357303U,
|
||||
3870105701U, 2008414854U, 3344188149U, 4221384143U,
|
||||
3956125452U, 2067696032U, 3594591187U, 2921233993U,
|
||||
2428461U, 544322398U, 577241275U, 1471733935U,
|
||||
610547355U, 4027169054U, 1432588573U, 1507829418U,
|
||||
2025931657U, 3646575487U, 545086370U, 48609733U,
|
||||
2200306550U, 1653985193U, 298326376U, 1316178497U,
|
||||
3007786442U, 2064951626U, 458293330U, 2589141269U,
|
||||
3591329599U, 3164325604U, 727753846U, 2179363840U,
|
||||
146436021U, 1461446943U, 4069977195U, 705550613U,
|
||||
3059967265U, 3887724982U, 4281599278U, 3313849956U,
|
||||
1404054877U, 2845806497U, 146425753U, 1854211946U,
|
||||
|
||||
1266315497U, 3048417604U, 3681880366U, 3289982499U,
|
||||
2909710000U, 1235738493U, 2632868024U, 2414719590U,
|
||||
3970600049U, 1771706367U, 1449415276U, 3266420449U,
|
||||
422970021U, 1963543593U, 2690192192U, 3826793022U,
|
||||
1062508698U, 1531092325U, 1804592342U, 2583117782U,
|
||||
2714934279U, 4024971509U, 1294809318U, 4028980673U,
|
||||
1289560198U, 2221992742U, 1669523910U, 35572830U,
|
||||
157838143U, 1052438473U, 1016535060U, 1802137761U,
|
||||
1753167236U, 1386275462U, 3080475397U, 2857371447U,
|
||||
1040679964U, 2145300060U, 2390574316U, 1461121720U,
|
||||
2956646967U, 4031777805U, 4028374788U, 33600511U,
|
||||
2920084762U, 1018524850U, 629373528U, 3691585981U,
|
||||
3515945977U, 2091462646U, 2486323059U, 586499841U,
|
||||
988145025U, 935516892U, 3367335476U, 2599673255U,
|
||||
2839830854U, 265290510U, 3972581182U, 2759138881U,
|
||||
3795373465U, 1005194799U, 847297441U, 406762289U,
|
||||
1314163512U, 1332590856U, 1866599683U, 4127851711U,
|
||||
750260880U, 613907577U, 1450815602U, 3165620655U,
|
||||
3734664991U, 3650291728U, 3012275730U, 3704569646U,
|
||||
1427272223U, 778793252U, 1343938022U, 2676280711U,
|
||||
2052605720U, 1946737175U, 3164576444U, 3914038668U,
|
||||
3967478842U, 3682934266U, 1661551462U, 3294938066U,
|
||||
4011595847U, 840292616U, 3712170807U, 616741398U,
|
||||
312560963U, 711312465U, 1351876610U, 322626781U,
|
||||
1910503582U, 271666773U, 2175563734U, 1594956187U,
|
||||
70604529U, 3617834859U, 1007753275U, 1495573769U,
|
||||
4069517037U, 2549218298U, 2663038764U, 504708206U,
|
||||
2263041392U, 3941167025U, 2249088522U, 1514023603U,
|
||||
1998579484U, 1312622330U, 694541497U, 2582060303U,
|
||||
2151582166U, 1382467621U, 776784248U, 2618340202U,
|
||||
3323268794U, 2497899128U, 2784771155U, 503983604U,
|
||||
4076293799U, 907881277U, 423175695U, 432175456U,
|
||||
1378068232U, 4145222326U, 3954048622U, 3938656102U,
|
||||
3820766613U, 2793130115U, 2977904593U, 26017576U,
|
||||
3274890735U, 3194772133U, 1700274565U, 1756076034U,
|
||||
4006520079U, 3677328699U, 720338349U, 1533947780U,
|
||||
354530856U, 688349552U, 3973924725U, 1637815568U,
|
||||
332179504U, 3949051286U, 53804574U, 2852348879U,
|
||||
3044236432U, 1282449977U, 3583942155U, 3416972820U,
|
||||
4006381244U, 1617046695U, 2628476075U, 3002303598U,
|
||||
1686838959U, 431878346U, 2686675385U, 1700445008U,
|
||||
1080580658U, 1009431731U, 832498133U, 3223435511U,
|
||||
2605976345U, 2271191193U, 2516031870U, 1648197032U,
|
||||
4164389018U, 2548247927U, 300782431U, 375919233U,
|
||||
238389289U, 3353747414U, 2531188641U, 2019080857U,
|
||||
1475708069U, 455242339U, 2609103871U, 448939670U,
|
||||
3451063019U, 1395535956U, 2413381860U, 1841049896U,
|
||||
1491858159U, 885456874U, 4264095073U, 4001119347U,
|
||||
1565136089U, 3898914787U, 1108368660U, 540939232U,
|
||||
1173283510U, 2745871338U, 3681308437U, 4207628240U,
|
||||
3343053890U, 4016749493U, 1699691293U, 1103962373U,
|
||||
3625875870U, 2256883143U, 3830138730U, 1031889488U,
|
||||
3479347698U, 1535977030U, 4236805024U, 3251091107U,
|
||||
2132092099U, 1774941330U, 1199868427U, 1452454533U,
|
||||
157007616U, 2904115357U, 342012276U, 595725824U,
|
||||
1480756522U, 206960106U, 497939518U, 591360097U,
|
||||
863170706U, 2375253569U, 3596610801U, 1814182875U,
|
||||
2094937945U, 3421402208U, 1082520231U, 3463918190U,
|
||||
2785509508U, 435703966U, 3908032597U, 1641649973U,
|
||||
2842273706U, 3305899714U, 1510255612U, 2148256476U,
|
||||
2655287854U, 3276092548U, 4258621189U, 236887753U,
|
||||
3681803219U, 274041037U, 1734335097U, 3815195456U,
|
||||
3317970021U, 1899903192U, 1026095262U, 4050517792U,
|
||||
356393447U, 2410691914U, 3873677099U, 3682840055U,
|
||||
|
||||
3913112168U, 2491498743U, 4132185628U, 2489919796U,
|
||||
1091903735U, 1979897079U, 3170134830U, 3567386728U,
|
||||
3557303409U, 857797738U, 1136121015U, 1342202287U,
|
||||
507115054U, 2535736646U, 337727348U, 3213592640U,
|
||||
1301675037U, 2528481711U, 1895095763U, 1721773893U,
|
||||
3216771564U, 62756741U, 2142006736U, 835421444U,
|
||||
2531993523U, 1442658625U, 3659876326U, 2882144922U,
|
||||
676362277U, 1392781812U, 170690266U, 3921047035U,
|
||||
1759253602U, 3611846912U, 1745797284U, 664899054U,
|
||||
1329594018U, 3901205900U, 3045908486U, 2062866102U,
|
||||
2865634940U, 3543621612U, 3464012697U, 1080764994U,
|
||||
553557557U, 3656615353U, 3996768171U, 991055499U,
|
||||
499776247U, 1265440854U, 648242737U, 3940784050U,
|
||||
980351604U, 3713745714U, 1749149687U, 3396870395U,
|
||||
4211799374U, 3640570775U, 1161844396U, 3125318951U,
|
||||
1431517754U, 545492359U, 4268468663U, 3499529547U,
|
||||
1437099964U, 2702547544U, 3433638243U, 2581715763U,
|
||||
2787789398U, 1060185593U, 1593081372U, 2418618748U,
|
||||
4260947970U, 69676912U, 2159744348U, 86519011U,
|
||||
2512459080U, 3838209314U, 1220612927U, 3339683548U,
|
||||
133810670U, 1090789135U, 1078426020U, 1569222167U,
|
||||
845107691U, 3583754449U, 4072456591U, 1091646820U,
|
||||
628848692U, 1613405280U, 3757631651U, 526609435U,
|
||||
236106946U, 48312990U, 2942717905U, 3402727701U,
|
||||
1797494240U, 859738849U, 992217954U, 4005476642U,
|
||||
2243076622U, 3870952857U, 3732016268U, 765654824U,
|
||||
3490871365U, 2511836413U, 1685915746U, 3888969200U,
|
||||
1414112111U, 2273134842U, 3281911079U, 4080962846U,
|
||||
172450625U, 2569994100U, 980381355U, 4109958455U,
|
||||
2819808352U, 2716589560U, 2568741196U, 3681446669U,
|
||||
3329971472U, 1835478071U, 660984891U, 3704678404U,
|
||||
4045999559U, 3422617507U, 3040415634U, 1762651403U,
|
||||
1719377915U, 3470491036U, 2693910283U, 3642056355U,
|
||||
3138596744U, 1364962596U, 2073328063U, 1983633131U,
|
||||
926494387U, 3423689081U, 2150032023U, 4096667949U,
|
||||
1749200295U, 3328846651U, 309677260U, 2016342300U,
|
||||
1779581495U, 3079819751U, 111262694U, 1274766160U,
|
||||
443224088U, 298511866U, 1025883608U, 3806446537U,
|
||||
1145181785U, 168956806U, 3641502830U, 3584813610U,
|
||||
1689216846U, 3666258015U, 3200248200U, 1692713982U,
|
||||
2646376535U, 4042768518U, 1618508792U, 1610833997U,
|
||||
3523052358U, 4130873264U, 2001055236U, 3610705100U,
|
||||
2202168115U, 4028541809U, 2961195399U, 1006657119U,
|
||||
2006996926U, 3186142756U, 1430667929U, 3210227297U,
|
||||
1314452623U, 4074634658U, 4101304120U, 2273951170U,
|
||||
1399257539U, 3367210612U, 3027628629U, 1190975929U,
|
||||
2062231137U, 2333990788U, 2221543033U, 2438960610U,
|
||||
1181637006U, 548689776U, 2362791313U, 3372408396U,
|
||||
3104550113U, 3145860560U, 296247880U, 1970579870U,
|
||||
3078560182U, 3769228297U, 1714227617U, 3291629107U,
|
||||
3898220290U, 166772364U, 1251581989U, 493813264U,
|
||||
448347421U, 195405023U, 2709975567U, 677966185U,
|
||||
3703036547U, 1463355134U, 2715995803U, 1338867538U,
|
||||
1343315457U, 2802222074U, 2684532164U, 233230375U,
|
||||
2599980071U, 2000651841U, 3277868038U, 1638401717U,
|
||||
4028070440U, 3237316320U, 6314154U, 819756386U,
|
||||
300326615U, 590932579U, 1405279636U, 3267499572U,
|
||||
3150704214U, 2428286686U, 3959192993U, 3461946742U,
|
||||
1862657033U, 1266418056U, 963775037U, 2089974820U,
|
||||
2263052895U, 1917689273U, 448879540U, 3550394620U,
|
||||
3981727096U, 150775221U, 3627908307U, 1303187396U,
|
||||
508620638U, 2975983352U, 2726630617U, 1817252668U,
|
||||
1876281319U, 1457606340U, 908771278U, 3720792119U,
|
||||
3617206836U, 2455994898U, 1729034894U, 1080033504U,
|
||||
|
||||
976866871U, 3556439503U, 2881648439U, 1522871579U,
|
||||
1555064734U, 1336096578U, 3548522304U, 2579274686U,
|
||||
3574697629U, 3205460757U, 3593280638U, 3338716283U,
|
||||
3079412587U, 564236357U, 2993598910U, 1781952180U,
|
||||
1464380207U, 3163844217U, 3332601554U, 1699332808U,
|
||||
1393555694U, 1183702653U, 3581086237U, 1288719814U,
|
||||
691649499U, 2847557200U, 2895455976U, 3193889540U,
|
||||
2717570544U, 1781354906U, 1676643554U, 2592534050U,
|
||||
3230253752U, 1126444790U, 2770207658U, 2633158820U,
|
||||
2210423226U, 2615765581U, 2414155088U, 3127139286U,
|
||||
673620729U, 2805611233U, 1269405062U, 4015350505U,
|
||||
3341807571U, 4149409754U, 1057255273U, 2012875353U,
|
||||
2162469141U, 2276492801U, 2601117357U, 993977747U,
|
||||
3918593370U, 2654263191U, 753973209U, 36408145U,
|
||||
2530585658U, 25011837U, 3520020182U, 2088578344U,
|
||||
530523599U, 2918365339U, 1524020338U, 1518925132U,
|
||||
3760827505U, 3759777254U, 1202760957U, 3985898139U,
|
||||
3906192525U, 674977740U, 4174734889U, 2031300136U,
|
||||
2019492241U, 3983892565U, 4153806404U, 3822280332U,
|
||||
352677332U, 2297720250U, 60907813U, 90501309U,
|
||||
3286998549U, 1016092578U, 2535922412U, 2839152426U,
|
||||
457141659U, 509813237U, 4120667899U, 652014361U,
|
||||
1966332200U, 2975202805U, 55981186U, 2327461051U,
|
||||
676427537U, 3255491064U, 2882294119U, 3433927263U,
|
||||
1307055953U, 942726286U, 933058658U, 2468411793U,
|
||||
3933900994U, 4215176142U, 1361170020U, 2001714738U,
|
||||
2830558078U, 3274259782U, 1222529897U, 1679025792U,
|
||||
2729314320U, 3714953764U, 1770335741U, 151462246U,
|
||||
3013232138U, 1682292957U, 1483529935U, 471910574U,
|
||||
1539241949U, 458788160U, 3436315007U, 1807016891U,
|
||||
3718408830U, 978976581U, 1043663428U, 3165965781U,
|
||||
1927990952U, 4200891579U, 2372276910U, 3208408903U,
|
||||
3533431907U, 1412390302U, 2931980059U, 4132332400U,
|
||||
1947078029U, 3881505623U, 4168226417U, 2941484381U,
|
||||
1077988104U, 1320477388U, 886195818U, 18198404U,
|
||||
3786409000U, 2509781533U, 112762804U, 3463356488U,
|
||||
1866414978U, 891333506U, 18488651U, 661792760U,
|
||||
1628790961U, 3885187036U, 3141171499U, 876946877U,
|
||||
2693282273U, 1372485963U, 791857591U, 2686433993U,
|
||||
3759982718U, 3167212022U, 3472953795U, 2716379847U,
|
||||
445679433U, 3561995674U, 3504004811U, 3574258232U,
|
||||
54117162U, 3331405415U, 2381918588U, 3769707343U,
|
||||
4154350007U, 1140177722U, 4074052095U, 668550556U,
|
||||
3214352940U, 367459370U, 261225585U, 2610173221U,
|
||||
4209349473U, 3468074219U, 3265815641U, 314222801U,
|
||||
3066103646U, 3808782860U, 282218597U, 3406013506U,
|
||||
3773591054U, 379116347U, 1285071038U, 846784868U,
|
||||
2669647154U, 3771962079U, 3550491691U, 2305946142U,
|
||||
453669953U, 1268987020U, 3317592352U, 3279303384U,
|
||||
3744833421U, 2610507566U, 3859509063U, 266596637U,
|
||||
3847019092U, 517658769U, 3462560207U, 3443424879U,
|
||||
370717030U, 4247526661U, 2224018117U, 4143653529U,
|
||||
4112773975U, 2788324899U, 2477274417U, 1456262402U,
|
||||
2901442914U, 1517677493U, 1846949527U, 2295493580U,
|
||||
3734397586U, 2176403920U, 1280348187U, 1908823572U,
|
||||
3871786941U, 846861322U, 1172426758U, 3287448474U,
|
||||
3383383037U, 1655181056U, 3139813346U, 901632758U,
|
||||
1897031941U, 2986607138U, 3066810236U, 3447102507U,
|
||||
1393639104U, 373351379U, 950779232U, 625454576U,
|
||||
3124240540U, 4148612726U, 2007998917U, 544563296U,
|
||||
2244738638U, 2330496472U, 2058025392U, 1291430526U,
|
||||
424198748U, 50039436U, 29584100U, 3605783033U,
|
||||
2429876329U, 2791104160U, 1057563949U, 3255363231U,
|
||||
3075367218U, 3463963227U, 1469046755U, 985887462U
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
+797
@@ -0,0 +1,797 @@
|
||||
// blake2.cpp - written and placed in the public domain by Jeffrey Walton
|
||||
// and Zooko Wilcox-O'Hearn. Based on Aumasson, Neves,
|
||||
// Wilcox-O'Hearn and Winnerlein's reference BLAKE2
|
||||
// implementation at http://github.com/BLAKE2/BLAKE2.
|
||||
//
|
||||
// The BLAKE2b and BLAKE2s numbers are consistent with the BLAKE2 team's
|
||||
// numbers. However, we have an Altivec implementation of BLAKE2s,
|
||||
// and a POWER8 implementation of BLAKE2b (BLAKE2 team is missing them).
|
||||
// Altivec code is about 2x faster than C++ when using GCC 5.0 or
|
||||
// above. The POWER8 code is about 2.5x faster than C++ when using GCC 5.0
|
||||
// or above. If you use GCC 4.0 (PowerMac) or GCC 4.8 (GCC Compile Farm)
|
||||
// then the PowerPC code will be slower than C++. Be sure to use GCC 5.0
|
||||
// or above for PowerPC builds or disable Altivec for BLAKE2b and BLAKE2s
|
||||
// if using the old compilers.
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
#include "cryptlib.h"
|
||||
#include "argnames.h"
|
||||
#include "algparam.h"
|
||||
#include "blake2.h"
|
||||
#include "cpu.h"
|
||||
|
||||
// Uncomment for benchmarking C++ against SSE2 or NEON.
|
||||
// Do so in both blake2.cpp and blake2_simd.cpp.
|
||||
// #undef CRYPTOPP_SSE41_AVAILABLE
|
||||
// #undef CRYPTOPP_ARM_NEON_AVAILABLE
|
||||
// #undef CRYPTOPP_ALTIVEC_AVAILABLE
|
||||
// #undef CRYPTOPP_POWER8_AVAILABLE
|
||||
|
||||
// Disable NEON/ASIMD for Cortex-A53 and A57. The shifts are too slow and C/C++ is about
|
||||
// 3 cpb faster than NEON/ASIMD. Also see http://github.com/weidai11/cryptopp/issues/367.
|
||||
#if (defined(__aarch32__) || defined(__aarch64__)) && defined(CRYPTOPP_SLOW_ARMV8_SHIFT)
|
||||
# undef CRYPTOPP_ARM_NEON_AVAILABLE
|
||||
#endif
|
||||
|
||||
// BLAKE2s bug on AIX 7.1 (POWER7) with XLC 12.01
|
||||
// https://github.com/weidai11/cryptopp/issues/743
|
||||
#if defined(__xlC__) && (__xlC__ < 0x0d01)
|
||||
# define CRYPTOPP_DISABLE_ALTIVEC 1
|
||||
# undef CRYPTOPP_POWER7_AVAILABLE
|
||||
# undef CRYPTOPP_POWER8_AVAILABLE
|
||||
# undef CRYPTOPP_ALTIVEC_AVAILABLE
|
||||
#endif
|
||||
|
||||
// Can't use GetAlignmentOf<word64>() because of C++11 and constexpr
|
||||
// Can use 'const unsigned int' because of MSVC 2013
|
||||
#if (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64)
|
||||
# define ALIGN_SPEC32 16
|
||||
# define ALIGN_SPEC64 16
|
||||
#else
|
||||
# define ALIGN_SPEC32 4
|
||||
# define ALIGN_SPEC64 8
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
// Export the tables to the SIMD files
|
||||
extern const word32 BLAKE2S_IV[8];
|
||||
extern const word64 BLAKE2B_IV[8];
|
||||
|
||||
CRYPTOPP_ALIGN_DATA(ALIGN_SPEC32)
|
||||
const word32 BLAKE2S_IV[8] = {
|
||||
0x6A09E667UL, 0xBB67AE85UL, 0x3C6EF372UL, 0xA54FF53AUL,
|
||||
0x510E527FUL, 0x9B05688CUL, 0x1F83D9ABUL, 0x5BE0CD19UL
|
||||
};
|
||||
|
||||
CRYPTOPP_ALIGN_DATA(ALIGN_SPEC64)
|
||||
const word64 BLAKE2B_IV[8] = {
|
||||
W64LIT(0x6a09e667f3bcc908), W64LIT(0xbb67ae8584caa73b),
|
||||
W64LIT(0x3c6ef372fe94f82b), W64LIT(0xa54ff53a5f1d36f1),
|
||||
W64LIT(0x510e527fade682d1), W64LIT(0x9b05688c2b3e6c1f),
|
||||
W64LIT(0x1f83d9abfb41bd6b), W64LIT(0x5be0cd19137e2179)
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
ANONYMOUS_NAMESPACE_BEGIN
|
||||
|
||||
using CryptoPP::byte;
|
||||
using CryptoPP::word32;
|
||||
using CryptoPP::word64;
|
||||
using CryptoPP::rotrConstant;
|
||||
|
||||
CRYPTOPP_ALIGN_DATA(ALIGN_SPEC32)
|
||||
const byte BLAKE2S_SIGMA[10][16] = {
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
|
||||
{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
|
||||
{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
|
||||
{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
|
||||
{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
|
||||
{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
|
||||
{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
|
||||
{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
|
||||
{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
|
||||
{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13 , 0 },
|
||||
};
|
||||
|
||||
CRYPTOPP_ALIGN_DATA(ALIGN_SPEC32)
|
||||
const byte BLAKE2B_SIGMA[12][16] = {
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
|
||||
{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
|
||||
{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
|
||||
{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
|
||||
{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
|
||||
{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
|
||||
{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
|
||||
{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
|
||||
{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
|
||||
{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13 , 0 },
|
||||
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
|
||||
{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }
|
||||
};
|
||||
|
||||
template <unsigned int R, unsigned int N>
|
||||
inline void BLAKE2B_G(const word64 m[16], word64& a, word64& b, word64& c, word64& d)
|
||||
{
|
||||
a = a + b + m[BLAKE2B_SIGMA[R][2*N+0]];
|
||||
d = rotrConstant<32>(d ^ a);
|
||||
c = c + d;
|
||||
b = rotrConstant<24>(b ^ c);
|
||||
a = a + b + m[BLAKE2B_SIGMA[R][2*N+1]];
|
||||
d = rotrConstant<16>(d ^ a);
|
||||
c = c + d;
|
||||
b = rotrConstant<63>(b ^ c);
|
||||
}
|
||||
|
||||
template <unsigned int R>
|
||||
inline void BLAKE2B_ROUND(const word64 m[16], word64 v[16])
|
||||
{
|
||||
BLAKE2B_G<R,0>(m,v[ 0],v[ 4],v[ 8],v[12]);
|
||||
BLAKE2B_G<R,1>(m,v[ 1],v[ 5],v[ 9],v[13]);
|
||||
BLAKE2B_G<R,2>(m,v[ 2],v[ 6],v[10],v[14]);
|
||||
BLAKE2B_G<R,3>(m,v[ 3],v[ 7],v[11],v[15]);
|
||||
BLAKE2B_G<R,4>(m,v[ 0],v[ 5],v[10],v[15]);
|
||||
BLAKE2B_G<R,5>(m,v[ 1],v[ 6],v[11],v[12]);
|
||||
BLAKE2B_G<R,6>(m,v[ 2],v[ 7],v[ 8],v[13]);
|
||||
BLAKE2B_G<R,7>(m,v[ 3],v[ 4],v[ 9],v[14]);
|
||||
}
|
||||
|
||||
template <unsigned int R, unsigned int N>
|
||||
inline void BLAKE2S_G(const word32 m[16], word32& a, word32& b, word32& c, word32& d)
|
||||
{
|
||||
a = a + b + m[BLAKE2S_SIGMA[R][2*N+0]];
|
||||
d = rotrConstant<16>(d ^ a);
|
||||
c = c + d;
|
||||
b = rotrConstant<12>(b ^ c);
|
||||
a = a + b + m[BLAKE2S_SIGMA[R][2*N+1]];
|
||||
d = rotrConstant<8>(d ^ a);
|
||||
c = c + d;
|
||||
b = rotrConstant<7>(b ^ c);
|
||||
}
|
||||
|
||||
template <unsigned int R>
|
||||
inline void BLAKE2S_ROUND(const word32 m[16], word32 v[])
|
||||
{
|
||||
BLAKE2S_G<R,0>(m,v[ 0],v[ 4],v[ 8],v[12]);
|
||||
BLAKE2S_G<R,1>(m,v[ 1],v[ 5],v[ 9],v[13]);
|
||||
BLAKE2S_G<R,2>(m,v[ 2],v[ 6],v[10],v[14]);
|
||||
BLAKE2S_G<R,3>(m,v[ 3],v[ 7],v[11],v[15]);
|
||||
BLAKE2S_G<R,4>(m,v[ 0],v[ 5],v[10],v[15]);
|
||||
BLAKE2S_G<R,5>(m,v[ 1],v[ 6],v[11],v[12]);
|
||||
BLAKE2S_G<R,6>(m,v[ 2],v[ 7],v[ 8],v[13]);
|
||||
BLAKE2S_G<R,7>(m,v[ 3],v[ 4],v[ 9],v[14]);
|
||||
}
|
||||
|
||||
ANONYMOUS_NAMESPACE_END
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
void BLAKE2_Compress32_CXX(const byte* input, BLAKE2s_State& state);
|
||||
void BLAKE2_Compress64_CXX(const byte* input, BLAKE2b_State& state);
|
||||
|
||||
#if CRYPTOPP_SSE41_AVAILABLE
|
||||
extern void BLAKE2_Compress32_SSE4(const byte* input, BLAKE2s_State& state);
|
||||
extern void BLAKE2_Compress64_SSE4(const byte* input, BLAKE2b_State& state);
|
||||
#endif
|
||||
|
||||
#if CRYPTOPP_ARM_NEON_AVAILABLE
|
||||
extern void BLAKE2_Compress32_NEON(const byte* input, BLAKE2s_State& state);
|
||||
extern void BLAKE2_Compress64_NEON(const byte* input, BLAKE2b_State& state);
|
||||
#endif
|
||||
|
||||
#if CRYPTOPP_ALTIVEC_AVAILABLE
|
||||
extern void BLAKE2_Compress32_ALTIVEC(const byte* input, BLAKE2s_State& state);
|
||||
#endif
|
||||
|
||||
#if CRYPTOPP_POWER8_AVAILABLE
|
||||
extern void BLAKE2_Compress64_POWER8(const byte* input, BLAKE2b_State& state);
|
||||
#endif
|
||||
|
||||
unsigned int BLAKE2b::OptimalDataAlignment() const
|
||||
{
|
||||
#if defined(CRYPTOPP_SSE41_AVAILABLE)
|
||||
if (HasSSE41())
|
||||
return 16; // load __m128i
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
if (HasNEON())
|
||||
return 8; // load uint64x2_t
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_POWER8_AVAILABLE)
|
||||
if (HasPower8())
|
||||
return 16; // load vector long long
|
||||
else
|
||||
#endif
|
||||
return GetAlignmentOf<word64>();
|
||||
}
|
||||
|
||||
std::string BLAKE2b::AlgorithmProvider() const
|
||||
{
|
||||
#if defined(CRYPTOPP_SSE41_AVAILABLE)
|
||||
if (HasSSE41())
|
||||
return "SSE4.1";
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
if (HasNEON())
|
||||
return "NEON";
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_POWER8_AVAILABLE)
|
||||
if (HasPower8())
|
||||
return "Power8";
|
||||
else
|
||||
#endif
|
||||
return "C++";
|
||||
}
|
||||
|
||||
unsigned int BLAKE2s::OptimalDataAlignment() const
|
||||
{
|
||||
#if defined(CRYPTOPP_SSE41_AVAILABLE)
|
||||
if (HasSSE41())
|
||||
return 16; // load __m128i
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
if (HasNEON())
|
||||
return 4; // load uint32x4_t
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ALTIVEC_AVAILABLE)
|
||||
if (HasAltivec())
|
||||
return 16; // load vector unsigned int
|
||||
else
|
||||
#endif
|
||||
return GetAlignmentOf<word32>();
|
||||
}
|
||||
|
||||
std::string BLAKE2s::AlgorithmProvider() const
|
||||
{
|
||||
#if defined(CRYPTOPP_SSE41_AVAILABLE)
|
||||
if (HasSSE41())
|
||||
return "SSE4.1";
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
if (HasNEON())
|
||||
return "NEON";
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ALTIVEC_AVAILABLE)
|
||||
if (HasAltivec())
|
||||
return "Altivec";
|
||||
else
|
||||
#endif
|
||||
return "C++";
|
||||
}
|
||||
|
||||
void BLAKE2s_State::Reset()
|
||||
{
|
||||
std::memset(m_hft, 0x00, m_hft.SizeInBytes());
|
||||
m_len = 0;
|
||||
}
|
||||
|
||||
void BLAKE2b_State::Reset()
|
||||
{
|
||||
std::memset(m_hft, 0x00, m_hft.SizeInBytes());
|
||||
m_len = 0;
|
||||
}
|
||||
|
||||
BLAKE2s_ParameterBlock::BLAKE2s_ParameterBlock(size_t digestLen, size_t keyLen,
|
||||
const byte* saltStr, size_t saltLen,
|
||||
const byte* personalizationStr, size_t personalizationLen)
|
||||
{
|
||||
Reset(digestLen, keyLen);
|
||||
|
||||
if (saltStr && saltLen)
|
||||
memcpy_s(salt(), SALTSIZE, saltStr, saltLen);
|
||||
|
||||
if (personalizationStr && personalizationLen)
|
||||
memcpy_s(personalization(), PERSONALIZATIONSIZE, personalizationStr, personalizationLen);
|
||||
}
|
||||
|
||||
BLAKE2b_ParameterBlock::BLAKE2b_ParameterBlock(size_t digestLen, size_t keyLen,
|
||||
const byte* saltStr, size_t saltLen,
|
||||
const byte* personalizationStr, size_t personalizationLen)
|
||||
{
|
||||
Reset(digestLen, keyLen);
|
||||
|
||||
if (saltStr && saltLen)
|
||||
memcpy_s(salt(), SALTSIZE, saltStr, saltLen);
|
||||
|
||||
if (personalizationStr && personalizationLen)
|
||||
memcpy_s(personalization(), PERSONALIZATIONSIZE, personalizationStr, personalizationLen);
|
||||
}
|
||||
|
||||
void BLAKE2s_ParameterBlock::Reset(size_t digestLen, size_t keyLen)
|
||||
{
|
||||
std::memset(m_data, 0x00, m_data.size());
|
||||
m_data[DigestOff] = static_cast<byte>(digestLen);
|
||||
m_data[KeyOff] = static_cast<byte>(keyLen);
|
||||
m_data[FanoutOff] = m_data[DepthOff] = 1;
|
||||
}
|
||||
|
||||
void BLAKE2b_ParameterBlock::Reset(size_t digestLen, size_t keyLen)
|
||||
{
|
||||
std::memset(m_data, 0x00, m_data.size());
|
||||
m_data[DigestOff] = static_cast<byte>(digestLen);
|
||||
m_data[KeyOff] = static_cast<byte>(keyLen);
|
||||
m_data[FanoutOff] = m_data[DepthOff] = 1;
|
||||
}
|
||||
|
||||
BLAKE2s::BLAKE2s(bool treeMode, unsigned int digestSize)
|
||||
: m_digestSize(digestSize), m_keyLength(0), m_treeMode(treeMode)
|
||||
{
|
||||
CRYPTOPP_ASSERT(digestSize <= DIGESTSIZE);
|
||||
|
||||
UncheckedSetKey(NULLPTR, 0, MakeParameters
|
||||
(Name::DigestSize(), (int)digestSize)
|
||||
(Name::TreeMode(), treeMode));
|
||||
}
|
||||
|
||||
BLAKE2b::BLAKE2b(bool treeMode, unsigned int digestSize)
|
||||
: m_digestSize(digestSize), m_keyLength(0), m_treeMode(treeMode)
|
||||
{
|
||||
CRYPTOPP_ASSERT(digestSize <= DIGESTSIZE);
|
||||
|
||||
UncheckedSetKey(NULLPTR, 0, MakeParameters
|
||||
(Name::DigestSize(), (int)digestSize)
|
||||
(Name::TreeMode(), treeMode));
|
||||
}
|
||||
|
||||
BLAKE2s::BLAKE2s(unsigned int digestSize)
|
||||
: m_digestSize(digestSize), m_keyLength(0), m_treeMode(false)
|
||||
{
|
||||
CRYPTOPP_ASSERT(digestSize <= DIGESTSIZE);
|
||||
|
||||
UncheckedSetKey(NULLPTR, 0, MakeParameters
|
||||
(Name::DigestSize(), (int)digestSize)
|
||||
(Name::TreeMode(), false));
|
||||
}
|
||||
|
||||
BLAKE2b::BLAKE2b(unsigned int digestSize)
|
||||
: m_digestSize(digestSize), m_keyLength(0), m_treeMode(false)
|
||||
{
|
||||
CRYPTOPP_ASSERT(digestSize <= DIGESTSIZE);
|
||||
|
||||
UncheckedSetKey(NULLPTR, 0, MakeParameters
|
||||
(Name::DigestSize(), (int)digestSize)
|
||||
(Name::TreeMode(), false));
|
||||
}
|
||||
|
||||
BLAKE2s::BLAKE2s(const byte *key, size_t keyLength, const byte* salt, size_t saltLength,
|
||||
const byte* personalization, size_t personalizationLength, bool treeMode, unsigned int digestSize)
|
||||
: m_digestSize(digestSize), m_keyLength(static_cast<unsigned int>(keyLength)), m_treeMode(treeMode)
|
||||
{
|
||||
CRYPTOPP_ASSERT(keyLength <= MAX_KEYLENGTH);
|
||||
CRYPTOPP_ASSERT(digestSize <= DIGESTSIZE);
|
||||
CRYPTOPP_ASSERT(saltLength <= SALTSIZE);
|
||||
CRYPTOPP_ASSERT(personalizationLength <= PERSONALIZATIONSIZE);
|
||||
|
||||
UncheckedSetKey(key, static_cast<unsigned int>(keyLength), MakeParameters
|
||||
(Name::DigestSize(),(int)digestSize)
|
||||
(Name::TreeMode(),treeMode)
|
||||
(Name::Salt(), ConstByteArrayParameter(salt, saltLength))
|
||||
(Name::Personalization(), ConstByteArrayParameter(personalization, personalizationLength)));
|
||||
}
|
||||
|
||||
BLAKE2b::BLAKE2b(const byte *key, size_t keyLength, const byte* salt, size_t saltLength,
|
||||
const byte* personalization, size_t personalizationLength, bool treeMode, unsigned int digestSize)
|
||||
: m_digestSize(digestSize), m_keyLength(static_cast<unsigned int>(keyLength)), m_treeMode(treeMode)
|
||||
{
|
||||
CRYPTOPP_ASSERT(keyLength <= MAX_KEYLENGTH);
|
||||
CRYPTOPP_ASSERT(digestSize <= DIGESTSIZE);
|
||||
CRYPTOPP_ASSERT(saltLength <= SALTSIZE);
|
||||
CRYPTOPP_ASSERT(personalizationLength <= PERSONALIZATIONSIZE);
|
||||
|
||||
UncheckedSetKey(key, static_cast<unsigned int>(keyLength), MakeParameters
|
||||
(Name::DigestSize(),(int)digestSize)
|
||||
(Name::TreeMode(),treeMode)
|
||||
(Name::Salt(), ConstByteArrayParameter(salt, saltLength))
|
||||
(Name::Personalization(), ConstByteArrayParameter(personalization, personalizationLength)));
|
||||
}
|
||||
|
||||
void BLAKE2s::UncheckedSetKey(const byte *key, unsigned int length, const CryptoPP::NameValuePairs& params)
|
||||
{
|
||||
if (key && length)
|
||||
{
|
||||
m_key.New(BLOCKSIZE);
|
||||
std::memcpy(m_key, key, length);
|
||||
std::memset(m_key + length, 0x00, BLOCKSIZE - length);
|
||||
m_keyLength = length;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_key.resize(0);
|
||||
m_keyLength = 0;
|
||||
}
|
||||
|
||||
m_digestSize = static_cast<unsigned int>(params.GetIntValueWithDefault(
|
||||
Name::DigestSize(), static_cast<int>(m_digestSize)));
|
||||
|
||||
m_state.Reset();
|
||||
m_block.Reset(m_digestSize, m_keyLength);
|
||||
(void)params.GetValue(Name::TreeMode(), m_treeMode);
|
||||
|
||||
ConstByteArrayParameter t;
|
||||
if (params.GetValue(Name::Salt(), t) && t.begin() && t.size())
|
||||
memcpy_s(m_block.salt(), SALTSIZE, t.begin(), t.size());
|
||||
|
||||
if (params.GetValue(Name::Personalization(), t) && t.begin() && t.size())
|
||||
memcpy_s(m_block.personalization(), PERSONALIZATIONSIZE, t.begin(), t.size());
|
||||
|
||||
Restart();
|
||||
}
|
||||
|
||||
void BLAKE2b::UncheckedSetKey(const byte *key, unsigned int length, const CryptoPP::NameValuePairs& params)
|
||||
{
|
||||
if (key && length)
|
||||
{
|
||||
m_key.New(BLOCKSIZE);
|
||||
std::memcpy(m_key, key, length);
|
||||
std::memset(m_key + length, 0x00, BLOCKSIZE - length);
|
||||
m_keyLength = length;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_key.resize(0);
|
||||
m_keyLength = 0;
|
||||
}
|
||||
|
||||
m_digestSize = static_cast<unsigned int>(params.GetIntValueWithDefault(
|
||||
Name::DigestSize(), static_cast<int>(m_digestSize)));
|
||||
|
||||
m_state.Reset();
|
||||
m_block.Reset(m_digestSize, m_keyLength);
|
||||
(void)params.GetValue(Name::TreeMode(), m_treeMode);
|
||||
|
||||
ConstByteArrayParameter t;
|
||||
if (params.GetValue(Name::Salt(), t) && t.begin() && t.size())
|
||||
memcpy_s(m_block.salt(), SALTSIZE, t.begin(), t.size());
|
||||
|
||||
if (params.GetValue(Name::Personalization(), t) && t.begin() && t.size())
|
||||
memcpy_s(m_block.personalization(), PERSONALIZATIONSIZE, t.begin(), t.size());
|
||||
|
||||
Restart();
|
||||
}
|
||||
|
||||
void BLAKE2s::Restart()
|
||||
{
|
||||
static const word32 zero[2] = {0,0};
|
||||
Restart(m_block, zero);
|
||||
}
|
||||
|
||||
void BLAKE2b::Restart()
|
||||
{
|
||||
static const word64 zero[2] = {0,0};
|
||||
Restart(m_block, zero);
|
||||
}
|
||||
|
||||
void BLAKE2s::Restart(const BLAKE2s_ParameterBlock& block, const word32 counter[2])
|
||||
{
|
||||
// We take a counter as a parameter to allow customized state.
|
||||
m_state.Reset();
|
||||
if (counter != NULLPTR)
|
||||
{
|
||||
word32* t = m_state.t();
|
||||
t[0] = counter[0];
|
||||
t[1] = counter[1];
|
||||
}
|
||||
|
||||
// We take a parameter block as a parameter to allow customized state.
|
||||
// Avoid the copy of the parameter block when we are passing our own block.
|
||||
if (block.data() != m_block.data()) {
|
||||
std::memcpy(m_block.data(), block.data(), m_block.size());
|
||||
}
|
||||
|
||||
m_block.m_data[BLAKE2s_ParameterBlock::DigestOff] = (byte)m_digestSize;
|
||||
m_block.m_data[BLAKE2s_ParameterBlock::KeyOff] = (byte)m_keyLength;
|
||||
|
||||
const word32* iv = BLAKE2S_IV;
|
||||
PutBlock<word32, LittleEndian, true> put(m_block.data(), m_state.h());
|
||||
put(iv[0])(iv[1])(iv[2])(iv[3])(iv[4])(iv[5])(iv[6])(iv[7]);
|
||||
|
||||
// When BLAKE2 is keyed, the input stream is simply {key || 0 || message}.
|
||||
// The key is padded to a full Blocksize with 0. Key it during Restart to
|
||||
// avoid FirstPut and friends. Key size == 0 means no key.
|
||||
if (m_keyLength)
|
||||
Update(m_key, BLOCKSIZE);
|
||||
}
|
||||
|
||||
void BLAKE2b::Restart(const BLAKE2b_ParameterBlock& block, const word64 counter[2])
|
||||
{
|
||||
// We take a counter as a parameter to allow customized state.
|
||||
m_state.Reset();
|
||||
if (counter != NULLPTR)
|
||||
{
|
||||
word64* t = m_state.t();
|
||||
t[0] = counter[0];
|
||||
t[1] = counter[1];
|
||||
}
|
||||
|
||||
// We take a parameter block as a parameter to allow customized state.
|
||||
// Avoid the copy of the parameter block when we are passing our own block.
|
||||
if (block.data() != m_block.data()) {
|
||||
std::memcpy(m_block.data(), block.data(), m_block.size());
|
||||
}
|
||||
|
||||
m_block.m_data[BLAKE2b_ParameterBlock::DigestOff] = (byte)m_digestSize;
|
||||
m_block.m_data[BLAKE2b_ParameterBlock::KeyOff] = (byte)m_keyLength;
|
||||
|
||||
const word64* iv = BLAKE2B_IV;
|
||||
PutBlock<word64, LittleEndian, true> put(m_block.data(), m_state.h());
|
||||
put(iv[0])(iv[1])(iv[2])(iv[3])(iv[4])(iv[5])(iv[6])(iv[7]);
|
||||
|
||||
// When BLAKE2 is keyed, the input stream is simply {key || 0 || message}.
|
||||
// The key is padded to a full Blocksize with 0. Key it during Restart to
|
||||
// avoid FirstPut and friends. Key size == 0 means no key.
|
||||
if (m_keyLength)
|
||||
Update(m_key, BLOCKSIZE);
|
||||
}
|
||||
|
||||
void BLAKE2s::Update(const byte *input, size_t length)
|
||||
{
|
||||
CRYPTOPP_ASSERT(input != NULLPTR || length == 0);
|
||||
|
||||
if (length > BLOCKSIZE - m_state.m_len)
|
||||
{
|
||||
if (m_state.m_len != 0)
|
||||
{
|
||||
// Complete current block
|
||||
const size_t fill = BLOCKSIZE - m_state.m_len;
|
||||
std::memcpy(m_state.m_buf+m_state.m_len, input, fill);
|
||||
|
||||
IncrementCounter(BLOCKSIZE);
|
||||
Compress(m_state.m_buf);
|
||||
m_state.m_len = 0;
|
||||
|
||||
length -= fill, input += fill;
|
||||
}
|
||||
|
||||
// Compress in-place to avoid copies
|
||||
while (length > BLOCKSIZE)
|
||||
{
|
||||
IncrementCounter(BLOCKSIZE);
|
||||
Compress(input);
|
||||
length -= BLOCKSIZE, input += BLOCKSIZE;
|
||||
}
|
||||
}
|
||||
|
||||
// Copy tail bytes
|
||||
if (length)
|
||||
{
|
||||
CRYPTOPP_ASSERT(length <= BLOCKSIZE - m_state.m_len);
|
||||
std::memcpy(m_state.m_buf+m_state.m_len, input, length);
|
||||
m_state.m_len += static_cast<unsigned int>(length);
|
||||
}
|
||||
}
|
||||
|
||||
void BLAKE2b::Update(const byte *input, size_t length)
|
||||
{
|
||||
CRYPTOPP_ASSERT(input != NULLPTR || length == 0);
|
||||
|
||||
if (length > BLOCKSIZE - m_state.m_len)
|
||||
{
|
||||
if (m_state.m_len != 0)
|
||||
{
|
||||
// Complete current block
|
||||
const size_t fill = BLOCKSIZE - m_state.m_len;
|
||||
std::memcpy(m_state.m_buf+m_state.m_len, input, fill);
|
||||
|
||||
IncrementCounter(BLOCKSIZE);
|
||||
Compress(m_state.m_buf);
|
||||
m_state.m_len = 0;
|
||||
|
||||
length -= fill, input += fill;
|
||||
}
|
||||
|
||||
// Compress in-place to avoid copies
|
||||
while (length > BLOCKSIZE)
|
||||
{
|
||||
CRYPTOPP_ASSERT(m_state.m_len == 0);
|
||||
IncrementCounter(BLOCKSIZE);
|
||||
Compress(input);
|
||||
length -= BLOCKSIZE, input += BLOCKSIZE;
|
||||
}
|
||||
}
|
||||
|
||||
// Copy tail bytes
|
||||
if (length)
|
||||
{
|
||||
CRYPTOPP_ASSERT(length <= BLOCKSIZE - m_state.m_len);
|
||||
std::memcpy(m_state.m_buf + m_state.m_len, input, length);
|
||||
m_state.m_len += static_cast<unsigned int>(length);
|
||||
}
|
||||
}
|
||||
|
||||
void BLAKE2s::TruncatedFinal(byte *hash, size_t size)
|
||||
{
|
||||
CRYPTOPP_ASSERT(hash != NULLPTR);
|
||||
this->ThrowIfInvalidTruncatedSize(size);
|
||||
word32* f = m_state.f();
|
||||
|
||||
// Set last block unconditionally
|
||||
f[0] = ~static_cast<word32>(0);
|
||||
|
||||
// Set last node if tree mode
|
||||
if (m_treeMode)
|
||||
f[1] = ~static_cast<word32>(0);
|
||||
|
||||
// Increment counter for tail bytes only
|
||||
IncrementCounter(m_state.m_len);
|
||||
|
||||
std::memset(m_state.m_buf + m_state.m_len, 0x00, BLOCKSIZE - m_state.m_len);
|
||||
Compress(m_state.m_buf);
|
||||
|
||||
// Copy to caller buffer
|
||||
std::memcpy(hash, m_state.h(), size);
|
||||
|
||||
Restart();
|
||||
}
|
||||
|
||||
void BLAKE2b::TruncatedFinal(byte *hash, size_t size)
|
||||
{
|
||||
CRYPTOPP_ASSERT(hash != NULLPTR);
|
||||
this->ThrowIfInvalidTruncatedSize(size);
|
||||
word64* f = m_state.f();
|
||||
|
||||
// Set last block unconditionally
|
||||
f[0] = ~static_cast<word64>(0);
|
||||
|
||||
// Set last node if tree mode
|
||||
if (m_treeMode)
|
||||
f[1] = ~static_cast<word64>(0);
|
||||
|
||||
// Increment counter for tail bytes only
|
||||
IncrementCounter(m_state.m_len);
|
||||
|
||||
std::memset(m_state.m_buf + m_state.m_len, 0x00, BLOCKSIZE - m_state.m_len);
|
||||
Compress(m_state.m_buf);
|
||||
|
||||
// Copy to caller buffer
|
||||
std::memcpy(hash, m_state.h(), size);
|
||||
|
||||
Restart();
|
||||
}
|
||||
|
||||
void BLAKE2s::IncrementCounter(size_t count)
|
||||
{
|
||||
word32* t = m_state.t();
|
||||
t[0] += static_cast<word32>(count);
|
||||
t[1] += !!(t[0] < count);
|
||||
}
|
||||
|
||||
void BLAKE2b::IncrementCounter(size_t count)
|
||||
{
|
||||
word64* t = m_state.t();
|
||||
t[0] += static_cast<word64>(count);
|
||||
t[1] += !!(t[0] < count);
|
||||
}
|
||||
|
||||
void BLAKE2s::Compress(const byte *input)
|
||||
{
|
||||
#if CRYPTOPP_SSE41_AVAILABLE
|
||||
if(HasSSE41())
|
||||
{
|
||||
return BLAKE2_Compress32_SSE4(input, m_state);
|
||||
}
|
||||
#endif
|
||||
#if CRYPTOPP_ARM_NEON_AVAILABLE
|
||||
if(HasNEON())
|
||||
{
|
||||
return BLAKE2_Compress32_NEON(input, m_state);
|
||||
}
|
||||
#endif
|
||||
#if CRYPTOPP_ALTIVEC_AVAILABLE
|
||||
if(HasAltivec())
|
||||
{
|
||||
return BLAKE2_Compress32_ALTIVEC(input, m_state);
|
||||
}
|
||||
#endif
|
||||
return BLAKE2_Compress32_CXX(input, m_state);
|
||||
}
|
||||
|
||||
void BLAKE2b::Compress(const byte *input)
|
||||
{
|
||||
#if CRYPTOPP_SSE41_AVAILABLE
|
||||
if(HasSSE41())
|
||||
{
|
||||
return BLAKE2_Compress64_SSE4(input, m_state);
|
||||
}
|
||||
#endif
|
||||
#if CRYPTOPP_ARM_NEON_AVAILABLE
|
||||
if(HasNEON())
|
||||
{
|
||||
return BLAKE2_Compress64_NEON(input, m_state);
|
||||
}
|
||||
#endif
|
||||
#if CRYPTOPP_POWER8_AVAILABLE
|
||||
if(HasPower8())
|
||||
{
|
||||
return BLAKE2_Compress64_POWER8(input, m_state);
|
||||
}
|
||||
#endif
|
||||
return BLAKE2_Compress64_CXX(input, m_state);
|
||||
}
|
||||
|
||||
void BLAKE2_Compress64_CXX(const byte* input, BLAKE2b_State& state)
|
||||
{
|
||||
word64 m[16], v[16];
|
||||
|
||||
GetBlock<word64, LittleEndian, true> get1(input);
|
||||
get1(m[0])(m[1])(m[2])(m[3])(m[4])(m[5])(m[6])(m[7])(m[8])(m[9])(m[10])(m[11])(m[12])(m[13])(m[14])(m[15]);
|
||||
|
||||
GetBlock<word64, LittleEndian, true> get2(state.h());
|
||||
get2(v[0])(v[1])(v[2])(v[3])(v[4])(v[5])(v[6])(v[7]);
|
||||
|
||||
const word64* iv = BLAKE2B_IV;
|
||||
const word64* tf = state.t();
|
||||
v[ 8] = iv[0];
|
||||
v[ 9] = iv[1];
|
||||
v[10] = iv[2];
|
||||
v[11] = iv[3];
|
||||
v[12] = tf[0] ^ iv[4];
|
||||
v[13] = tf[1] ^ iv[5];
|
||||
v[14] = tf[2] ^ iv[6];
|
||||
v[15] = tf[3] ^ iv[7];
|
||||
|
||||
BLAKE2B_ROUND<0>(m, v);
|
||||
BLAKE2B_ROUND<1>(m, v);
|
||||
BLAKE2B_ROUND<2>(m, v);
|
||||
BLAKE2B_ROUND<3>(m, v);
|
||||
BLAKE2B_ROUND<4>(m, v);
|
||||
BLAKE2B_ROUND<5>(m, v);
|
||||
BLAKE2B_ROUND<6>(m, v);
|
||||
BLAKE2B_ROUND<7>(m, v);
|
||||
BLAKE2B_ROUND<8>(m, v);
|
||||
BLAKE2B_ROUND<9>(m, v);
|
||||
BLAKE2B_ROUND<10>(m, v);
|
||||
BLAKE2B_ROUND<11>(m, v);
|
||||
|
||||
word64* h = state.h();
|
||||
for (unsigned int i = 0; i < 8; ++i)
|
||||
h[i] = h[i] ^ ConditionalByteReverse(LITTLE_ENDIAN_ORDER, v[i] ^ v[i + 8]);
|
||||
}
|
||||
|
||||
void BLAKE2_Compress32_CXX(const byte* input, BLAKE2s_State& state)
|
||||
{
|
||||
word32 m[16], v[16];
|
||||
|
||||
GetBlock<word32, LittleEndian, true> get1(input);
|
||||
get1(m[0])(m[1])(m[2])(m[3])(m[4])(m[5])(m[6])(m[7])(m[8])(m[9])(m[10])(m[11])(m[12])(m[13])(m[14])(m[15]);
|
||||
|
||||
GetBlock<word32, LittleEndian, true> get2(state.h());
|
||||
get2(v[0])(v[1])(v[2])(v[3])(v[4])(v[5])(v[6])(v[7]);
|
||||
|
||||
const word32* iv = BLAKE2S_IV;
|
||||
const word32* tf = state.t();
|
||||
v[ 8] = iv[0];
|
||||
v[ 9] = iv[1];
|
||||
v[10] = iv[2];
|
||||
v[11] = iv[3];
|
||||
v[12] = tf[0] ^ iv[4];
|
||||
v[13] = tf[1] ^ iv[5];
|
||||
v[14] = tf[2] ^ iv[6];
|
||||
v[15] = tf[3] ^ iv[7];
|
||||
|
||||
BLAKE2S_ROUND<0>(m, v);
|
||||
BLAKE2S_ROUND<1>(m, v);
|
||||
BLAKE2S_ROUND<2>(m, v);
|
||||
BLAKE2S_ROUND<3>(m, v);
|
||||
BLAKE2S_ROUND<4>(m, v);
|
||||
BLAKE2S_ROUND<5>(m, v);
|
||||
BLAKE2S_ROUND<6>(m, v);
|
||||
BLAKE2S_ROUND<7>(m, v);
|
||||
BLAKE2S_ROUND<8>(m, v);
|
||||
BLAKE2S_ROUND<9>(m, v);
|
||||
|
||||
word32* h = state.h();
|
||||
for (unsigned int i = 0; i < 8; ++i)
|
||||
h[i] = h[i] ^ ConditionalByteReverse(LITTLE_ENDIAN_ORDER, v[i] ^ v[i + 8]);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+444
@@ -0,0 +1,444 @@
|
||||
// blake2.h - written and placed in the public domain by Jeffrey Walton
|
||||
// and Zooko Wilcox-O'Hearn. Based on Aumasson, Neves,
|
||||
// Wilcox-O'Hearn and Winnerlein's reference BLAKE2
|
||||
// implementation at http://github.com/BLAKE2/BLAKE2.
|
||||
|
||||
/// \file blake2.h
|
||||
/// \brief Classes for BLAKE2b and BLAKE2s message digests and keyed message digests
|
||||
/// \details This implementation follows Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's
|
||||
/// <A HREF="http://blake2.net/blake2.pdf">BLAKE2: simpler, smaller, fast as MD5</A> (2013.01.29).
|
||||
/// Static algorithm name return either "BLAKE2b" or "BLAKE2s". An object algorithm name follows
|
||||
/// the naming described in <A HREF="http://tools.ietf.org/html/rfc7693#section-4">RFC 7693, The
|
||||
/// BLAKE2 Cryptographic Hash and Message Authentication Code (MAC)</A>.
|
||||
/// \since C++ since Crypto++ 5.6.4, SSE since Crypto++ 5.6.4, NEON since Crypto++ 6.0,
|
||||
/// Power8 since Crypto++ 8.0
|
||||
|
||||
#ifndef CRYPTOPP_BLAKE2_H
|
||||
#define CRYPTOPP_BLAKE2_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "secblock.h"
|
||||
#include "seckey.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief BLAKE2s hash information
|
||||
/// \since Crypto++ 5.6.4
|
||||
struct BLAKE2s_Info : public VariableKeyLength<32,0,32,1,SimpleKeyingInterface::NOT_RESYNCHRONIZABLE>
|
||||
{
|
||||
typedef VariableKeyLength<32,0,32,1,SimpleKeyingInterface::NOT_RESYNCHRONIZABLE> KeyBase;
|
||||
CRYPTOPP_CONSTANT(MIN_KEYLENGTH = KeyBase::MIN_KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(MAX_KEYLENGTH = KeyBase::MAX_KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(DEFAULT_KEYLENGTH = KeyBase::DEFAULT_KEYLENGTH);
|
||||
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = 64);
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = 32);
|
||||
CRYPTOPP_CONSTANT(SALTSIZE = 8);
|
||||
CRYPTOPP_CONSTANT(PERSONALIZATIONSIZE = 8);
|
||||
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "BLAKE2s";}
|
||||
};
|
||||
|
||||
/// \brief BLAKE2b hash information
|
||||
/// \since Crypto++ 5.6.4
|
||||
struct BLAKE2b_Info : public VariableKeyLength<64,0,64,1,SimpleKeyingInterface::NOT_RESYNCHRONIZABLE>
|
||||
{
|
||||
typedef VariableKeyLength<64,0,64,1,SimpleKeyingInterface::NOT_RESYNCHRONIZABLE> KeyBase;
|
||||
CRYPTOPP_CONSTANT(MIN_KEYLENGTH = KeyBase::MIN_KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(MAX_KEYLENGTH = KeyBase::MAX_KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(DEFAULT_KEYLENGTH = KeyBase::DEFAULT_KEYLENGTH);
|
||||
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = 128);
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = 64);
|
||||
CRYPTOPP_CONSTANT(SALTSIZE = 16);
|
||||
CRYPTOPP_CONSTANT(PERSONALIZATIONSIZE = 16);
|
||||
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "BLAKE2b";}
|
||||
};
|
||||
|
||||
/// \brief BLAKE2s parameter block
|
||||
struct CRYPTOPP_NO_VTABLE BLAKE2s_ParameterBlock
|
||||
{
|
||||
CRYPTOPP_CONSTANT(SALTSIZE = BLAKE2s_Info::SALTSIZE);
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = BLAKE2s_Info::DIGESTSIZE);
|
||||
CRYPTOPP_CONSTANT(PERSONALIZATIONSIZE = BLAKE2s_Info::PERSONALIZATIONSIZE);
|
||||
|
||||
BLAKE2s_ParameterBlock()
|
||||
{
|
||||
Reset();
|
||||
}
|
||||
|
||||
BLAKE2s_ParameterBlock(size_t digestSize)
|
||||
{
|
||||
Reset(digestSize);
|
||||
}
|
||||
|
||||
BLAKE2s_ParameterBlock(size_t digestSize, size_t keyLength, const byte* salt, size_t saltLength,
|
||||
const byte* personalization, size_t personalizationLength);
|
||||
|
||||
void Reset(size_t digestLength=DIGESTSIZE, size_t keyLength=0);
|
||||
|
||||
byte* data() {
|
||||
return m_data.data();
|
||||
}
|
||||
|
||||
const byte* data() const {
|
||||
return m_data.data();
|
||||
}
|
||||
|
||||
size_t size() const {
|
||||
return m_data.size();
|
||||
}
|
||||
|
||||
byte* salt() {
|
||||
return m_data + SaltOff;
|
||||
}
|
||||
|
||||
byte* personalization() {
|
||||
return m_data + PersonalizationOff;
|
||||
}
|
||||
|
||||
// Offsets into the byte array
|
||||
enum {
|
||||
DigestOff = 0, KeyOff = 1, FanoutOff = 2, DepthOff = 3, LeafOff = 4, NodeOff = 8,
|
||||
NodeDepthOff = 14, InnerOff = 15, SaltOff = 16, PersonalizationOff = 24
|
||||
};
|
||||
|
||||
FixedSizeAlignedSecBlock<byte, 32, true> m_data;
|
||||
};
|
||||
|
||||
/// \brief BLAKE2b parameter block
|
||||
struct CRYPTOPP_NO_VTABLE BLAKE2b_ParameterBlock
|
||||
{
|
||||
CRYPTOPP_CONSTANT(SALTSIZE = BLAKE2b_Info::SALTSIZE);
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = BLAKE2b_Info::DIGESTSIZE);
|
||||
CRYPTOPP_CONSTANT(PERSONALIZATIONSIZE = BLAKE2b_Info::PERSONALIZATIONSIZE);
|
||||
|
||||
BLAKE2b_ParameterBlock()
|
||||
{
|
||||
Reset();
|
||||
}
|
||||
|
||||
BLAKE2b_ParameterBlock(size_t digestSize)
|
||||
{
|
||||
Reset(digestSize);
|
||||
}
|
||||
|
||||
BLAKE2b_ParameterBlock(size_t digestSize, size_t keyLength, const byte* salt, size_t saltLength,
|
||||
const byte* personalization, size_t personalizationLength);
|
||||
|
||||
void Reset(size_t digestLength=DIGESTSIZE, size_t keyLength=0);
|
||||
|
||||
byte* data() {
|
||||
return m_data.data();
|
||||
}
|
||||
|
||||
const byte* data() const {
|
||||
return m_data.data();
|
||||
}
|
||||
|
||||
size_t size() const {
|
||||
return m_data.size();
|
||||
}
|
||||
|
||||
byte* salt() {
|
||||
return m_data + SaltOff;
|
||||
}
|
||||
|
||||
byte* personalization() {
|
||||
return m_data + PersonalizationOff;
|
||||
}
|
||||
|
||||
// Offsets into the byte array
|
||||
enum {
|
||||
DigestOff = 0, KeyOff = 1, FanoutOff = 2, DepthOff = 3, LeafOff = 4, NodeOff = 8,
|
||||
NodeDepthOff = 16, InnerOff = 17, RfuOff = 18, SaltOff = 32, PersonalizationOff = 48
|
||||
};
|
||||
|
||||
FixedSizeAlignedSecBlock<byte, 64, true> m_data;
|
||||
};
|
||||
|
||||
/// \brief BLAKE2s state information
|
||||
/// \since Crypto++ 5.6.4
|
||||
struct CRYPTOPP_NO_VTABLE BLAKE2s_State
|
||||
{
|
||||
BLAKE2s_State() {
|
||||
Reset();
|
||||
}
|
||||
|
||||
void Reset();
|
||||
|
||||
inline word32* h() {
|
||||
return m_hft.data();
|
||||
}
|
||||
|
||||
inline word32* t() {
|
||||
return m_hft.data() + 8;
|
||||
}
|
||||
|
||||
inline word32* f() {
|
||||
return m_hft.data() + 10;
|
||||
}
|
||||
|
||||
inline byte* data() {
|
||||
return m_buf.data();
|
||||
}
|
||||
|
||||
// SSE4, Power7 and NEON depend upon t[] and f[] being side-by-side
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = BLAKE2s_Info::BLOCKSIZE);
|
||||
FixedSizeAlignedSecBlock<word32, 8+2+2, true> m_hft;
|
||||
FixedSizeAlignedSecBlock<byte, BLOCKSIZE, true> m_buf;
|
||||
size_t m_len;
|
||||
};
|
||||
|
||||
/// \brief BLAKE2b state information
|
||||
/// \since Crypto++ 5.6.4
|
||||
struct CRYPTOPP_NO_VTABLE BLAKE2b_State
|
||||
{
|
||||
BLAKE2b_State() {
|
||||
Reset();
|
||||
}
|
||||
|
||||
void Reset();
|
||||
|
||||
inline word64* h() {
|
||||
return m_hft.data();
|
||||
}
|
||||
|
||||
inline word64* t() {
|
||||
return m_hft.data() + 8;
|
||||
}
|
||||
|
||||
inline word64* f() {
|
||||
return m_hft.data() + 10;
|
||||
}
|
||||
|
||||
inline byte* data() {
|
||||
return m_buf.data();
|
||||
}
|
||||
|
||||
// SSE4, Power8 and NEON depend upon t[] and f[] being side-by-side
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = BLAKE2b_Info::BLOCKSIZE);
|
||||
FixedSizeAlignedSecBlock<word64, 8+2+2, true> m_hft;
|
||||
FixedSizeAlignedSecBlock<byte, BLOCKSIZE, true> m_buf;
|
||||
size_t m_len;
|
||||
};
|
||||
|
||||
/// \brief The BLAKE2s cryptographic hash function
|
||||
/// \details BLAKE2s can function as both a hash and keyed hash. If you want only the hash,
|
||||
/// then use the BLAKE2s constructor that accepts no parameters or digest size. If you
|
||||
/// want a keyed hash, then use the constructor that accpts the key as a parameter.
|
||||
/// Once a key and digest size are selected, its effectively immutable. The Restart()
|
||||
/// method that accepts a ParameterBlock does not allow you to change it.
|
||||
/// \sa Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's
|
||||
/// <A HREF="http://blake2.net/blake2.pdf">BLAKE2: simpler, smaller, fast as MD5</A> (2013.01.29).
|
||||
/// \since C++ since Crypto++ 5.6.4, SSE since Crypto++ 5.6.4, NEON since Crypto++ 6.0,
|
||||
/// Power8 since Crypto++ 8.0
|
||||
class BLAKE2s : public SimpleKeyingInterfaceImpl<MessageAuthenticationCode, BLAKE2s_Info>
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_CONSTANT(DEFAULT_KEYLENGTH = BLAKE2s_Info::DEFAULT_KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(MIN_KEYLENGTH = BLAKE2s_Info::MIN_KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(MAX_KEYLENGTH = BLAKE2s_Info::MAX_KEYLENGTH);
|
||||
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = BLAKE2s_Info::DIGESTSIZE);
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = BLAKE2s_Info::BLOCKSIZE);
|
||||
CRYPTOPP_CONSTANT(SALTSIZE = BLAKE2s_Info::SALTSIZE);
|
||||
CRYPTOPP_CONSTANT(PERSONALIZATIONSIZE = BLAKE2s_Info::PERSONALIZATIONSIZE);
|
||||
|
||||
typedef BLAKE2s_State State;
|
||||
typedef BLAKE2s_ParameterBlock ParameterBlock;
|
||||
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "BLAKE2s";}
|
||||
|
||||
virtual ~BLAKE2s() {}
|
||||
|
||||
/// \brief Construct a BLAKE2s hash
|
||||
/// \param digestSize the digest size, in bytes
|
||||
/// \param treeMode flag indicating tree mode
|
||||
/// \since Crypto++ 5.6.4
|
||||
BLAKE2s(bool treeMode=false, unsigned int digestSize = DIGESTSIZE);
|
||||
|
||||
/// \brief Construct a BLAKE2s hash
|
||||
/// \param digestSize the digest size, in bytes
|
||||
/// \details treeMode flag is set to false
|
||||
/// \since Crypto++ 8.2
|
||||
BLAKE2s(unsigned int digestSize);
|
||||
|
||||
/// \brief Construct a BLAKE2s hash
|
||||
/// \param key a byte array used to key the cipher
|
||||
/// \param keyLength the size of the byte array
|
||||
/// \param salt a byte array used as salt
|
||||
/// \param saltLength the size of the byte array
|
||||
/// \param personalization a byte array used as personalization string
|
||||
/// \param personalizationLength the size of the byte array
|
||||
/// \param treeMode flag indicating tree mode
|
||||
/// \param digestSize the digest size, in bytes
|
||||
/// \since Crypto++ 5.6.4
|
||||
BLAKE2s(const byte *key, size_t keyLength, const byte* salt = NULLPTR, size_t saltLength = 0,
|
||||
const byte* personalization = NULLPTR, size_t personalizationLength = 0,
|
||||
bool treeMode=false, unsigned int digestSize = DIGESTSIZE);
|
||||
|
||||
/// \brief Retrieve the object's name
|
||||
/// \return the object's algorithm name following RFC 7693
|
||||
/// \details Object algorithm name follows the naming described in
|
||||
/// <A HREF="http://tools.ietf.org/html/rfc7693#section-4">RFC 7693, The BLAKE2 Cryptographic Hash and
|
||||
/// Message Authentication Code (MAC)</A>. For example, "BLAKE2b-512" and "BLAKE2s-256".
|
||||
std::string AlgorithmName() const {return std::string(BLAKE2s_Info::StaticAlgorithmName()) + "-" + IntToString(DigestSize()*8);}
|
||||
|
||||
unsigned int BlockSize() const {return BLOCKSIZE;}
|
||||
unsigned int DigestSize() const {return m_digestSize;}
|
||||
unsigned int OptimalDataAlignment() const;
|
||||
|
||||
void Update(const byte *input, size_t length);
|
||||
void Restart();
|
||||
|
||||
/// \brief Restart a hash with parameter block and counter
|
||||
/// \param block parameter block
|
||||
/// \param counter counter array
|
||||
/// \details Parameter block is persisted across calls to Restart().
|
||||
void Restart(const BLAKE2s_ParameterBlock& block, const word32 counter[2]);
|
||||
|
||||
/// \brief Set tree mode
|
||||
/// \param mode the new tree mode
|
||||
/// \details BLAKE2 has two finalization flags, called State::f[0] and State::f[1].
|
||||
/// If <tt>treeMode=false</tt> (default), then State::f[1] is never set. If
|
||||
/// <tt>treeMode=true</tt>, then State::f[1] is set when State::f[0] is set.
|
||||
/// Tree mode is persisted across calls to Restart().
|
||||
void SetTreeMode(bool mode) {m_treeMode=mode;}
|
||||
|
||||
/// \brief Get tree mode
|
||||
/// \return the current tree mode
|
||||
/// \details Tree mode is persisted across calls to Restart().
|
||||
bool GetTreeMode() const {return m_treeMode;}
|
||||
|
||||
void TruncatedFinal(byte *hash, size_t size);
|
||||
|
||||
std::string AlgorithmProvider() const;
|
||||
|
||||
protected:
|
||||
// Operates on state buffer and/or input. Must be BLOCKSIZE, final block will pad with 0's.
|
||||
void Compress(const byte *input);
|
||||
inline void IncrementCounter(size_t count=BLOCKSIZE);
|
||||
|
||||
void UncheckedSetKey(const byte* key, unsigned int length, const CryptoPP::NameValuePairs& params);
|
||||
|
||||
private:
|
||||
State m_state;
|
||||
ParameterBlock m_block;
|
||||
AlignedSecByteBlock m_key;
|
||||
word32 m_digestSize, m_keyLength;
|
||||
bool m_treeMode;
|
||||
};
|
||||
|
||||
/// \brief The BLAKE2b cryptographic hash function
|
||||
/// \details BLAKE2b can function as both a hash and keyed hash. If you want only the hash,
|
||||
/// then use the BLAKE2b constructor that accepts no parameters or digest size. If you
|
||||
/// want a keyed hash, then use the constructor that accpts the key as a parameter.
|
||||
/// Once a key and digest size are selected, its effectively immutable. The Restart()
|
||||
/// method that accepts a ParameterBlock does not allow you to change it.
|
||||
/// \sa Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's
|
||||
/// <A HREF="http://blake2.net/blake2.pdf">BLAKE2: simpler, smaller, fast as MD5</A> (2013.01.29).
|
||||
/// \since C++ since Crypto++ 5.6.4, SSE since Crypto++ 5.6.4, NEON since Crypto++ 6.0,
|
||||
/// Power8 since Crypto++ 8.0
|
||||
class BLAKE2b : public SimpleKeyingInterfaceImpl<MessageAuthenticationCode, BLAKE2b_Info>
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_CONSTANT(DEFAULT_KEYLENGTH = BLAKE2b_Info::DEFAULT_KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(MIN_KEYLENGTH = BLAKE2b_Info::MIN_KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(MAX_KEYLENGTH = BLAKE2b_Info::MAX_KEYLENGTH);
|
||||
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = BLAKE2b_Info::DIGESTSIZE);
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = BLAKE2b_Info::BLOCKSIZE);
|
||||
CRYPTOPP_CONSTANT(SALTSIZE = BLAKE2b_Info::SALTSIZE);
|
||||
CRYPTOPP_CONSTANT(PERSONALIZATIONSIZE = BLAKE2b_Info::PERSONALIZATIONSIZE);
|
||||
|
||||
typedef BLAKE2b_State State;
|
||||
typedef BLAKE2b_ParameterBlock ParameterBlock;
|
||||
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "BLAKE2b";}
|
||||
|
||||
virtual ~BLAKE2b() {}
|
||||
|
||||
/// \brief Construct a BLAKE2b hash
|
||||
/// \param digestSize the digest size, in bytes
|
||||
/// \param treeMode flag indicating tree mode
|
||||
/// \since Crypto++ 5.6.4
|
||||
BLAKE2b(bool treeMode=false, unsigned int digestSize = DIGESTSIZE);
|
||||
|
||||
/// \brief Construct a BLAKE2s hash
|
||||
/// \param digestSize the digest size, in bytes
|
||||
/// \details treeMode flag is set to false
|
||||
/// \since Crypto++ 8.2
|
||||
BLAKE2b(unsigned int digestSize);
|
||||
|
||||
/// \brief Construct a BLAKE2b hash
|
||||
/// \param key a byte array used to key the cipher
|
||||
/// \param keyLength the size of the byte array
|
||||
/// \param salt a byte array used as salt
|
||||
/// \param saltLength the size of the byte array
|
||||
/// \param personalization a byte array used as personalization string
|
||||
/// \param personalizationLength the size of the byte array
|
||||
/// \param treeMode flag indicating tree mode
|
||||
/// \param digestSize the digest size, in bytes
|
||||
/// \since Crypto++ 5.6.4
|
||||
BLAKE2b(const byte *key, size_t keyLength, const byte* salt = NULLPTR, size_t saltLength = 0,
|
||||
const byte* personalization = NULLPTR, size_t personalizationLength = 0,
|
||||
bool treeMode=false, unsigned int digestSize = DIGESTSIZE);
|
||||
|
||||
/// \brief Retrieve the object's name
|
||||
/// \return the object's algorithm name following RFC 7693
|
||||
/// \details Object algorithm name follows the naming described in
|
||||
/// <A HREF="http://tools.ietf.org/html/rfc7693#section-4">RFC 7693, The BLAKE2 Cryptographic Hash and
|
||||
/// Message Authentication Code (MAC)</A>. For example, "BLAKE2b-512" and "BLAKE2s-256".
|
||||
std::string AlgorithmName() const {return std::string(BLAKE2b_Info::StaticAlgorithmName()) + "-" + IntToString(DigestSize()*8);}
|
||||
|
||||
unsigned int BlockSize() const {return BLOCKSIZE;}
|
||||
unsigned int DigestSize() const {return m_digestSize;}
|
||||
unsigned int OptimalDataAlignment() const;
|
||||
|
||||
void Update(const byte *input, size_t length);
|
||||
void Restart();
|
||||
|
||||
/// \brief Restart a hash with parameter block and counter
|
||||
/// \param block parameter block
|
||||
/// \param counter counter array
|
||||
/// \details Parameter block is persisted across calls to Restart().
|
||||
void Restart(const BLAKE2b_ParameterBlock& block, const word64 counter[2]);
|
||||
|
||||
/// \brief Set tree mode
|
||||
/// \param mode the new tree mode
|
||||
/// \details BLAKE2 has two finalization flags, called State::f[0] and State::f[1].
|
||||
/// If <tt>treeMode=false</tt> (default), then State::f[1] is never set. If
|
||||
/// <tt>treeMode=true</tt>, then State::f[1] is set when State::f[0] is set.
|
||||
/// Tree mode is persisted across calls to Restart().
|
||||
void SetTreeMode(bool mode) {m_treeMode=mode;}
|
||||
|
||||
/// \brief Get tree mode
|
||||
/// \return the current tree mode
|
||||
/// \details Tree mode is persisted across calls to Restart().
|
||||
bool GetTreeMode() const {return m_treeMode;}
|
||||
|
||||
void TruncatedFinal(byte *hash, size_t size);
|
||||
|
||||
std::string AlgorithmProvider() const;
|
||||
|
||||
protected:
|
||||
|
||||
// Operates on state buffer and/or input. Must be BLOCKSIZE, final block will pad with 0's.
|
||||
void Compress(const byte *input);
|
||||
inline void IncrementCounter(size_t count=BLOCKSIZE);
|
||||
|
||||
void UncheckedSetKey(const byte* key, unsigned int length, const CryptoPP::NameValuePairs& params);
|
||||
|
||||
private:
|
||||
State m_state;
|
||||
ParameterBlock m_block;
|
||||
AlignedSecByteBlock m_key;
|
||||
word32 m_digestSize, m_keyLength;
|
||||
bool m_treeMode;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+1276
File diff suppressed because it is too large
Load Diff
+1091
File diff suppressed because it is too large
Load Diff
+99
@@ -0,0 +1,99 @@
|
||||
// blowfish.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
#include "blowfish.h"
|
||||
#include "misc.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
void Blowfish::Base::UncheckedSetKey(const byte *key_string, unsigned int keylength, const NameValuePairs &)
|
||||
{
|
||||
AssertValidKeyLength(keylength);
|
||||
|
||||
unsigned i, j=0, k;
|
||||
word32 data, dspace[2] = {0, 0};
|
||||
|
||||
memcpy(pbox, p_init, sizeof(p_init));
|
||||
memcpy(sbox, s_init, sizeof(s_init));
|
||||
|
||||
// Xor key string into encryption key vector
|
||||
for (i=0 ; i<ROUNDS+2 ; ++i)
|
||||
{
|
||||
data = 0 ;
|
||||
for (k=0 ; k<4 ; ++k )
|
||||
data = (data << 8) | key_string[j++ % keylength];
|
||||
pbox[i] ^= data;
|
||||
}
|
||||
|
||||
crypt_block(dspace, pbox);
|
||||
|
||||
for (i=0; i<ROUNDS; i+=2)
|
||||
crypt_block(pbox+i, pbox+i+2);
|
||||
|
||||
crypt_block(pbox+ROUNDS, sbox);
|
||||
|
||||
for (i=0; i<4*256-2; i+=2)
|
||||
crypt_block(sbox+i, sbox+i+2);
|
||||
|
||||
if (!IsForwardTransformation())
|
||||
for (i=0; i<(ROUNDS+2)/2; i++)
|
||||
std::swap(pbox[i], pbox[ROUNDS+1-i]);
|
||||
}
|
||||
|
||||
// this version is only used to make pbox and sbox
|
||||
void Blowfish::Base::crypt_block(const word32 in[2], word32 out[2]) const
|
||||
{
|
||||
word32 left = in[0];
|
||||
word32 right = in[1];
|
||||
|
||||
const word32 *const s=sbox;
|
||||
const word32 *p=pbox;
|
||||
|
||||
left ^= p[0];
|
||||
|
||||
for (unsigned i=0; i<ROUNDS/2; i++)
|
||||
{
|
||||
right ^= (((s[GETBYTE(left,3)] + s[256+GETBYTE(left,2)])
|
||||
^ s[2*256+GETBYTE(left,1)]) + s[3*256+GETBYTE(left,0)])
|
||||
^ p[2*i+1];
|
||||
|
||||
left ^= (((s[GETBYTE(right,3)] + s[256+GETBYTE(right,2)])
|
||||
^ s[2*256+GETBYTE(right,1)]) + s[3*256+GETBYTE(right,0)])
|
||||
^ p[2*i+2];
|
||||
}
|
||||
|
||||
right ^= p[ROUNDS+1];
|
||||
|
||||
out[0] = right;
|
||||
out[1] = left;
|
||||
}
|
||||
|
||||
void Blowfish::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
typedef BlockGetAndPut<word32, BigEndian> Block;
|
||||
|
||||
word32 left, right;
|
||||
Block::Get(inBlock)(left)(right);
|
||||
|
||||
const word32 *const s=sbox;
|
||||
const word32 *p=pbox;
|
||||
|
||||
left ^= p[0];
|
||||
|
||||
for (unsigned i=0; i<ROUNDS/2; i++)
|
||||
{
|
||||
right ^= (((s[GETBYTE(left,3)] + s[256+GETBYTE(left,2)])
|
||||
^ s[2*256+GETBYTE(left,1)]) + s[3*256+GETBYTE(left,0)])
|
||||
^ p[2*i+1];
|
||||
|
||||
left ^= (((s[GETBYTE(right,3)] + s[256+GETBYTE(right,2)])
|
||||
^ s[2*256+GETBYTE(right,1)]) + s[3*256+GETBYTE(right,0)])
|
||||
^ p[2*i+2];
|
||||
}
|
||||
|
||||
right ^= p[ROUNDS+1];
|
||||
|
||||
Block::Put(xorBlock, outBlock)(right)(left);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
// blowfish.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file blowfish.h
|
||||
/// \brief Classes for the Blowfish block cipher
|
||||
|
||||
#ifndef CRYPTOPP_BLOWFISH_H
|
||||
#define CRYPTOPP_BLOWFISH_H
|
||||
|
||||
#include "seckey.h"
|
||||
#include "secblock.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief Blowfish block cipher information
|
||||
struct Blowfish_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 4, 56>, public FixedRounds<16>
|
||||
{
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "Blowfish";}
|
||||
};
|
||||
|
||||
// <a href="http://www.cryptopp.com/wiki/Blowfish">Blowfish</a>
|
||||
|
||||
/// \brief Blowfish block cipher
|
||||
/// \since Crypto++ 1.0
|
||||
class Blowfish : public Blowfish_Info, public BlockCipherDocumentation
|
||||
{
|
||||
/// \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:
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
void UncheckedSetKey(const byte *key_string, unsigned int keylength, const NameValuePairs ¶ms);
|
||||
|
||||
private:
|
||||
void crypt_block(const word32 in[2], word32 out[2]) const;
|
||||
|
||||
static const word32 p_init[ROUNDS+2];
|
||||
static const word32 s_init[4*256];
|
||||
|
||||
FixedSizeSecBlock<word32, ROUNDS+2> pbox;
|
||||
FixedSizeSecBlock<word32, 4*256> sbox;
|
||||
};
|
||||
|
||||
public:
|
||||
typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
|
||||
typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
|
||||
};
|
||||
|
||||
typedef Blowfish::Encryption BlowfishEncryption;
|
||||
typedef Blowfish::Decryption BlowfishDecryption;
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
// blumshub.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
#include "blumshub.h"
|
||||
#include "integer.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
PublicBlumBlumShub::PublicBlumBlumShub(const Integer &n, const Integer &seed)
|
||||
: modn(n),
|
||||
current(modn.Square(modn.Square(seed))),
|
||||
maxBits(BitPrecision(n.BitCount())-1),
|
||||
bitsLeft(maxBits)
|
||||
{
|
||||
}
|
||||
|
||||
unsigned int PublicBlumBlumShub::GenerateBit()
|
||||
{
|
||||
if (bitsLeft==0)
|
||||
{
|
||||
current = modn.Square(current);
|
||||
bitsLeft = maxBits;
|
||||
}
|
||||
|
||||
return static_cast<unsigned int>(current.GetBit(--bitsLeft));
|
||||
}
|
||||
|
||||
byte PublicBlumBlumShub::GenerateByte()
|
||||
{
|
||||
byte b=0;
|
||||
for (int i=0; i<8; i++)
|
||||
b = byte((b << 1) | PublicBlumBlumShub::GenerateBit());
|
||||
return b;
|
||||
}
|
||||
|
||||
void PublicBlumBlumShub::GenerateBlock(byte *output, size_t size)
|
||||
{
|
||||
while (size--)
|
||||
*output++ = PublicBlumBlumShub::GenerateByte();
|
||||
}
|
||||
|
||||
void PublicBlumBlumShub::ProcessData(byte *outString, const byte *inString, size_t length)
|
||||
{
|
||||
while (length--)
|
||||
*outString++ = *inString++ ^ PublicBlumBlumShub::GenerateByte();
|
||||
}
|
||||
|
||||
BlumBlumShub::BlumBlumShub(const Integer &p, const Integer &q, const Integer &seed)
|
||||
: PublicBlumBlumShub(p*q, seed),
|
||||
p(p), q(q),
|
||||
x0(modn.Square(seed))
|
||||
{
|
||||
}
|
||||
|
||||
void BlumBlumShub::Seek(lword index)
|
||||
{
|
||||
Integer i(Integer::POSITIVE, index);
|
||||
i *= 8;
|
||||
Integer e = a_exp_b_mod_c (2, i / maxBits + 1, (p-1)*(q-1));
|
||||
current = modn.Exponentiate(x0, e);
|
||||
bitsLeft = maxBits - i % maxBits;
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// blumshub.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file blumshub.h
|
||||
/// \brief Classes for Blum Blum Shub generator
|
||||
|
||||
#ifndef CRYPTOPP_BLUMSHUB_H
|
||||
#define CRYPTOPP_BLUMSHUB_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "modarith.h"
|
||||
#include "integer.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief BlumBlumShub without factorization of the modulus
|
||||
/// \details You should reseed the generator after a fork() to avoid multiple generators
|
||||
/// with the same internal state.
|
||||
class PublicBlumBlumShub : public RandomNumberGenerator,
|
||||
public StreamTransformation
|
||||
{
|
||||
public:
|
||||
virtual ~PublicBlumBlumShub() {}
|
||||
|
||||
/// \brief Construct a PublicBlumBlumShub
|
||||
/// \param n the modulus
|
||||
/// \param seed the seed for the generator
|
||||
/// \details seed is the secret key and should be about as large as n.
|
||||
PublicBlumBlumShub(const Integer &n, const Integer &seed);
|
||||
|
||||
unsigned int GenerateBit();
|
||||
byte GenerateByte();
|
||||
void GenerateBlock(byte *output, size_t size);
|
||||
void ProcessData(byte *outString, const byte *inString, size_t length);
|
||||
|
||||
bool IsSelfInverting() const {return true;}
|
||||
bool IsForwardTransformation() const {return true;}
|
||||
|
||||
protected:
|
||||
ModularArithmetic modn;
|
||||
Integer current;
|
||||
word maxBits, bitsLeft;
|
||||
};
|
||||
|
||||
/// \brief BlumBlumShub with factorization of the modulus
|
||||
/// \details You should reseed the generator after a fork() to avoid multiple generators
|
||||
/// with the same internal state.
|
||||
class BlumBlumShub : public PublicBlumBlumShub
|
||||
{
|
||||
public:
|
||||
virtual ~BlumBlumShub() {}
|
||||
|
||||
/// \brief Construct a BlumBlumShub
|
||||
/// \param p the first prime factor
|
||||
/// \param q the second prime factor
|
||||
/// \param seed the seed for the generator
|
||||
/// \details Esure p and q are both primes congruent to 3 mod 4 and at least 512 bits long.
|
||||
/// seed is the secret key and should be about as large as p*q.
|
||||
BlumBlumShub(const Integer &p, const Integer &q, const Integer &seed);
|
||||
|
||||
bool IsRandomAccess() const {return true;}
|
||||
void Seek(lword index);
|
||||
|
||||
protected:
|
||||
const Integer p, q;
|
||||
const Integer x0;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+539
@@ -0,0 +1,539 @@
|
||||
// camellia.cpp - by Kevin Springle, 2003
|
||||
// This code is hereby placed in the public domain.
|
||||
|
||||
/*
|
||||
Optimisations and defense against timing attacks added in Jan 2007 by Wei Dai.
|
||||
|
||||
The first 2 rounds and the last round seem especially vulnerable to timing
|
||||
attacks. The protection is similar to what was implemented for Rijndael.
|
||||
See comments at top of rijndael.cpp for more details.
|
||||
*/
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(disable: 4456)
|
||||
# if (CRYPTOPP_MSC_VERSION >= 1400)
|
||||
# pragma warning(disable: 6246)
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#include "camellia.h"
|
||||
#include "misc.h"
|
||||
#include "cpu.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
// round implementation that uses a small table for protection against timing attacks
|
||||
#define SLOW_ROUND(lh, ll, rh, rl, kh, kl) { \
|
||||
word32 zr = ll ^ kl; \
|
||||
word32 zl = lh ^ kh; \
|
||||
zr= rotlConstant<1>(s1[GETBYTE(zr, 3)]) | \
|
||||
(rotrConstant<1>(s1[GETBYTE(zr, 2)]) << 24) | \
|
||||
(s1[rotlConstant<1>(CRYPTOPP_GET_BYTE_AS_BYTE(zr, 1))] << 16) | \
|
||||
(s1[GETBYTE(zr, 0)] << 8); \
|
||||
zl= (s1[GETBYTE(zl, 3)] << 24) | \
|
||||
(rotlConstant<1>(s1[GETBYTE(zl, 2)]) << 16) | \
|
||||
(rotrConstant<1>(s1[GETBYTE(zl, 1)]) << 8) | \
|
||||
s1[rotlConstant<1>(CRYPTOPP_GET_BYTE_AS_BYTE(zl, 0))]; \
|
||||
zl ^= zr; \
|
||||
zr = zl ^ rotlConstant<8>(zr); \
|
||||
zl = zr ^ rotrConstant<8>(zl); \
|
||||
rh ^= rotlConstant<16>(zr); \
|
||||
rh ^= zl; \
|
||||
rl ^= rotlConstant<8>(zl); \
|
||||
}
|
||||
|
||||
// normal round - same output as above but using larger tables for faster speed
|
||||
#define ROUND(lh, ll, rh, rl, kh, kl) { \
|
||||
word32 th = lh ^ kh; \
|
||||
word32 tl = ll ^ kl; \
|
||||
word32 d = SP[0][GETBYTE(tl,0)] ^ SP[1][GETBYTE(tl,3)] ^ SP[2][GETBYTE(tl,2)] ^ SP[3][GETBYTE(tl,1)]; \
|
||||
word32 u = SP[0][GETBYTE(th,3)] ^ SP[1][GETBYTE(th,2)] ^ SP[2][GETBYTE(th,1)] ^ SP[3][GETBYTE(th,0)]; \
|
||||
d ^= u; \
|
||||
rh ^= d; \
|
||||
rl ^= d; \
|
||||
rl ^= rotrConstant<8>(u);}
|
||||
|
||||
#define DOUBLE_ROUND(lh, ll, rh, rl, k0, k1, k2, k3) \
|
||||
ROUND(lh, ll, rh, rl, k0, k1) \
|
||||
ROUND(rh, rl, lh, ll, k2, k3)
|
||||
|
||||
#if (CRYPTOPP_LITTLE_ENDIAN)
|
||||
#define EFI(i) (1-(i))
|
||||
#else
|
||||
#define EFI(i) (i)
|
||||
#endif
|
||||
|
||||
void Camellia::Base::UncheckedSetKey(const byte *key, unsigned int keylen, const NameValuePairs &)
|
||||
{
|
||||
m_rounds = (keylen >= 24) ? 4 : 3;
|
||||
unsigned int kslen = (8 * m_rounds + 2);
|
||||
m_key.New(kslen*2);
|
||||
word32 *ks32 = m_key.data();
|
||||
int m=0, a=0;
|
||||
if (!IsForwardTransformation())
|
||||
m = -1, a = kslen-1;
|
||||
|
||||
word32 kl0, kl1, kl2, kl3;
|
||||
GetBlock<word32, BigEndian> getBlock(key);
|
||||
getBlock(kl0)(kl1)(kl2)(kl3);
|
||||
word32 k0=kl0, k1=kl1, k2=kl2, k3=kl3;
|
||||
|
||||
#define CALC_ADDR2(base, i, j) ((byte *)(base)+8*(i)+4*(j)+((-16*(i))&m))
|
||||
#define CALC_ADDR(base, i) CALC_ADDR2(base, i, 0)
|
||||
|
||||
#if 1
|
||||
word64 kwl, kwr;
|
||||
ks32 += 2*a;
|
||||
#define PREPARE_KS_ROUNDS \
|
||||
kwl = (word64(k0) << 32) | k1; \
|
||||
kwr = (word64(k2) << 32) | k3
|
||||
#define KS_ROUND_0(i) \
|
||||
CRYPTOPP_ASSERT(IsAlignedOn(CALC_ADDR(ks32, i+EFI(0)),GetAlignmentOf<word64>())); \
|
||||
CRYPTOPP_ASSERT(IsAlignedOn(CALC_ADDR(ks32, i+EFI(1)),GetAlignmentOf<word64>())); \
|
||||
*(word64*)(void*)CALC_ADDR(ks32, i+EFI(0)) = kwl; \
|
||||
*(word64*)(void*)CALC_ADDR(ks32, i+EFI(1)) = kwr
|
||||
#define KS_ROUND(i, r, which) \
|
||||
CRYPTOPP_ASSERT(IsAlignedOn(CALC_ADDR(ks32, i+EFI(r<64)),GetAlignmentOf<word64>())); \
|
||||
CRYPTOPP_ASSERT(IsAlignedOn(CALC_ADDR(ks32, i+EFI(r>64)),GetAlignmentOf<word64>())); \
|
||||
if (which & (1<<int(r<64))) *(word64*)(void*)CALC_ADDR(ks32, i+EFI(r<64)) = (kwr << (r%64)) | (kwl >> (64 - (r%64))); \
|
||||
if (which & (1<<int(r>64))) *(word64*)(void*)CALC_ADDR(ks32, i+EFI(r>64)) = (kwl << (r%64)) | (kwr >> (64 - (r%64)))
|
||||
#else
|
||||
// SSE2 version is 30% faster on Intel Core 2. Doesn't seem worth the hassle of maintenance, but left here
|
||||
// #if'd out in case someone needs it.
|
||||
__m128i kw, kw2;
|
||||
__m128i *ks128 = (__m128i *)ks32+a/2;
|
||||
ks32 += 2*a;
|
||||
#define PREPARE_KS_ROUNDS \
|
||||
kw = _mm_set_epi32(k0, k1, k2, k3); \
|
||||
if (m) kw2 = kw, kw = _mm_shuffle_epi32(kw, _MM_SHUFFLE(1, 0, 3, 2)); \
|
||||
else kw2 = _mm_shuffle_epi32(kw, _MM_SHUFFLE(1, 0, 3, 2))
|
||||
#define KS_ROUND_0(i) \
|
||||
_mm_store_si128((__m128i *)CALC_ADDR(ks128, i), kw)
|
||||
#define KS_ROUND(i, r, which) { \
|
||||
__m128i temp; \
|
||||
if (r<64 && (which!=1 || m)) temp = _mm_or_si128(_mm_slli_epi64(kw, r%64), _mm_srli_epi64(kw2, 64-r%64)); \
|
||||
else temp = _mm_or_si128(_mm_slli_epi64(kw2, r%64), _mm_srli_epi64(kw, 64-r%64)); \
|
||||
if (which & 2) _mm_store_si128((__m128i *)CALC_ADDR(ks128, i), temp); \
|
||||
else _mm_storel_epi64((__m128i*)CALC_ADDR(ks32, i+EFI(0)), temp); \
|
||||
}
|
||||
#endif
|
||||
|
||||
if (keylen == 16)
|
||||
{
|
||||
// KL
|
||||
PREPARE_KS_ROUNDS;
|
||||
KS_ROUND_0(0);
|
||||
KS_ROUND(4, 15, 3);
|
||||
KS_ROUND(10, 45, 3);
|
||||
KS_ROUND(12, 60, 2);
|
||||
KS_ROUND(16, 77, 3);
|
||||
KS_ROUND(18, 94, 3);
|
||||
KS_ROUND(22, 111, 3);
|
||||
|
||||
// KA
|
||||
k0=kl0, k1=kl1, k2=kl2, k3=kl3;
|
||||
DOUBLE_ROUND(k0, k1, k2, k3, 0xA09E667Ful, 0x3BCC908Bul, 0xB67AE858ul, 0x4CAA73B2ul);
|
||||
k0^=kl0, k1^=kl1, k2^=kl2, k3^=kl3;
|
||||
DOUBLE_ROUND(k0, k1, k2, k3, 0xC6EF372Ful, 0xE94F82BEul, 0x54FF53A5ul, 0xF1D36F1Cul);
|
||||
|
||||
PREPARE_KS_ROUNDS;
|
||||
KS_ROUND_0(2);
|
||||
KS_ROUND(6, 15, 3);
|
||||
KS_ROUND(8, 30, 3);
|
||||
KS_ROUND(12, 45, 1);
|
||||
KS_ROUND(14, 60, 3);
|
||||
KS_ROUND(20, 94, 3);
|
||||
KS_ROUND(24, 47, 3);
|
||||
}
|
||||
else
|
||||
{
|
||||
// KL
|
||||
PREPARE_KS_ROUNDS;
|
||||
KS_ROUND_0(0);
|
||||
KS_ROUND(12, 45, 3);
|
||||
KS_ROUND(16, 60, 3);
|
||||
KS_ROUND(22, 77, 3);
|
||||
KS_ROUND(30, 111, 3);
|
||||
|
||||
// KR
|
||||
word32 kr0, kr1, kr2, kr3;
|
||||
GetBlock<word32, BigEndian>(key+16)(kr0)(kr1);
|
||||
if (keylen == 24)
|
||||
kr2 = ~kr0, kr3 = ~kr1;
|
||||
else
|
||||
GetBlock<word32, BigEndian>(key+24)(kr2)(kr3);
|
||||
k0=kr0, k1=kr1, k2=kr2, k3=kr3;
|
||||
|
||||
PREPARE_KS_ROUNDS;
|
||||
KS_ROUND(4, 15, 3);
|
||||
KS_ROUND(8, 30, 3);
|
||||
KS_ROUND(18, 60, 3);
|
||||
KS_ROUND(26, 94, 3);
|
||||
|
||||
// KA
|
||||
k0^=kl0, k1^=kl1, k2^=kl2, k3^=kl3;
|
||||
DOUBLE_ROUND(k0, k1, k2, k3, 0xA09E667Ful, 0x3BCC908Bul, 0xB67AE858ul, 0x4CAA73B2ul);
|
||||
k0^=kl0, k1^=kl1, k2^=kl2, k3^=kl3;
|
||||
DOUBLE_ROUND(k0, k1, k2, k3, 0xC6EF372Ful, 0xE94F82BEul, 0x54FF53A5ul, 0xF1D36F1Cul);
|
||||
|
||||
PREPARE_KS_ROUNDS;
|
||||
KS_ROUND(6, 15, 3);
|
||||
KS_ROUND(14, 45, 3);
|
||||
KS_ROUND(24, 77, 3);
|
||||
KS_ROUND(28, 94, 3);
|
||||
|
||||
// KB
|
||||
k0^=kr0, k1^=kr1, k2^=kr2, k3^=kr3;
|
||||
DOUBLE_ROUND(k0, k1, k2, k3, 0x10E527FAul, 0xDE682D1Dul, 0xB05688C2ul, 0xB3E6C1FDul);
|
||||
|
||||
PREPARE_KS_ROUNDS;
|
||||
KS_ROUND_0(2);
|
||||
KS_ROUND(10, 30, 3);
|
||||
KS_ROUND(20, 60, 3);
|
||||
KS_ROUND(32, 47, 3);
|
||||
}
|
||||
}
|
||||
|
||||
void Camellia::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
#define KS(i, j) ks[i*4 + EFI(j/2)*2 + EFI(j%2)]
|
||||
|
||||
#define FL(klh, kll, krh, krl) \
|
||||
ll ^= rotlConstant<1>(lh & klh);\
|
||||
lh ^= (ll | kll); \
|
||||
rh ^= (rl | krl); \
|
||||
rl ^= rotlConstant<1>(rh & krh);
|
||||
|
||||
word32 lh, ll, rh, rl;
|
||||
typedef BlockGetAndPut<word32, BigEndian> Block;
|
||||
Block::Get(inBlock)(lh)(ll)(rh)(rl);
|
||||
const word32 *ks = m_key.data();
|
||||
lh ^= KS(0,0);
|
||||
ll ^= KS(0,1);
|
||||
rh ^= KS(0,2);
|
||||
rl ^= KS(0,3);
|
||||
|
||||
// Timing attack countermeasure. see comments in Rijndael for more details
|
||||
const int cacheLineSize = GetCacheLineSize();
|
||||
unsigned int i;
|
||||
volatile word32 _u = 0;
|
||||
word32 u = _u;
|
||||
|
||||
for (i=0; i<256; i+=cacheLineSize)
|
||||
u &= *(const word32 *)(void*)(s1+i);
|
||||
u &= *(const word32 *)(void*)(s1+252);
|
||||
lh |= u; ll |= u;
|
||||
|
||||
SLOW_ROUND(lh, ll, rh, rl, KS(1,0), KS(1,1))
|
||||
SLOW_ROUND(rh, rl, lh, ll, KS(1,2), KS(1,3))
|
||||
for (i = m_rounds-1; i > 0; --i)
|
||||
{
|
||||
DOUBLE_ROUND(lh, ll, rh, rl, KS(2,0), KS(2,1), KS(2,2), KS(2,3))
|
||||
DOUBLE_ROUND(lh, ll, rh, rl, KS(3,0), KS(3,1), KS(3,2), KS(3,3))
|
||||
FL(KS(4,0), KS(4,1), KS(4,2), KS(4,3));
|
||||
DOUBLE_ROUND(lh, ll, rh, rl, KS(5,0), KS(5,1), KS(5,2), KS(5,3))
|
||||
ks += 16;
|
||||
}
|
||||
DOUBLE_ROUND(lh, ll, rh, rl, KS(2,0), KS(2,1), KS(2,2), KS(2,3))
|
||||
ROUND(lh, ll, rh, rl, KS(3,0), KS(3,1))
|
||||
SLOW_ROUND(rh, rl, lh, ll, KS(3,2), KS(3,3))
|
||||
lh ^= KS(4,0);
|
||||
ll ^= KS(4,1);
|
||||
rh ^= KS(4,2);
|
||||
rl ^= KS(4,3);
|
||||
Block::Put(xorBlock, outBlock)(rh)(rl)(lh)(ll);
|
||||
}
|
||||
|
||||
// The Camellia s-boxes
|
||||
|
||||
CRYPTOPP_ALIGN_DATA(4)
|
||||
const byte Camellia::Base::s1[256] =
|
||||
{
|
||||
112,130,44,236,179,39,192,229,228,133,87,53,234,12,174,65,
|
||||
35,239,107,147,69,25,165,33,237,14,79,78,29,101,146,189,
|
||||
134,184,175,143,124,235,31,206,62,48,220,95,94,197,11,26,
|
||||
166,225,57,202,213,71,93,61,217,1,90,214,81,86,108,77,
|
||||
139,13,154,102,251,204,176,45,116,18,43,32,240,177,132,153,
|
||||
223,76,203,194,52,126,118,5,109,183,169,49,209,23,4,215,
|
||||
20,88,58,97,222,27,17,28,50,15,156,22,83,24,242,34,
|
||||
254,68,207,178,195,181,122,145,36,8,232,168,96,252,105,80,
|
||||
170,208,160,125,161,137,98,151,84,91,30,149,224,255,100,210,
|
||||
16,196,0,72,163,247,117,219,138,3,230,218,9,63,221,148,
|
||||
135,92,131,2,205,74,144,51,115,103,246,243,157,127,191,226,
|
||||
82,155,216,38,200,55,198,59,129,150,111,75,19,190,99,46,
|
||||
233,121,167,140,159,110,188,142,41,245,249,182,47,253,180,89,
|
||||
120,152,6,106,231,70,113,186,212,37,171,66,136,162,141,250,
|
||||
114,7,185,85,248,238,172,10,54,73,42,104,60,56,241,164,
|
||||
64,40,211,123,187,201,67,193,21,227,173,244,119,199,128,158
|
||||
};
|
||||
|
||||
const word32 Camellia::Base::SP[4][256] = {
|
||||
{
|
||||
0x70707000, 0x82828200, 0x2c2c2c00, 0xececec00,
|
||||
0xb3b3b300, 0x27272700, 0xc0c0c000, 0xe5e5e500,
|
||||
0xe4e4e400, 0x85858500, 0x57575700, 0x35353500,
|
||||
0xeaeaea00, 0x0c0c0c00, 0xaeaeae00, 0x41414100,
|
||||
0x23232300, 0xefefef00, 0x6b6b6b00, 0x93939300,
|
||||
0x45454500, 0x19191900, 0xa5a5a500, 0x21212100,
|
||||
0xededed00, 0x0e0e0e00, 0x4f4f4f00, 0x4e4e4e00,
|
||||
0x1d1d1d00, 0x65656500, 0x92929200, 0xbdbdbd00,
|
||||
0x86868600, 0xb8b8b800, 0xafafaf00, 0x8f8f8f00,
|
||||
0x7c7c7c00, 0xebebeb00, 0x1f1f1f00, 0xcecece00,
|
||||
0x3e3e3e00, 0x30303000, 0xdcdcdc00, 0x5f5f5f00,
|
||||
0x5e5e5e00, 0xc5c5c500, 0x0b0b0b00, 0x1a1a1a00,
|
||||
0xa6a6a600, 0xe1e1e100, 0x39393900, 0xcacaca00,
|
||||
0xd5d5d500, 0x47474700, 0x5d5d5d00, 0x3d3d3d00,
|
||||
0xd9d9d900, 0x01010100, 0x5a5a5a00, 0xd6d6d600,
|
||||
0x51515100, 0x56565600, 0x6c6c6c00, 0x4d4d4d00,
|
||||
0x8b8b8b00, 0x0d0d0d00, 0x9a9a9a00, 0x66666600,
|
||||
0xfbfbfb00, 0xcccccc00, 0xb0b0b000, 0x2d2d2d00,
|
||||
0x74747400, 0x12121200, 0x2b2b2b00, 0x20202000,
|
||||
0xf0f0f000, 0xb1b1b100, 0x84848400, 0x99999900,
|
||||
0xdfdfdf00, 0x4c4c4c00, 0xcbcbcb00, 0xc2c2c200,
|
||||
0x34343400, 0x7e7e7e00, 0x76767600, 0x05050500,
|
||||
0x6d6d6d00, 0xb7b7b700, 0xa9a9a900, 0x31313100,
|
||||
0xd1d1d100, 0x17171700, 0x04040400, 0xd7d7d700,
|
||||
0x14141400, 0x58585800, 0x3a3a3a00, 0x61616100,
|
||||
0xdedede00, 0x1b1b1b00, 0x11111100, 0x1c1c1c00,
|
||||
0x32323200, 0x0f0f0f00, 0x9c9c9c00, 0x16161600,
|
||||
0x53535300, 0x18181800, 0xf2f2f200, 0x22222200,
|
||||
0xfefefe00, 0x44444400, 0xcfcfcf00, 0xb2b2b200,
|
||||
0xc3c3c300, 0xb5b5b500, 0x7a7a7a00, 0x91919100,
|
||||
0x24242400, 0x08080800, 0xe8e8e800, 0xa8a8a800,
|
||||
0x60606000, 0xfcfcfc00, 0x69696900, 0x50505000,
|
||||
0xaaaaaa00, 0xd0d0d000, 0xa0a0a000, 0x7d7d7d00,
|
||||
0xa1a1a100, 0x89898900, 0x62626200, 0x97979700,
|
||||
0x54545400, 0x5b5b5b00, 0x1e1e1e00, 0x95959500,
|
||||
0xe0e0e000, 0xffffff00, 0x64646400, 0xd2d2d200,
|
||||
0x10101000, 0xc4c4c400, 0x00000000, 0x48484800,
|
||||
0xa3a3a300, 0xf7f7f700, 0x75757500, 0xdbdbdb00,
|
||||
0x8a8a8a00, 0x03030300, 0xe6e6e600, 0xdadada00,
|
||||
0x09090900, 0x3f3f3f00, 0xdddddd00, 0x94949400,
|
||||
0x87878700, 0x5c5c5c00, 0x83838300, 0x02020200,
|
||||
0xcdcdcd00, 0x4a4a4a00, 0x90909000, 0x33333300,
|
||||
0x73737300, 0x67676700, 0xf6f6f600, 0xf3f3f300,
|
||||
0x9d9d9d00, 0x7f7f7f00, 0xbfbfbf00, 0xe2e2e200,
|
||||
0x52525200, 0x9b9b9b00, 0xd8d8d800, 0x26262600,
|
||||
0xc8c8c800, 0x37373700, 0xc6c6c600, 0x3b3b3b00,
|
||||
0x81818100, 0x96969600, 0x6f6f6f00, 0x4b4b4b00,
|
||||
0x13131300, 0xbebebe00, 0x63636300, 0x2e2e2e00,
|
||||
0xe9e9e900, 0x79797900, 0xa7a7a700, 0x8c8c8c00,
|
||||
0x9f9f9f00, 0x6e6e6e00, 0xbcbcbc00, 0x8e8e8e00,
|
||||
0x29292900, 0xf5f5f500, 0xf9f9f900, 0xb6b6b600,
|
||||
0x2f2f2f00, 0xfdfdfd00, 0xb4b4b400, 0x59595900,
|
||||
0x78787800, 0x98989800, 0x06060600, 0x6a6a6a00,
|
||||
0xe7e7e700, 0x46464600, 0x71717100, 0xbababa00,
|
||||
0xd4d4d400, 0x25252500, 0xababab00, 0x42424200,
|
||||
0x88888800, 0xa2a2a200, 0x8d8d8d00, 0xfafafa00,
|
||||
0x72727200, 0x07070700, 0xb9b9b900, 0x55555500,
|
||||
0xf8f8f800, 0xeeeeee00, 0xacacac00, 0x0a0a0a00,
|
||||
0x36363600, 0x49494900, 0x2a2a2a00, 0x68686800,
|
||||
0x3c3c3c00, 0x38383800, 0xf1f1f100, 0xa4a4a400,
|
||||
0x40404000, 0x28282800, 0xd3d3d300, 0x7b7b7b00,
|
||||
0xbbbbbb00, 0xc9c9c900, 0x43434300, 0xc1c1c100,
|
||||
0x15151500, 0xe3e3e300, 0xadadad00, 0xf4f4f400,
|
||||
0x77777700, 0xc7c7c700, 0x80808000, 0x9e9e9e00
|
||||
},
|
||||
{
|
||||
0x00e0e0e0, 0x00050505, 0x00585858, 0x00d9d9d9,
|
||||
0x00676767, 0x004e4e4e, 0x00818181, 0x00cbcbcb,
|
||||
0x00c9c9c9, 0x000b0b0b, 0x00aeaeae, 0x006a6a6a,
|
||||
0x00d5d5d5, 0x00181818, 0x005d5d5d, 0x00828282,
|
||||
0x00464646, 0x00dfdfdf, 0x00d6d6d6, 0x00272727,
|
||||
0x008a8a8a, 0x00323232, 0x004b4b4b, 0x00424242,
|
||||
0x00dbdbdb, 0x001c1c1c, 0x009e9e9e, 0x009c9c9c,
|
||||
0x003a3a3a, 0x00cacaca, 0x00252525, 0x007b7b7b,
|
||||
0x000d0d0d, 0x00717171, 0x005f5f5f, 0x001f1f1f,
|
||||
0x00f8f8f8, 0x00d7d7d7, 0x003e3e3e, 0x009d9d9d,
|
||||
0x007c7c7c, 0x00606060, 0x00b9b9b9, 0x00bebebe,
|
||||
0x00bcbcbc, 0x008b8b8b, 0x00161616, 0x00343434,
|
||||
0x004d4d4d, 0x00c3c3c3, 0x00727272, 0x00959595,
|
||||
0x00ababab, 0x008e8e8e, 0x00bababa, 0x007a7a7a,
|
||||
0x00b3b3b3, 0x00020202, 0x00b4b4b4, 0x00adadad,
|
||||
0x00a2a2a2, 0x00acacac, 0x00d8d8d8, 0x009a9a9a,
|
||||
0x00171717, 0x001a1a1a, 0x00353535, 0x00cccccc,
|
||||
0x00f7f7f7, 0x00999999, 0x00616161, 0x005a5a5a,
|
||||
0x00e8e8e8, 0x00242424, 0x00565656, 0x00404040,
|
||||
0x00e1e1e1, 0x00636363, 0x00090909, 0x00333333,
|
||||
0x00bfbfbf, 0x00989898, 0x00979797, 0x00858585,
|
||||
0x00686868, 0x00fcfcfc, 0x00ececec, 0x000a0a0a,
|
||||
0x00dadada, 0x006f6f6f, 0x00535353, 0x00626262,
|
||||
0x00a3a3a3, 0x002e2e2e, 0x00080808, 0x00afafaf,
|
||||
0x00282828, 0x00b0b0b0, 0x00747474, 0x00c2c2c2,
|
||||
0x00bdbdbd, 0x00363636, 0x00222222, 0x00383838,
|
||||
0x00646464, 0x001e1e1e, 0x00393939, 0x002c2c2c,
|
||||
0x00a6a6a6, 0x00303030, 0x00e5e5e5, 0x00444444,
|
||||
0x00fdfdfd, 0x00888888, 0x009f9f9f, 0x00656565,
|
||||
0x00878787, 0x006b6b6b, 0x00f4f4f4, 0x00232323,
|
||||
0x00484848, 0x00101010, 0x00d1d1d1, 0x00515151,
|
||||
0x00c0c0c0, 0x00f9f9f9, 0x00d2d2d2, 0x00a0a0a0,
|
||||
0x00555555, 0x00a1a1a1, 0x00414141, 0x00fafafa,
|
||||
0x00434343, 0x00131313, 0x00c4c4c4, 0x002f2f2f,
|
||||
0x00a8a8a8, 0x00b6b6b6, 0x003c3c3c, 0x002b2b2b,
|
||||
0x00c1c1c1, 0x00ffffff, 0x00c8c8c8, 0x00a5a5a5,
|
||||
0x00202020, 0x00898989, 0x00000000, 0x00909090,
|
||||
0x00474747, 0x00efefef, 0x00eaeaea, 0x00b7b7b7,
|
||||
0x00151515, 0x00060606, 0x00cdcdcd, 0x00b5b5b5,
|
||||
0x00121212, 0x007e7e7e, 0x00bbbbbb, 0x00292929,
|
||||
0x000f0f0f, 0x00b8b8b8, 0x00070707, 0x00040404,
|
||||
0x009b9b9b, 0x00949494, 0x00212121, 0x00666666,
|
||||
0x00e6e6e6, 0x00cecece, 0x00ededed, 0x00e7e7e7,
|
||||
0x003b3b3b, 0x00fefefe, 0x007f7f7f, 0x00c5c5c5,
|
||||
0x00a4a4a4, 0x00373737, 0x00b1b1b1, 0x004c4c4c,
|
||||
0x00919191, 0x006e6e6e, 0x008d8d8d, 0x00767676,
|
||||
0x00030303, 0x002d2d2d, 0x00dedede, 0x00969696,
|
||||
0x00262626, 0x007d7d7d, 0x00c6c6c6, 0x005c5c5c,
|
||||
0x00d3d3d3, 0x00f2f2f2, 0x004f4f4f, 0x00191919,
|
||||
0x003f3f3f, 0x00dcdcdc, 0x00797979, 0x001d1d1d,
|
||||
0x00525252, 0x00ebebeb, 0x00f3f3f3, 0x006d6d6d,
|
||||
0x005e5e5e, 0x00fbfbfb, 0x00696969, 0x00b2b2b2,
|
||||
0x00f0f0f0, 0x00313131, 0x000c0c0c, 0x00d4d4d4,
|
||||
0x00cfcfcf, 0x008c8c8c, 0x00e2e2e2, 0x00757575,
|
||||
0x00a9a9a9, 0x004a4a4a, 0x00575757, 0x00848484,
|
||||
0x00111111, 0x00454545, 0x001b1b1b, 0x00f5f5f5,
|
||||
0x00e4e4e4, 0x000e0e0e, 0x00737373, 0x00aaaaaa,
|
||||
0x00f1f1f1, 0x00dddddd, 0x00595959, 0x00141414,
|
||||
0x006c6c6c, 0x00929292, 0x00545454, 0x00d0d0d0,
|
||||
0x00787878, 0x00707070, 0x00e3e3e3, 0x00494949,
|
||||
0x00808080, 0x00505050, 0x00a7a7a7, 0x00f6f6f6,
|
||||
0x00777777, 0x00939393, 0x00868686, 0x00838383,
|
||||
0x002a2a2a, 0x00c7c7c7, 0x005b5b5b, 0x00e9e9e9,
|
||||
0x00eeeeee, 0x008f8f8f, 0x00010101, 0x003d3d3d
|
||||
},
|
||||
{
|
||||
0x38003838, 0x41004141, 0x16001616, 0x76007676,
|
||||
0xd900d9d9, 0x93009393, 0x60006060, 0xf200f2f2,
|
||||
0x72007272, 0xc200c2c2, 0xab00abab, 0x9a009a9a,
|
||||
0x75007575, 0x06000606, 0x57005757, 0xa000a0a0,
|
||||
0x91009191, 0xf700f7f7, 0xb500b5b5, 0xc900c9c9,
|
||||
0xa200a2a2, 0x8c008c8c, 0xd200d2d2, 0x90009090,
|
||||
0xf600f6f6, 0x07000707, 0xa700a7a7, 0x27002727,
|
||||
0x8e008e8e, 0xb200b2b2, 0x49004949, 0xde00dede,
|
||||
0x43004343, 0x5c005c5c, 0xd700d7d7, 0xc700c7c7,
|
||||
0x3e003e3e, 0xf500f5f5, 0x8f008f8f, 0x67006767,
|
||||
0x1f001f1f, 0x18001818, 0x6e006e6e, 0xaf00afaf,
|
||||
0x2f002f2f, 0xe200e2e2, 0x85008585, 0x0d000d0d,
|
||||
0x53005353, 0xf000f0f0, 0x9c009c9c, 0x65006565,
|
||||
0xea00eaea, 0xa300a3a3, 0xae00aeae, 0x9e009e9e,
|
||||
0xec00ecec, 0x80008080, 0x2d002d2d, 0x6b006b6b,
|
||||
0xa800a8a8, 0x2b002b2b, 0x36003636, 0xa600a6a6,
|
||||
0xc500c5c5, 0x86008686, 0x4d004d4d, 0x33003333,
|
||||
0xfd00fdfd, 0x66006666, 0x58005858, 0x96009696,
|
||||
0x3a003a3a, 0x09000909, 0x95009595, 0x10001010,
|
||||
0x78007878, 0xd800d8d8, 0x42004242, 0xcc00cccc,
|
||||
0xef00efef, 0x26002626, 0xe500e5e5, 0x61006161,
|
||||
0x1a001a1a, 0x3f003f3f, 0x3b003b3b, 0x82008282,
|
||||
0xb600b6b6, 0xdb00dbdb, 0xd400d4d4, 0x98009898,
|
||||
0xe800e8e8, 0x8b008b8b, 0x02000202, 0xeb00ebeb,
|
||||
0x0a000a0a, 0x2c002c2c, 0x1d001d1d, 0xb000b0b0,
|
||||
0x6f006f6f, 0x8d008d8d, 0x88008888, 0x0e000e0e,
|
||||
0x19001919, 0x87008787, 0x4e004e4e, 0x0b000b0b,
|
||||
0xa900a9a9, 0x0c000c0c, 0x79007979, 0x11001111,
|
||||
0x7f007f7f, 0x22002222, 0xe700e7e7, 0x59005959,
|
||||
0xe100e1e1, 0xda00dada, 0x3d003d3d, 0xc800c8c8,
|
||||
0x12001212, 0x04000404, 0x74007474, 0x54005454,
|
||||
0x30003030, 0x7e007e7e, 0xb400b4b4, 0x28002828,
|
||||
0x55005555, 0x68006868, 0x50005050, 0xbe00bebe,
|
||||
0xd000d0d0, 0xc400c4c4, 0x31003131, 0xcb00cbcb,
|
||||
0x2a002a2a, 0xad00adad, 0x0f000f0f, 0xca00caca,
|
||||
0x70007070, 0xff00ffff, 0x32003232, 0x69006969,
|
||||
0x08000808, 0x62006262, 0x00000000, 0x24002424,
|
||||
0xd100d1d1, 0xfb00fbfb, 0xba00baba, 0xed00eded,
|
||||
0x45004545, 0x81008181, 0x73007373, 0x6d006d6d,
|
||||
0x84008484, 0x9f009f9f, 0xee00eeee, 0x4a004a4a,
|
||||
0xc300c3c3, 0x2e002e2e, 0xc100c1c1, 0x01000101,
|
||||
0xe600e6e6, 0x25002525, 0x48004848, 0x99009999,
|
||||
0xb900b9b9, 0xb300b3b3, 0x7b007b7b, 0xf900f9f9,
|
||||
0xce00cece, 0xbf00bfbf, 0xdf00dfdf, 0x71007171,
|
||||
0x29002929, 0xcd00cdcd, 0x6c006c6c, 0x13001313,
|
||||
0x64006464, 0x9b009b9b, 0x63006363, 0x9d009d9d,
|
||||
0xc000c0c0, 0x4b004b4b, 0xb700b7b7, 0xa500a5a5,
|
||||
0x89008989, 0x5f005f5f, 0xb100b1b1, 0x17001717,
|
||||
0xf400f4f4, 0xbc00bcbc, 0xd300d3d3, 0x46004646,
|
||||
0xcf00cfcf, 0x37003737, 0x5e005e5e, 0x47004747,
|
||||
0x94009494, 0xfa00fafa, 0xfc00fcfc, 0x5b005b5b,
|
||||
0x97009797, 0xfe00fefe, 0x5a005a5a, 0xac00acac,
|
||||
0x3c003c3c, 0x4c004c4c, 0x03000303, 0x35003535,
|
||||
0xf300f3f3, 0x23002323, 0xb800b8b8, 0x5d005d5d,
|
||||
0x6a006a6a, 0x92009292, 0xd500d5d5, 0x21002121,
|
||||
0x44004444, 0x51005151, 0xc600c6c6, 0x7d007d7d,
|
||||
0x39003939, 0x83008383, 0xdc00dcdc, 0xaa00aaaa,
|
||||
0x7c007c7c, 0x77007777, 0x56005656, 0x05000505,
|
||||
0x1b001b1b, 0xa400a4a4, 0x15001515, 0x34003434,
|
||||
0x1e001e1e, 0x1c001c1c, 0xf800f8f8, 0x52005252,
|
||||
0x20002020, 0x14001414, 0xe900e9e9, 0xbd00bdbd,
|
||||
0xdd00dddd, 0xe400e4e4, 0xa100a1a1, 0xe000e0e0,
|
||||
0x8a008a8a, 0xf100f1f1, 0xd600d6d6, 0x7a007a7a,
|
||||
0xbb00bbbb, 0xe300e3e3, 0x40004040, 0x4f004f4f
|
||||
},
|
||||
{
|
||||
0x70700070, 0x2c2c002c, 0xb3b300b3, 0xc0c000c0,
|
||||
0xe4e400e4, 0x57570057, 0xeaea00ea, 0xaeae00ae,
|
||||
0x23230023, 0x6b6b006b, 0x45450045, 0xa5a500a5,
|
||||
0xeded00ed, 0x4f4f004f, 0x1d1d001d, 0x92920092,
|
||||
0x86860086, 0xafaf00af, 0x7c7c007c, 0x1f1f001f,
|
||||
0x3e3e003e, 0xdcdc00dc, 0x5e5e005e, 0x0b0b000b,
|
||||
0xa6a600a6, 0x39390039, 0xd5d500d5, 0x5d5d005d,
|
||||
0xd9d900d9, 0x5a5a005a, 0x51510051, 0x6c6c006c,
|
||||
0x8b8b008b, 0x9a9a009a, 0xfbfb00fb, 0xb0b000b0,
|
||||
0x74740074, 0x2b2b002b, 0xf0f000f0, 0x84840084,
|
||||
0xdfdf00df, 0xcbcb00cb, 0x34340034, 0x76760076,
|
||||
0x6d6d006d, 0xa9a900a9, 0xd1d100d1, 0x04040004,
|
||||
0x14140014, 0x3a3a003a, 0xdede00de, 0x11110011,
|
||||
0x32320032, 0x9c9c009c, 0x53530053, 0xf2f200f2,
|
||||
0xfefe00fe, 0xcfcf00cf, 0xc3c300c3, 0x7a7a007a,
|
||||
0x24240024, 0xe8e800e8, 0x60600060, 0x69690069,
|
||||
0xaaaa00aa, 0xa0a000a0, 0xa1a100a1, 0x62620062,
|
||||
0x54540054, 0x1e1e001e, 0xe0e000e0, 0x64640064,
|
||||
0x10100010, 0x00000000, 0xa3a300a3, 0x75750075,
|
||||
0x8a8a008a, 0xe6e600e6, 0x09090009, 0xdddd00dd,
|
||||
0x87870087, 0x83830083, 0xcdcd00cd, 0x90900090,
|
||||
0x73730073, 0xf6f600f6, 0x9d9d009d, 0xbfbf00bf,
|
||||
0x52520052, 0xd8d800d8, 0xc8c800c8, 0xc6c600c6,
|
||||
0x81810081, 0x6f6f006f, 0x13130013, 0x63630063,
|
||||
0xe9e900e9, 0xa7a700a7, 0x9f9f009f, 0xbcbc00bc,
|
||||
0x29290029, 0xf9f900f9, 0x2f2f002f, 0xb4b400b4,
|
||||
0x78780078, 0x06060006, 0xe7e700e7, 0x71710071,
|
||||
0xd4d400d4, 0xabab00ab, 0x88880088, 0x8d8d008d,
|
||||
0x72720072, 0xb9b900b9, 0xf8f800f8, 0xacac00ac,
|
||||
0x36360036, 0x2a2a002a, 0x3c3c003c, 0xf1f100f1,
|
||||
0x40400040, 0xd3d300d3, 0xbbbb00bb, 0x43430043,
|
||||
0x15150015, 0xadad00ad, 0x77770077, 0x80800080,
|
||||
0x82820082, 0xecec00ec, 0x27270027, 0xe5e500e5,
|
||||
0x85850085, 0x35350035, 0x0c0c000c, 0x41410041,
|
||||
0xefef00ef, 0x93930093, 0x19190019, 0x21210021,
|
||||
0x0e0e000e, 0x4e4e004e, 0x65650065, 0xbdbd00bd,
|
||||
0xb8b800b8, 0x8f8f008f, 0xebeb00eb, 0xcece00ce,
|
||||
0x30300030, 0x5f5f005f, 0xc5c500c5, 0x1a1a001a,
|
||||
0xe1e100e1, 0xcaca00ca, 0x47470047, 0x3d3d003d,
|
||||
0x01010001, 0xd6d600d6, 0x56560056, 0x4d4d004d,
|
||||
0x0d0d000d, 0x66660066, 0xcccc00cc, 0x2d2d002d,
|
||||
0x12120012, 0x20200020, 0xb1b100b1, 0x99990099,
|
||||
0x4c4c004c, 0xc2c200c2, 0x7e7e007e, 0x05050005,
|
||||
0xb7b700b7, 0x31310031, 0x17170017, 0xd7d700d7,
|
||||
0x58580058, 0x61610061, 0x1b1b001b, 0x1c1c001c,
|
||||
0x0f0f000f, 0x16160016, 0x18180018, 0x22220022,
|
||||
0x44440044, 0xb2b200b2, 0xb5b500b5, 0x91910091,
|
||||
0x08080008, 0xa8a800a8, 0xfcfc00fc, 0x50500050,
|
||||
0xd0d000d0, 0x7d7d007d, 0x89890089, 0x97970097,
|
||||
0x5b5b005b, 0x95950095, 0xffff00ff, 0xd2d200d2,
|
||||
0xc4c400c4, 0x48480048, 0xf7f700f7, 0xdbdb00db,
|
||||
0x03030003, 0xdada00da, 0x3f3f003f, 0x94940094,
|
||||
0x5c5c005c, 0x02020002, 0x4a4a004a, 0x33330033,
|
||||
0x67670067, 0xf3f300f3, 0x7f7f007f, 0xe2e200e2,
|
||||
0x9b9b009b, 0x26260026, 0x37370037, 0x3b3b003b,
|
||||
0x96960096, 0x4b4b004b, 0xbebe00be, 0x2e2e002e,
|
||||
0x79790079, 0x8c8c008c, 0x6e6e006e, 0x8e8e008e,
|
||||
0xf5f500f5, 0xb6b600b6, 0xfdfd00fd, 0x59590059,
|
||||
0x98980098, 0x6a6a006a, 0x46460046, 0xbaba00ba,
|
||||
0x25250025, 0x42420042, 0xa2a200a2, 0xfafa00fa,
|
||||
0x07070007, 0x55550055, 0xeeee00ee, 0x0a0a000a,
|
||||
0x49490049, 0x68680068, 0x38380038, 0xa4a400a4,
|
||||
0x28280028, 0x7b7b007b, 0xc9c900c9, 0xc1c100c1,
|
||||
0xe3e300e3, 0xf4f400f4, 0xc7c700c7, 0x9e9e009e
|
||||
}};
|
||||
|
||||
NAMESPACE_END
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
// camellia.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file camellia.h
|
||||
/// \brief Classes for the Camellia block cipher
|
||||
|
||||
#ifndef CRYPTOPP_CAMELLIA_H
|
||||
#define CRYPTOPP_CAMELLIA_H
|
||||
|
||||
#include "config.h"
|
||||
#include "seckey.h"
|
||||
#include "secblock.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief Camellia block cipher information
|
||||
struct Camellia_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 32, 8>
|
||||
{
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "Camellia";}
|
||||
};
|
||||
|
||||
/// \brief Camellia block cipher
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/Camellia">Camellia</a>
|
||||
class Camellia : public Camellia_Info, public BlockCipherDocumentation
|
||||
{
|
||||
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<Camellia_Info>
|
||||
{
|
||||
public:
|
||||
void UncheckedSetKey(const byte *key, unsigned int keylen, const NameValuePairs ¶ms);
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
|
||||
protected:
|
||||
CRYPTOPP_ALIGN_DATA(4) static const byte s1[256];
|
||||
static const word32 SP[4][256];
|
||||
|
||||
unsigned int m_rounds;
|
||||
SecBlock<word32> m_key;
|
||||
};
|
||||
|
||||
public:
|
||||
typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
|
||||
typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
|
||||
};
|
||||
|
||||
typedef Camellia::Encryption CamelliaEncryption;
|
||||
typedef Camellia::Decryption CamelliaDecryption;
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
// cast.cpp - originally written and placed in the public domain by Wei Dai and Leonard Janke
|
||||
// based on Steve Reid's public domain cast.c
|
||||
|
||||
#include "pch.h"
|
||||
#include "cast.h"
|
||||
#include "misc.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/* Macros to access 8-bit bytes out of a 32-bit word */
|
||||
#define U8a(x) GETBYTE(x,3)
|
||||
#define U8b(x) GETBYTE(x,2)
|
||||
#define U8c(x) GETBYTE(x,1)
|
||||
#define U8d(x) GETBYTE(x,0)
|
||||
|
||||
/* CAST uses three different round functions */
|
||||
#define f1(l, r, km, 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 = 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 = rotlVariable(km - r, kr); \
|
||||
l ^= ((S[0][U8a(t)] + S[1][U8b(t)]) ^ \
|
||||
S[2][U8c(t)]) - S[3][U8d(t)];
|
||||
|
||||
#define F1(l, r, i, j) f1(l, r, K[i], K[i+j])
|
||||
#define F2(l, r, i, j) f2(l, r, K[i], K[i+j])
|
||||
#define F3(l, r, i, j) f3(l, r, K[i], K[i+j])
|
||||
|
||||
typedef BlockGetAndPut<word32, BigEndian> Block;
|
||||
|
||||
void CAST128::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
word32 &t=m_t[0], &l=m_t[1], &r=m_t[2];
|
||||
|
||||
/* Get inblock into l,r */
|
||||
Block::Get(inBlock)(l)(r);
|
||||
/* Do the work */
|
||||
F1(l, r, 0, 16);
|
||||
F2(r, l, 1, 16);
|
||||
F3(l, r, 2, 16);
|
||||
F1(r, l, 3, 16);
|
||||
F2(l, r, 4, 16);
|
||||
F3(r, l, 5, 16);
|
||||
F1(l, r, 6, 16);
|
||||
F2(r, l, 7, 16);
|
||||
F3(l, r, 8, 16);
|
||||
F1(r, l, 9, 16);
|
||||
F2(l, r, 10, 16);
|
||||
F3(r, l, 11, 16);
|
||||
/* Only do full 16 rounds if key length > 80 bits */
|
||||
if (!reduced) {
|
||||
F1(l, r, 12, 16);
|
||||
F2(r, l, 13, 16);
|
||||
F3(l, r, 14, 16);
|
||||
F1(r, l, 15, 16);
|
||||
}
|
||||
/* Put l,r into outblock */
|
||||
Block::Put(xorBlock, outBlock)(r)(l);
|
||||
}
|
||||
|
||||
void CAST128::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
word32 &t=m_t[0], &l=m_t[1], &r=m_t[2];
|
||||
|
||||
/* Get inblock into l,r */
|
||||
Block::Get(inBlock)(r)(l);
|
||||
/* Only do full 16 rounds if key length > 80 bits */
|
||||
if (!reduced) {
|
||||
F1(r, l, 15, 16);
|
||||
F3(l, r, 14, 16);
|
||||
F2(r, l, 13, 16);
|
||||
F1(l, r, 12, 16);
|
||||
}
|
||||
F3(r, l, 11, 16);
|
||||
F2(l, r, 10, 16);
|
||||
F1(r, l, 9, 16);
|
||||
F3(l, r, 8, 16);
|
||||
F2(r, l, 7, 16);
|
||||
F1(l, r, 6, 16);
|
||||
F3(r, l, 5, 16);
|
||||
F2(l, r, 4, 16);
|
||||
F1(r, l, 3, 16);
|
||||
F3(l, r, 2, 16);
|
||||
F2(r, l, 1, 16);
|
||||
F1(l, r, 0, 16);
|
||||
/* Put l,r into outblock */
|
||||
Block::Put(xorBlock, outBlock)(l)(r);
|
||||
}
|
||||
|
||||
void CAST128::Base::UncheckedSetKey(const byte *userKey, unsigned int keylength, const NameValuePairs &)
|
||||
{
|
||||
AssertValidKeyLength(keylength);
|
||||
|
||||
reduced = (keylength <= 10);
|
||||
|
||||
word32 X[4], Z[4]={0};
|
||||
GetUserKey(BIG_ENDIAN_ORDER, X, 4, userKey, keylength);
|
||||
|
||||
#define x(i) GETBYTE(X[i/4], 3-i%4)
|
||||
#define z(i) GETBYTE(Z[i/4], 3-i%4)
|
||||
|
||||
unsigned int i;
|
||||
for (i=0; i<=16; i+=16)
|
||||
{
|
||||
// this part is copied directly from RFC 2144 (with some search and replace) by Wei Dai
|
||||
Z[0] = X[0] ^ S[4][x(0xD)] ^ S[5][x(0xF)] ^ S[6][x(0xC)] ^ S[7][x(0xE)] ^ S[6][x(0x8)];
|
||||
Z[1] = X[2] ^ S[4][z(0x0)] ^ S[5][z(0x2)] ^ S[6][z(0x1)] ^ S[7][z(0x3)] ^ S[7][x(0xA)];
|
||||
Z[2] = X[3] ^ S[4][z(0x7)] ^ S[5][z(0x6)] ^ S[6][z(0x5)] ^ S[7][z(0x4)] ^ S[4][x(0x9)];
|
||||
Z[3] = X[1] ^ S[4][z(0xA)] ^ S[5][z(0x9)] ^ S[6][z(0xB)] ^ S[7][z(0x8)] ^ S[5][x(0xB)];
|
||||
K[i+0] = S[4][z(0x8)] ^ S[5][z(0x9)] ^ S[6][z(0x7)] ^ S[7][z(0x6)] ^ S[4][z(0x2)];
|
||||
K[i+1] = S[4][z(0xA)] ^ S[5][z(0xB)] ^ S[6][z(0x5)] ^ S[7][z(0x4)] ^ S[5][z(0x6)];
|
||||
K[i+2] = S[4][z(0xC)] ^ S[5][z(0xD)] ^ S[6][z(0x3)] ^ S[7][z(0x2)] ^ S[6][z(0x9)];
|
||||
K[i+3] = S[4][z(0xE)] ^ S[5][z(0xF)] ^ S[6][z(0x1)] ^ S[7][z(0x0)] ^ S[7][z(0xC)];
|
||||
X[0] = Z[2] ^ S[4][z(0x5)] ^ S[5][z(0x7)] ^ S[6][z(0x4)] ^ S[7][z(0x6)] ^ S[6][z(0x0)];
|
||||
X[1] = Z[0] ^ S[4][x(0x0)] ^ S[5][x(0x2)] ^ S[6][x(0x1)] ^ S[7][x(0x3)] ^ S[7][z(0x2)];
|
||||
X[2] = Z[1] ^ S[4][x(0x7)] ^ S[5][x(0x6)] ^ S[6][x(0x5)] ^ S[7][x(0x4)] ^ S[4][z(0x1)];
|
||||
X[3] = Z[3] ^ S[4][x(0xA)] ^ S[5][x(0x9)] ^ S[6][x(0xB)] ^ S[7][x(0x8)] ^ S[5][z(0x3)];
|
||||
K[i+4] = S[4][x(0x3)] ^ S[5][x(0x2)] ^ S[6][x(0xC)] ^ S[7][x(0xD)] ^ S[4][x(0x8)];
|
||||
K[i+5] = S[4][x(0x1)] ^ S[5][x(0x0)] ^ S[6][x(0xE)] ^ S[7][x(0xF)] ^ S[5][x(0xD)];
|
||||
K[i+6] = S[4][x(0x7)] ^ S[5][x(0x6)] ^ S[6][x(0x8)] ^ S[7][x(0x9)] ^ S[6][x(0x3)];
|
||||
K[i+7] = S[4][x(0x5)] ^ S[5][x(0x4)] ^ S[6][x(0xA)] ^ S[7][x(0xB)] ^ S[7][x(0x7)];
|
||||
Z[0] = X[0] ^ S[4][x(0xD)] ^ S[5][x(0xF)] ^ S[6][x(0xC)] ^ S[7][x(0xE)] ^ S[6][x(0x8)];
|
||||
Z[1] = X[2] ^ S[4][z(0x0)] ^ S[5][z(0x2)] ^ S[6][z(0x1)] ^ S[7][z(0x3)] ^ S[7][x(0xA)];
|
||||
Z[2] = X[3] ^ S[4][z(0x7)] ^ S[5][z(0x6)] ^ S[6][z(0x5)] ^ S[7][z(0x4)] ^ S[4][x(0x9)];
|
||||
Z[3] = X[1] ^ S[4][z(0xA)] ^ S[5][z(0x9)] ^ S[6][z(0xB)] ^ S[7][z(0x8)] ^ S[5][x(0xB)];
|
||||
K[i+8] = S[4][z(0x3)] ^ S[5][z(0x2)] ^ S[6][z(0xC)] ^ S[7][z(0xD)] ^ S[4][z(0x9)];
|
||||
K[i+9] = S[4][z(0x1)] ^ S[5][z(0x0)] ^ S[6][z(0xE)] ^ S[7][z(0xF)] ^ S[5][z(0xC)];
|
||||
K[i+10] = S[4][z(0x7)] ^ S[5][z(0x6)] ^ S[6][z(0x8)] ^ S[7][z(0x9)] ^ S[6][z(0x2)];
|
||||
K[i+11] = S[4][z(0x5)] ^ S[5][z(0x4)] ^ S[6][z(0xA)] ^ S[7][z(0xB)] ^ S[7][z(0x6)];
|
||||
X[0] = Z[2] ^ S[4][z(0x5)] ^ S[5][z(0x7)] ^ S[6][z(0x4)] ^ S[7][z(0x6)] ^ S[6][z(0x0)];
|
||||
X[1] = Z[0] ^ S[4][x(0x0)] ^ S[5][x(0x2)] ^ S[6][x(0x1)] ^ S[7][x(0x3)] ^ S[7][z(0x2)];
|
||||
X[2] = Z[1] ^ S[4][x(0x7)] ^ S[5][x(0x6)] ^ S[6][x(0x5)] ^ S[7][x(0x4)] ^ S[4][z(0x1)];
|
||||
X[3] = Z[3] ^ S[4][x(0xA)] ^ S[5][x(0x9)] ^ S[6][x(0xB)] ^ S[7][x(0x8)] ^ S[5][z(0x3)];
|
||||
K[i+12] = S[4][x(0x8)] ^ S[5][x(0x9)] ^ S[6][x(0x7)] ^ S[7][x(0x6)] ^ S[4][x(0x3)];
|
||||
K[i+13] = S[4][x(0xA)] ^ S[5][x(0xB)] ^ S[6][x(0x5)] ^ S[7][x(0x4)] ^ S[5][x(0x7)];
|
||||
K[i+14] = S[4][x(0xC)] ^ S[5][x(0xD)] ^ S[6][x(0x3)] ^ S[7][x(0x2)] ^ S[6][x(0x8)];
|
||||
K[i+15] = S[4][x(0xE)] ^ S[5][x(0xF)] ^ S[6][x(0x1)] ^ S[7][x(0x0)] ^ S[7][x(0xD)];
|
||||
}
|
||||
|
||||
for (i=16; i<32; i++)
|
||||
K[i] &= 0x1f;
|
||||
}
|
||||
|
||||
// The following CAST-256 implementation was contributed by Leonard Janke
|
||||
|
||||
const word32 CAST256::Base::t_m[8][24]={
|
||||
{ 0x5a827999, 0xd151d6a1, 0x482133a9, 0xbef090b1, 0x35bfedb9, 0xac8f4ac1,
|
||||
0x235ea7c9, 0x9a2e04d1, 0x10fd61d9, 0x87ccbee1, 0xfe9c1be9, 0x756b78f1,
|
||||
0xec3ad5f9, 0x630a3301, 0xd9d99009, 0x50a8ed11, 0xc7784a19, 0x3e47a721,
|
||||
0xb5170429, 0x2be66131, 0xa2b5be39, 0x19851b41, 0x90547849, 0x0723d551},
|
||||
{ 0xc95c653a, 0x402bc242, 0xb6fb1f4a, 0x2dca7c52, 0xa499d95a, 0x1b693662,
|
||||
0x9238936a, 0x0907f072, 0x7fd74d7a, 0xf6a6aa82, 0x6d76078a, 0xe4456492,
|
||||
0x5b14c19a, 0xd1e41ea2, 0x48b37baa, 0xbf82d8b2, 0x365235ba, 0xad2192c2,
|
||||
0x23f0efca, 0x9ac04cd2, 0x118fa9da, 0x885f06e2, 0xff2e63ea, 0x75fdc0f2},
|
||||
{ 0x383650db, 0xaf05ade3, 0x25d50aeb, 0x9ca467f3, 0x1373c4fb, 0x8a432203,
|
||||
0x01127f0b, 0x77e1dc13, 0xeeb1391b, 0x65809623, 0xdc4ff32b, 0x531f5033,
|
||||
0xc9eead3b, 0x40be0a43, 0xb78d674b, 0x2e5cc453, 0xa52c215b, 0x1bfb7e63,
|
||||
0x92cadb6b, 0x099a3873, 0x8069957b, 0xf738f283, 0x6e084f8b, 0xe4d7ac93},
|
||||
{ 0xa7103c7c, 0x1ddf9984, 0x94aef68c, 0x0b7e5394, 0x824db09c, 0xf91d0da4,
|
||||
0x6fec6aac, 0xe6bbc7b4, 0x5d8b24bc, 0xd45a81c4, 0x4b29decc, 0xc1f93bd4,
|
||||
0x38c898dc, 0xaf97f5e4, 0x266752ec, 0x9d36aff4, 0x14060cfc, 0x8ad56a04,
|
||||
0x01a4c70c, 0x78742414, 0xef43811c, 0x6612de24, 0xdce23b2c, 0x53b19834},
|
||||
{ 0x15ea281d, 0x8cb98525, 0x0388e22d, 0x7a583f35, 0xf1279c3d, 0x67f6f945,
|
||||
0xdec6564d, 0x5595b355, 0xcc65105d, 0x43346d65, 0xba03ca6d, 0x30d32775,
|
||||
0xa7a2847d, 0x1e71e185, 0x95413e8d, 0x0c109b95, 0x82dff89d, 0xf9af55a5,
|
||||
0x707eb2ad, 0xe74e0fb5, 0x5e1d6cbd, 0xd4ecc9c5, 0x4bbc26cd, 0xc28b83d5},
|
||||
{ 0x84c413be, 0xfb9370c6, 0x7262cdce, 0xe9322ad6, 0x600187de, 0xd6d0e4e6,
|
||||
0x4da041ee, 0xc46f9ef6, 0x3b3efbfe, 0xb20e5906, 0x28ddb60e, 0x9fad1316,
|
||||
0x167c701e, 0x8d4bcd26, 0x041b2a2e, 0x7aea8736, 0xf1b9e43e, 0x68894146,
|
||||
0xdf589e4e, 0x5627fb56, 0xccf7585e, 0x43c6b566, 0xba96126e, 0x31656f76},
|
||||
{ 0xf39dff5f, 0x6a6d5c67, 0xe13cb96f, 0x580c1677, 0xcedb737f, 0x45aad087,
|
||||
0xbc7a2d8f, 0x33498a97, 0xaa18e79f, 0x20e844a7, 0x97b7a1af, 0x0e86feb7,
|
||||
0x85565bbf, 0xfc25b8c7, 0x72f515cf, 0xe9c472d7, 0x6093cfdf, 0xd7632ce7,
|
||||
0x4e3289ef, 0xc501e6f7, 0x3bd143ff, 0xb2a0a107, 0x296ffe0f, 0xa03f5b17},
|
||||
{ 0x6277eb00, 0xd9474808, 0x5016a510, 0xc6e60218, 0x3db55f20, 0xb484bc28,
|
||||
0x2b541930, 0xa2237638, 0x18f2d340, 0x8fc23048, 0x06918d50, 0x7d60ea58,
|
||||
0xf4304760, 0x6affa468, 0xe1cf0170, 0x589e5e78, 0xcf6dbb80, 0x463d1888,
|
||||
0xbd0c7590, 0x33dbd298, 0xaaab2fa0, 0x217a8ca8, 0x9849e9b0, 0x0f1946b8}
|
||||
};
|
||||
|
||||
const unsigned int CAST256::Base::t_r[8][24]={
|
||||
{19, 27, 3, 11, 19, 27, 3, 11, 19, 27, 3, 11, 19, 27, 3, 11, 19, 27, 3, 11, 19, 27, 3, 11},
|
||||
{4, 12, 20, 28, 4, 12, 20, 28, 4, 12, 20, 28, 4, 12, 20, 28, 4, 12, 20, 28, 4, 12, 20, 28},
|
||||
{21, 29, 5, 13, 21, 29, 5, 13, 21, 29, 5, 13, 21, 29, 5, 13, 21, 29, 5, 13, 21, 29, 5, 13},
|
||||
{6, 14, 22, 30, 6, 14, 22, 30, 6, 14, 22, 30, 6, 14, 22, 30, 6, 14, 22, 30, 6, 14, 22, 30},
|
||||
{23, 31, 7, 15, 23, 31, 7, 15, 23, 31, 7, 15, 23, 31, 7, 15, 23, 31, 7, 15, 23, 31, 7, 15},
|
||||
{8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0},
|
||||
{25, 1, 9, 17, 25, 1, 9, 17, 25, 1, 9, 17, 25, 1, 9, 17, 25, 1, 9, 17, 25, 1, 9, 17},
|
||||
{10, 18, 26, 2, 10, 18, 26, 2, 10, 18, 26, 2, 10, 18, 26, 2, 10, 18, 26, 2, 10, 18, 26, 2}
|
||||
};
|
||||
|
||||
#define Q(i) \
|
||||
F1(block[2],block[3],8*i+4,-4); \
|
||||
F2(block[1],block[2],8*i+5,-4); \
|
||||
F3(block[0],block[1],8*i+6,-4); \
|
||||
F1(block[3],block[0],8*i+7,-4);
|
||||
|
||||
#define QBar(i) \
|
||||
F1(block[3],block[0],8*i+7,-4); \
|
||||
F3(block[0],block[1],8*i+6,-4); \
|
||||
F2(block[1],block[2],8*i+5,-4); \
|
||||
F1(block[2],block[3],8*i+4,-4);
|
||||
|
||||
/* CAST256's encrypt/decrypt functions are identical except for the order that
|
||||
the keys are used */
|
||||
|
||||
void CAST256::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
// TODO: add a SecBlock workspace to the class when the ABI can change
|
||||
word32 t, block[4];
|
||||
Block::Get(inBlock)(block[0])(block[1])(block[2])(block[3]);
|
||||
|
||||
// Perform 6 forward quad rounds
|
||||
Q(0);
|
||||
Q(1);
|
||||
Q(2);
|
||||
Q(3);
|
||||
Q(4);
|
||||
Q(5);
|
||||
|
||||
// Perform 6 reverse quad rounds
|
||||
QBar(6);
|
||||
QBar(7);
|
||||
QBar(8);
|
||||
QBar(9);
|
||||
QBar(10);
|
||||
QBar(11);
|
||||
|
||||
Block::Put(xorBlock, outBlock)(block[0])(block[1])(block[2])(block[3]);
|
||||
}
|
||||
|
||||
/* Set up a CAST-256 key */
|
||||
|
||||
void CAST256::Base::Omega(int i, word32 kappa[8])
|
||||
{
|
||||
word32 t;
|
||||
|
||||
f1(kappa[6],kappa[7],t_m[0][i],t_r[0][i]);
|
||||
f2(kappa[5],kappa[6],t_m[1][i],t_r[1][i]);
|
||||
f3(kappa[4],kappa[5],t_m[2][i],t_r[2][i]);
|
||||
f1(kappa[3],kappa[4],t_m[3][i],t_r[3][i]);
|
||||
f2(kappa[2],kappa[3],t_m[4][i],t_r[4][i]);
|
||||
f3(kappa[1],kappa[2],t_m[5][i],t_r[5][i]);
|
||||
f1(kappa[0],kappa[1],t_m[6][i],t_r[6][i]);
|
||||
f2(kappa[7],kappa[0],t_m[7][i],t_r[7][i]);
|
||||
}
|
||||
|
||||
void CAST256::Base::UncheckedSetKey(const byte *userKey, unsigned int keylength, const NameValuePairs &)
|
||||
{
|
||||
AssertValidKeyLength(keylength);
|
||||
|
||||
GetUserKey(BIG_ENDIAN_ORDER, kappa.begin(), 8, userKey, keylength);
|
||||
|
||||
for(int i=0; i<12; ++i)
|
||||
{
|
||||
Omega(2*i,kappa);
|
||||
Omega(2*i+1,kappa);
|
||||
|
||||
K[8*i]=kappa[0] & 31;
|
||||
K[8*i+1]=kappa[2] & 31;
|
||||
K[8*i+2]=kappa[4] & 31;
|
||||
K[8*i+3]=kappa[6] & 31;
|
||||
K[8*i+4]=kappa[7];
|
||||
K[8*i+5]=kappa[5];
|
||||
K[8*i+6]=kappa[3];
|
||||
K[8*i+7]=kappa[1];
|
||||
}
|
||||
|
||||
if (!IsForwardTransformation())
|
||||
{
|
||||
for(int j=0; j<6; ++j)
|
||||
{
|
||||
for(int i=0; i<4; ++i)
|
||||
{
|
||||
int i1=8*j+i;
|
||||
int i2=8*(11-j)+i;
|
||||
|
||||
CRYPTOPP_ASSERT(i1<i2);
|
||||
|
||||
std::swap(K[i1],K[i2]);
|
||||
std::swap(K[i1+4],K[i2+4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
// cast.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file cast.h
|
||||
/// \brief Classes for the CAST-128 and CAST-256 block ciphers
|
||||
/// \since Crypto++ 2.2
|
||||
|
||||
#ifndef CRYPTOPP_CAST_H
|
||||
#define CRYPTOPP_CAST_H
|
||||
|
||||
#include "seckey.h"
|
||||
#include "secblock.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief CAST block cipher base
|
||||
/// \since Crypto++ 2.2
|
||||
class CAST
|
||||
{
|
||||
protected:
|
||||
static const word32 S[8][256];
|
||||
};
|
||||
|
||||
/// \brief CAST128 block cipher information
|
||||
/// \since Crypto++ 2.2
|
||||
struct CAST128_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 5, 16>
|
||||
{
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "CAST-128";}
|
||||
};
|
||||
|
||||
/// \brief CAST128 block cipher
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/CAST-128">CAST-128</a>
|
||||
/// \since Crypto++ 2.2
|
||||
class CAST128 : public CAST128_Info, public BlockCipherDocumentation
|
||||
{
|
||||
/// \brief CAST128 block cipher default operation
|
||||
class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherImpl<CAST128_Info>
|
||||
{
|
||||
public:
|
||||
void UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs ¶ms);
|
||||
|
||||
protected:
|
||||
bool reduced;
|
||||
FixedSizeSecBlock<word32, 32> K;
|
||||
mutable FixedSizeSecBlock<word32, 3> m_t;
|
||||
};
|
||||
|
||||
/// \brief CAST128 block cipher encryption operation
|
||||
class CRYPTOPP_NO_VTABLE Enc : public Base
|
||||
{
|
||||
public:
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
};
|
||||
|
||||
/// \brief CAST128 block cipher decryption operation
|
||||
class CRYPTOPP_NO_VTABLE Dec : public Base
|
||||
{
|
||||
public:
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
};
|
||||
|
||||
public:
|
||||
typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
|
||||
typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
|
||||
};
|
||||
|
||||
/// \brief CAST256 block cipher information
|
||||
/// \since Crypto++ 4.0
|
||||
struct CAST256_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 32, 4>
|
||||
{
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "CAST-256";}
|
||||
};
|
||||
|
||||
/// \brief CAST256 block cipher
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/CAST-256">CAST-256</a>
|
||||
/// \since Crypto++ 4.0
|
||||
class CAST256 : public CAST256_Info, public BlockCipherDocumentation
|
||||
{
|
||||
/// \brief CAST256 block cipher default operation
|
||||
class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherImpl<CAST256_Info>
|
||||
{
|
||||
public:
|
||||
void UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs ¶ms);
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
|
||||
protected:
|
||||
static const word32 t_m[8][24];
|
||||
static const unsigned int t_r[8][24];
|
||||
|
||||
static void Omega(int i, word32 kappa[8]);
|
||||
|
||||
FixedSizeSecBlock<word32, 8*12> K;
|
||||
mutable FixedSizeSecBlock<word32, 8> kappa;
|
||||
mutable FixedSizeSecBlock<word32, 3> m_t;
|
||||
};
|
||||
|
||||
public:
|
||||
typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
|
||||
typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
|
||||
};
|
||||
|
||||
typedef CAST128::Encryption CAST128Encryption;
|
||||
typedef CAST128::Decryption CAST128Decryption;
|
||||
|
||||
typedef CAST256::Encryption CAST256Encryption;
|
||||
typedef CAST256::Decryption CAST256Decryption;
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+545
@@ -0,0 +1,545 @@
|
||||
#include "pch.h"
|
||||
#include "cast.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
// CAST S-boxes
|
||||
|
||||
const word32 CAST::S[8][256] = {
|
||||
{
|
||||
0x30FB40D4UL, 0x9FA0FF0BUL, 0x6BECCD2FUL, 0x3F258C7AUL,
|
||||
0x1E213F2FUL, 0x9C004DD3UL, 0x6003E540UL, 0xCF9FC949UL,
|
||||
0xBFD4AF27UL, 0x88BBBDB5UL, 0xE2034090UL, 0x98D09675UL,
|
||||
0x6E63A0E0UL, 0x15C361D2UL, 0xC2E7661DUL, 0x22D4FF8EUL,
|
||||
0x28683B6FUL, 0xC07FD059UL, 0xFF2379C8UL, 0x775F50E2UL,
|
||||
0x43C340D3UL, 0xDF2F8656UL, 0x887CA41AUL, 0xA2D2BD2DUL,
|
||||
0xA1C9E0D6UL, 0x346C4819UL, 0x61B76D87UL, 0x22540F2FUL,
|
||||
0x2ABE32E1UL, 0xAA54166BUL, 0x22568E3AUL, 0xA2D341D0UL,
|
||||
0x66DB40C8UL, 0xA784392FUL, 0x004DFF2FUL, 0x2DB9D2DEUL,
|
||||
0x97943FACUL, 0x4A97C1D8UL, 0x527644B7UL, 0xB5F437A7UL,
|
||||
0xB82CBAEFUL, 0xD751D159UL, 0x6FF7F0EDUL, 0x5A097A1FUL,
|
||||
0x827B68D0UL, 0x90ECF52EUL, 0x22B0C054UL, 0xBC8E5935UL,
|
||||
0x4B6D2F7FUL, 0x50BB64A2UL, 0xD2664910UL, 0xBEE5812DUL,
|
||||
0xB7332290UL, 0xE93B159FUL, 0xB48EE411UL, 0x4BFF345DUL,
|
||||
0xFD45C240UL, 0xAD31973FUL, 0xC4F6D02EUL, 0x55FC8165UL,
|
||||
0xD5B1CAADUL, 0xA1AC2DAEUL, 0xA2D4B76DUL, 0xC19B0C50UL,
|
||||
0x882240F2UL, 0x0C6E4F38UL, 0xA4E4BFD7UL, 0x4F5BA272UL,
|
||||
0x564C1D2FUL, 0xC59C5319UL, 0xB949E354UL, 0xB04669FEUL,
|
||||
0xB1B6AB8AUL, 0xC71358DDUL, 0x6385C545UL, 0x110F935DUL,
|
||||
0x57538AD5UL, 0x6A390493UL, 0xE63D37E0UL, 0x2A54F6B3UL,
|
||||
0x3A787D5FUL, 0x6276A0B5UL, 0x19A6FCDFUL, 0x7A42206AUL,
|
||||
0x29F9D4D5UL, 0xF61B1891UL, 0xBB72275EUL, 0xAA508167UL,
|
||||
0x38901091UL, 0xC6B505EBUL, 0x84C7CB8CUL, 0x2AD75A0FUL,
|
||||
0x874A1427UL, 0xA2D1936BUL, 0x2AD286AFUL, 0xAA56D291UL,
|
||||
0xD7894360UL, 0x425C750DUL, 0x93B39E26UL, 0x187184C9UL,
|
||||
0x6C00B32DUL, 0x73E2BB14UL, 0xA0BEBC3CUL, 0x54623779UL,
|
||||
0x64459EABUL, 0x3F328B82UL, 0x7718CF82UL, 0x59A2CEA6UL,
|
||||
0x04EE002EUL, 0x89FE78E6UL, 0x3FAB0950UL, 0x325FF6C2UL,
|
||||
0x81383F05UL, 0x6963C5C8UL, 0x76CB5AD6UL, 0xD49974C9UL,
|
||||
0xCA180DCFUL, 0x380782D5UL, 0xC7FA5CF6UL, 0x8AC31511UL,
|
||||
0x35E79E13UL, 0x47DA91D0UL, 0xF40F9086UL, 0xA7E2419EUL,
|
||||
0x31366241UL, 0x051EF495UL, 0xAA573B04UL, 0x4A805D8DUL,
|
||||
0x548300D0UL, 0x00322A3CUL, 0xBF64CDDFUL, 0xBA57A68EUL,
|
||||
0x75C6372BUL, 0x50AFD341UL, 0xA7C13275UL, 0x915A0BF5UL,
|
||||
0x6B54BFABUL, 0x2B0B1426UL, 0xAB4CC9D7UL, 0x449CCD82UL,
|
||||
0xF7FBF265UL, 0xAB85C5F3UL, 0x1B55DB94UL, 0xAAD4E324UL,
|
||||
0xCFA4BD3FUL, 0x2DEAA3E2UL, 0x9E204D02UL, 0xC8BD25ACUL,
|
||||
0xEADF55B3UL, 0xD5BD9E98UL, 0xE31231B2UL, 0x2AD5AD6CUL,
|
||||
0x954329DEUL, 0xADBE4528UL, 0xD8710F69UL, 0xAA51C90FUL,
|
||||
0xAA786BF6UL, 0x22513F1EUL, 0xAA51A79BUL, 0x2AD344CCUL,
|
||||
0x7B5A41F0UL, 0xD37CFBADUL, 0x1B069505UL, 0x41ECE491UL,
|
||||
0xB4C332E6UL, 0x032268D4UL, 0xC9600ACCUL, 0xCE387E6DUL,
|
||||
0xBF6BB16CUL, 0x6A70FB78UL, 0x0D03D9C9UL, 0xD4DF39DEUL,
|
||||
0xE01063DAUL, 0x4736F464UL, 0x5AD328D8UL, 0xB347CC96UL,
|
||||
0x75BB0FC3UL, 0x98511BFBUL, 0x4FFBCC35UL, 0xB58BCF6AUL,
|
||||
0xE11F0ABCUL, 0xBFC5FE4AUL, 0xA70AEC10UL, 0xAC39570AUL,
|
||||
0x3F04442FUL, 0x6188B153UL, 0xE0397A2EUL, 0x5727CB79UL,
|
||||
0x9CEB418FUL, 0x1CACD68DUL, 0x2AD37C96UL, 0x0175CB9DUL,
|
||||
0xC69DFF09UL, 0xC75B65F0UL, 0xD9DB40D8UL, 0xEC0E7779UL,
|
||||
0x4744EAD4UL, 0xB11C3274UL, 0xDD24CB9EUL, 0x7E1C54BDUL,
|
||||
0xF01144F9UL, 0xD2240EB1UL, 0x9675B3FDUL, 0xA3AC3755UL,
|
||||
0xD47C27AFUL, 0x51C85F4DUL, 0x56907596UL, 0xA5BB15E6UL,
|
||||
0x580304F0UL, 0xCA042CF1UL, 0x011A37EAUL, 0x8DBFAADBUL,
|
||||
0x35BA3E4AUL, 0x3526FFA0UL, 0xC37B4D09UL, 0xBC306ED9UL,
|
||||
0x98A52666UL, 0x5648F725UL, 0xFF5E569DUL, 0x0CED63D0UL,
|
||||
0x7C63B2CFUL, 0x700B45E1UL, 0xD5EA50F1UL, 0x85A92872UL,
|
||||
0xAF1FBDA7UL, 0xD4234870UL, 0xA7870BF3UL, 0x2D3B4D79UL,
|
||||
0x42E04198UL, 0x0CD0EDE7UL, 0x26470DB8UL, 0xF881814CUL,
|
||||
0x474D6AD7UL, 0x7C0C5E5CUL, 0xD1231959UL, 0x381B7298UL,
|
||||
0xF5D2F4DBUL, 0xAB838653UL, 0x6E2F1E23UL, 0x83719C9EUL,
|
||||
0xBD91E046UL, 0x9A56456EUL, 0xDC39200CUL, 0x20C8C571UL,
|
||||
0x962BDA1CUL, 0xE1E696FFUL, 0xB141AB08UL, 0x7CCA89B9UL,
|
||||
0x1A69E783UL, 0x02CC4843UL, 0xA2F7C579UL, 0x429EF47DUL,
|
||||
0x427B169CUL, 0x5AC9F049UL, 0xDD8F0F00UL, 0x5C8165BFUL
|
||||
},
|
||||
|
||||
{
|
||||
0x1F201094UL, 0xEF0BA75BUL, 0x69E3CF7EUL, 0x393F4380UL,
|
||||
0xFE61CF7AUL, 0xEEC5207AUL, 0x55889C94UL, 0x72FC0651UL,
|
||||
0xADA7EF79UL, 0x4E1D7235UL, 0xD55A63CEUL, 0xDE0436BAUL,
|
||||
0x99C430EFUL, 0x5F0C0794UL, 0x18DCDB7DUL, 0xA1D6EFF3UL,
|
||||
0xA0B52F7BUL, 0x59E83605UL, 0xEE15B094UL, 0xE9FFD909UL,
|
||||
0xDC440086UL, 0xEF944459UL, 0xBA83CCB3UL, 0xE0C3CDFBUL,
|
||||
0xD1DA4181UL, 0x3B092AB1UL, 0xF997F1C1UL, 0xA5E6CF7BUL,
|
||||
0x01420DDBUL, 0xE4E7EF5BUL, 0x25A1FF41UL, 0xE180F806UL,
|
||||
0x1FC41080UL, 0x179BEE7AUL, 0xD37AC6A9UL, 0xFE5830A4UL,
|
||||
0x98DE8B7FUL, 0x77E83F4EUL, 0x79929269UL, 0x24FA9F7BUL,
|
||||
0xE113C85BUL, 0xACC40083UL, 0xD7503525UL, 0xF7EA615FUL,
|
||||
0x62143154UL, 0x0D554B63UL, 0x5D681121UL, 0xC866C359UL,
|
||||
0x3D63CF73UL, 0xCEE234C0UL, 0xD4D87E87UL, 0x5C672B21UL,
|
||||
0x071F6181UL, 0x39F7627FUL, 0x361E3084UL, 0xE4EB573BUL,
|
||||
0x602F64A4UL, 0xD63ACD9CUL, 0x1BBC4635UL, 0x9E81032DUL,
|
||||
0x2701F50CUL, 0x99847AB4UL, 0xA0E3DF79UL, 0xBA6CF38CUL,
|
||||
0x10843094UL, 0x2537A95EUL, 0xF46F6FFEUL, 0xA1FF3B1FUL,
|
||||
0x208CFB6AUL, 0x8F458C74UL, 0xD9E0A227UL, 0x4EC73A34UL,
|
||||
0xFC884F69UL, 0x3E4DE8DFUL, 0xEF0E0088UL, 0x3559648DUL,
|
||||
0x8A45388CUL, 0x1D804366UL, 0x721D9BFDUL, 0xA58684BBUL,
|
||||
0xE8256333UL, 0x844E8212UL, 0x128D8098UL, 0xFED33FB4UL,
|
||||
0xCE280AE1UL, 0x27E19BA5UL, 0xD5A6C252UL, 0xE49754BDUL,
|
||||
0xC5D655DDUL, 0xEB667064UL, 0x77840B4DUL, 0xA1B6A801UL,
|
||||
0x84DB26A9UL, 0xE0B56714UL, 0x21F043B7UL, 0xE5D05860UL,
|
||||
0x54F03084UL, 0x066FF472UL, 0xA31AA153UL, 0xDADC4755UL,
|
||||
0xB5625DBFUL, 0x68561BE6UL, 0x83CA6B94UL, 0x2D6ED23BUL,
|
||||
0xECCF01DBUL, 0xA6D3D0BAUL, 0xB6803D5CUL, 0xAF77A709UL,
|
||||
0x33B4A34CUL, 0x397BC8D6UL, 0x5EE22B95UL, 0x5F0E5304UL,
|
||||
0x81ED6F61UL, 0x20E74364UL, 0xB45E1378UL, 0xDE18639BUL,
|
||||
0x881CA122UL, 0xB96726D1UL, 0x8049A7E8UL, 0x22B7DA7BUL,
|
||||
0x5E552D25UL, 0x5272D237UL, 0x79D2951CUL, 0xC60D894CUL,
|
||||
0x488CB402UL, 0x1BA4FE5BUL, 0xA4B09F6BUL, 0x1CA815CFUL,
|
||||
0xA20C3005UL, 0x8871DF63UL, 0xB9DE2FCBUL, 0x0CC6C9E9UL,
|
||||
0x0BEEFF53UL, 0xE3214517UL, 0xB4542835UL, 0x9F63293CUL,
|
||||
0xEE41E729UL, 0x6E1D2D7CUL, 0x50045286UL, 0x1E6685F3UL,
|
||||
0xF33401C6UL, 0x30A22C95UL, 0x31A70850UL, 0x60930F13UL,
|
||||
0x73F98417UL, 0xA1269859UL, 0xEC645C44UL, 0x52C877A9UL,
|
||||
0xCDFF33A6UL, 0xA02B1741UL, 0x7CBAD9A2UL, 0x2180036FUL,
|
||||
0x50D99C08UL, 0xCB3F4861UL, 0xC26BD765UL, 0x64A3F6ABUL,
|
||||
0x80342676UL, 0x25A75E7BUL, 0xE4E6D1FCUL, 0x20C710E6UL,
|
||||
0xCDF0B680UL, 0x17844D3BUL, 0x31EEF84DUL, 0x7E0824E4UL,
|
||||
0x2CCB49EBUL, 0x846A3BAEUL, 0x8FF77888UL, 0xEE5D60F6UL,
|
||||
0x7AF75673UL, 0x2FDD5CDBUL, 0xA11631C1UL, 0x30F66F43UL,
|
||||
0xB3FAEC54UL, 0x157FD7FAUL, 0xEF8579CCUL, 0xD152DE58UL,
|
||||
0xDB2FFD5EUL, 0x8F32CE19UL, 0x306AF97AUL, 0x02F03EF8UL,
|
||||
0x99319AD5UL, 0xC242FA0FUL, 0xA7E3EBB0UL, 0xC68E4906UL,
|
||||
0xB8DA230CUL, 0x80823028UL, 0xDCDEF3C8UL, 0xD35FB171UL,
|
||||
0x088A1BC8UL, 0xBEC0C560UL, 0x61A3C9E8UL, 0xBCA8F54DUL,
|
||||
0xC72FEFFAUL, 0x22822E99UL, 0x82C570B4UL, 0xD8D94E89UL,
|
||||
0x8B1C34BCUL, 0x301E16E6UL, 0x273BE979UL, 0xB0FFEAA6UL,
|
||||
0x61D9B8C6UL, 0x00B24869UL, 0xB7FFCE3FUL, 0x08DC283BUL,
|
||||
0x43DAF65AUL, 0xF7E19798UL, 0x7619B72FUL, 0x8F1C9BA4UL,
|
||||
0xDC8637A0UL, 0x16A7D3B1UL, 0x9FC393B7UL, 0xA7136EEBUL,
|
||||
0xC6BCC63EUL, 0x1A513742UL, 0xEF6828BCUL, 0x520365D6UL,
|
||||
0x2D6A77ABUL, 0x3527ED4BUL, 0x821FD216UL, 0x095C6E2EUL,
|
||||
0xDB92F2FBUL, 0x5EEA29CBUL, 0x145892F5UL, 0x91584F7FUL,
|
||||
0x5483697BUL, 0x2667A8CCUL, 0x85196048UL, 0x8C4BACEAUL,
|
||||
0x833860D4UL, 0x0D23E0F9UL, 0x6C387E8AUL, 0x0AE6D249UL,
|
||||
0xB284600CUL, 0xD835731DUL, 0xDCB1C647UL, 0xAC4C56EAUL,
|
||||
0x3EBD81B3UL, 0x230EABB0UL, 0x6438BC87UL, 0xF0B5B1FAUL,
|
||||
0x8F5EA2B3UL, 0xFC184642UL, 0x0A036B7AUL, 0x4FB089BDUL,
|
||||
0x649DA589UL, 0xA345415EUL, 0x5C038323UL, 0x3E5D3BB9UL,
|
||||
0x43D79572UL, 0x7E6DD07CUL, 0x06DFDF1EUL, 0x6C6CC4EFUL,
|
||||
0x7160A539UL, 0x73BFBE70UL, 0x83877605UL, 0x4523ECF1UL
|
||||
},
|
||||
|
||||
{
|
||||
0x8DEFC240UL, 0x25FA5D9FUL, 0xEB903DBFUL, 0xE810C907UL,
|
||||
0x47607FFFUL, 0x369FE44BUL, 0x8C1FC644UL, 0xAECECA90UL,
|
||||
0xBEB1F9BFUL, 0xEEFBCAEAUL, 0xE8CF1950UL, 0x51DF07AEUL,
|
||||
0x920E8806UL, 0xF0AD0548UL, 0xE13C8D83UL, 0x927010D5UL,
|
||||
0x11107D9FUL, 0x07647DB9UL, 0xB2E3E4D4UL, 0x3D4F285EUL,
|
||||
0xB9AFA820UL, 0xFADE82E0UL, 0xA067268BUL, 0x8272792EUL,
|
||||
0x553FB2C0UL, 0x489AE22BUL, 0xD4EF9794UL, 0x125E3FBCUL,
|
||||
0x21FFFCEEUL, 0x825B1BFDUL, 0x9255C5EDUL, 0x1257A240UL,
|
||||
0x4E1A8302UL, 0xBAE07FFFUL, 0x528246E7UL, 0x8E57140EUL,
|
||||
0x3373F7BFUL, 0x8C9F8188UL, 0xA6FC4EE8UL, 0xC982B5A5UL,
|
||||
0xA8C01DB7UL, 0x579FC264UL, 0x67094F31UL, 0xF2BD3F5FUL,
|
||||
0x40FFF7C1UL, 0x1FB78DFCUL, 0x8E6BD2C1UL, 0x437BE59BUL,
|
||||
0x99B03DBFUL, 0xB5DBC64BUL, 0x638DC0E6UL, 0x55819D99UL,
|
||||
0xA197C81CUL, 0x4A012D6EUL, 0xC5884A28UL, 0xCCC36F71UL,
|
||||
0xB843C213UL, 0x6C0743F1UL, 0x8309893CUL, 0x0FEDDD5FUL,
|
||||
0x2F7FE850UL, 0xD7C07F7EUL, 0x02507FBFUL, 0x5AFB9A04UL,
|
||||
0xA747D2D0UL, 0x1651192EUL, 0xAF70BF3EUL, 0x58C31380UL,
|
||||
0x5F98302EUL, 0x727CC3C4UL, 0x0A0FB402UL, 0x0F7FEF82UL,
|
||||
0x8C96FDADUL, 0x5D2C2AAEUL, 0x8EE99A49UL, 0x50DA88B8UL,
|
||||
0x8427F4A0UL, 0x1EAC5790UL, 0x796FB449UL, 0x8252DC15UL,
|
||||
0xEFBD7D9BUL, 0xA672597DUL, 0xADA840D8UL, 0x45F54504UL,
|
||||
0xFA5D7403UL, 0xE83EC305UL, 0x4F91751AUL, 0x925669C2UL,
|
||||
0x23EFE941UL, 0xA903F12EUL, 0x60270DF2UL, 0x0276E4B6UL,
|
||||
0x94FD6574UL, 0x927985B2UL, 0x8276DBCBUL, 0x02778176UL,
|
||||
0xF8AF918DUL, 0x4E48F79EUL, 0x8F616DDFUL, 0xE29D840EUL,
|
||||
0x842F7D83UL, 0x340CE5C8UL, 0x96BBB682UL, 0x93B4B148UL,
|
||||
0xEF303CABUL, 0x984FAF28UL, 0x779FAF9BUL, 0x92DC560DUL,
|
||||
0x224D1E20UL, 0x8437AA88UL, 0x7D29DC96UL, 0x2756D3DCUL,
|
||||
0x8B907CEEUL, 0xB51FD240UL, 0xE7C07CE3UL, 0xE566B4A1UL,
|
||||
0xC3E9615EUL, 0x3CF8209DUL, 0x6094D1E3UL, 0xCD9CA341UL,
|
||||
0x5C76460EUL, 0x00EA983BUL, 0xD4D67881UL, 0xFD47572CUL,
|
||||
0xF76CEDD9UL, 0xBDA8229CUL, 0x127DADAAUL, 0x438A074EUL,
|
||||
0x1F97C090UL, 0x081BDB8AUL, 0x93A07EBEUL, 0xB938CA15UL,
|
||||
0x97B03CFFUL, 0x3DC2C0F8UL, 0x8D1AB2ECUL, 0x64380E51UL,
|
||||
0x68CC7BFBUL, 0xD90F2788UL, 0x12490181UL, 0x5DE5FFD4UL,
|
||||
0xDD7EF86AUL, 0x76A2E214UL, 0xB9A40368UL, 0x925D958FUL,
|
||||
0x4B39FFFAUL, 0xBA39AEE9UL, 0xA4FFD30BUL, 0xFAF7933BUL,
|
||||
0x6D498623UL, 0x193CBCFAUL, 0x27627545UL, 0x825CF47AUL,
|
||||
0x61BD8BA0UL, 0xD11E42D1UL, 0xCEAD04F4UL, 0x127EA392UL,
|
||||
0x10428DB7UL, 0x8272A972UL, 0x9270C4A8UL, 0x127DE50BUL,
|
||||
0x285BA1C8UL, 0x3C62F44FUL, 0x35C0EAA5UL, 0xE805D231UL,
|
||||
0x428929FBUL, 0xB4FCDF82UL, 0x4FB66A53UL, 0x0E7DC15BUL,
|
||||
0x1F081FABUL, 0x108618AEUL, 0xFCFD086DUL, 0xF9FF2889UL,
|
||||
0x694BCC11UL, 0x236A5CAEUL, 0x12DECA4DUL, 0x2C3F8CC5UL,
|
||||
0xD2D02DFEUL, 0xF8EF5896UL, 0xE4CF52DAUL, 0x95155B67UL,
|
||||
0x494A488CUL, 0xB9B6A80CUL, 0x5C8F82BCUL, 0x89D36B45UL,
|
||||
0x3A609437UL, 0xEC00C9A9UL, 0x44715253UL, 0x0A874B49UL,
|
||||
0xD773BC40UL, 0x7C34671CUL, 0x02717EF6UL, 0x4FEB5536UL,
|
||||
0xA2D02FFFUL, 0xD2BF60C4UL, 0xD43F03C0UL, 0x50B4EF6DUL,
|
||||
0x07478CD1UL, 0x006E1888UL, 0xA2E53F55UL, 0xB9E6D4BCUL,
|
||||
0xA2048016UL, 0x97573833UL, 0xD7207D67UL, 0xDE0F8F3DUL,
|
||||
0x72F87B33UL, 0xABCC4F33UL, 0x7688C55DUL, 0x7B00A6B0UL,
|
||||
0x947B0001UL, 0x570075D2UL, 0xF9BB88F8UL, 0x8942019EUL,
|
||||
0x4264A5FFUL, 0x856302E0UL, 0x72DBD92BUL, 0xEE971B69UL,
|
||||
0x6EA22FDEUL, 0x5F08AE2BUL, 0xAF7A616DUL, 0xE5C98767UL,
|
||||
0xCF1FEBD2UL, 0x61EFC8C2UL, 0xF1AC2571UL, 0xCC8239C2UL,
|
||||
0x67214CB8UL, 0xB1E583D1UL, 0xB7DC3E62UL, 0x7F10BDCEUL,
|
||||
0xF90A5C38UL, 0x0FF0443DUL, 0x606E6DC6UL, 0x60543A49UL,
|
||||
0x5727C148UL, 0x2BE98A1DUL, 0x8AB41738UL, 0x20E1BE24UL,
|
||||
0xAF96DA0FUL, 0x68458425UL, 0x99833BE5UL, 0x600D457DUL,
|
||||
0x282F9350UL, 0x8334B362UL, 0xD91D1120UL, 0x2B6D8DA0UL,
|
||||
0x642B1E31UL, 0x9C305A00UL, 0x52BCE688UL, 0x1B03588AUL,
|
||||
0xF7BAEFD5UL, 0x4142ED9CUL, 0xA4315C11UL, 0x83323EC5UL,
|
||||
0xDFEF4636UL, 0xA133C501UL, 0xE9D3531CUL, 0xEE353783UL
|
||||
},
|
||||
|
||||
{
|
||||
0x9DB30420UL, 0x1FB6E9DEUL, 0xA7BE7BEFUL, 0xD273A298UL,
|
||||
0x4A4F7BDBUL, 0x64AD8C57UL, 0x85510443UL, 0xFA020ED1UL,
|
||||
0x7E287AFFUL, 0xE60FB663UL, 0x095F35A1UL, 0x79EBF120UL,
|
||||
0xFD059D43UL, 0x6497B7B1UL, 0xF3641F63UL, 0x241E4ADFUL,
|
||||
0x28147F5FUL, 0x4FA2B8CDUL, 0xC9430040UL, 0x0CC32220UL,
|
||||
0xFDD30B30UL, 0xC0A5374FUL, 0x1D2D00D9UL, 0x24147B15UL,
|
||||
0xEE4D111AUL, 0x0FCA5167UL, 0x71FF904CUL, 0x2D195FFEUL,
|
||||
0x1A05645FUL, 0x0C13FEFEUL, 0x081B08CAUL, 0x05170121UL,
|
||||
0x80530100UL, 0xE83E5EFEUL, 0xAC9AF4F8UL, 0x7FE72701UL,
|
||||
0xD2B8EE5FUL, 0x06DF4261UL, 0xBB9E9B8AUL, 0x7293EA25UL,
|
||||
0xCE84FFDFUL, 0xF5718801UL, 0x3DD64B04UL, 0xA26F263BUL,
|
||||
0x7ED48400UL, 0x547EEBE6UL, 0x446D4CA0UL, 0x6CF3D6F5UL,
|
||||
0x2649ABDFUL, 0xAEA0C7F5UL, 0x36338CC1UL, 0x503F7E93UL,
|
||||
0xD3772061UL, 0x11B638E1UL, 0x72500E03UL, 0xF80EB2BBUL,
|
||||
0xABE0502EUL, 0xEC8D77DEUL, 0x57971E81UL, 0xE14F6746UL,
|
||||
0xC9335400UL, 0x6920318FUL, 0x081DBB99UL, 0xFFC304A5UL,
|
||||
0x4D351805UL, 0x7F3D5CE3UL, 0xA6C866C6UL, 0x5D5BCCA9UL,
|
||||
0xDAEC6FEAUL, 0x9F926F91UL, 0x9F46222FUL, 0x3991467DUL,
|
||||
0xA5BF6D8EUL, 0x1143C44FUL, 0x43958302UL, 0xD0214EEBUL,
|
||||
0x022083B8UL, 0x3FB6180CUL, 0x18F8931EUL, 0x281658E6UL,
|
||||
0x26486E3EUL, 0x8BD78A70UL, 0x7477E4C1UL, 0xB506E07CUL,
|
||||
0xF32D0A25UL, 0x79098B02UL, 0xE4EABB81UL, 0x28123B23UL,
|
||||
0x69DEAD38UL, 0x1574CA16UL, 0xDF871B62UL, 0x211C40B7UL,
|
||||
0xA51A9EF9UL, 0x0014377BUL, 0x041E8AC8UL, 0x09114003UL,
|
||||
0xBD59E4D2UL, 0xE3D156D5UL, 0x4FE876D5UL, 0x2F91A340UL,
|
||||
0x557BE8DEUL, 0x00EAE4A7UL, 0x0CE5C2ECUL, 0x4DB4BBA6UL,
|
||||
0xE756BDFFUL, 0xDD3369ACUL, 0xEC17B035UL, 0x06572327UL,
|
||||
0x99AFC8B0UL, 0x56C8C391UL, 0x6B65811CUL, 0x5E146119UL,
|
||||
0x6E85CB75UL, 0xBE07C002UL, 0xC2325577UL, 0x893FF4ECUL,
|
||||
0x5BBFC92DUL, 0xD0EC3B25UL, 0xB7801AB7UL, 0x8D6D3B24UL,
|
||||
0x20C763EFUL, 0xC366A5FCUL, 0x9C382880UL, 0x0ACE3205UL,
|
||||
0xAAC9548AUL, 0xECA1D7C7UL, 0x041AFA32UL, 0x1D16625AUL,
|
||||
0x6701902CUL, 0x9B757A54UL, 0x31D477F7UL, 0x9126B031UL,
|
||||
0x36CC6FDBUL, 0xC70B8B46UL, 0xD9E66A48UL, 0x56E55A79UL,
|
||||
0x026A4CEBUL, 0x52437EFFUL, 0x2F8F76B4UL, 0x0DF980A5UL,
|
||||
0x8674CDE3UL, 0xEDDA04EBUL, 0x17A9BE04UL, 0x2C18F4DFUL,
|
||||
0xB7747F9DUL, 0xAB2AF7B4UL, 0xEFC34D20UL, 0x2E096B7CUL,
|
||||
0x1741A254UL, 0xE5B6A035UL, 0x213D42F6UL, 0x2C1C7C26UL,
|
||||
0x61C2F50FUL, 0x6552DAF9UL, 0xD2C231F8UL, 0x25130F69UL,
|
||||
0xD8167FA2UL, 0x0418F2C8UL, 0x001A96A6UL, 0x0D1526ABUL,
|
||||
0x63315C21UL, 0x5E0A72ECUL, 0x49BAFEFDUL, 0x187908D9UL,
|
||||
0x8D0DBD86UL, 0x311170A7UL, 0x3E9B640CUL, 0xCC3E10D7UL,
|
||||
0xD5CAD3B6UL, 0x0CAEC388UL, 0xF73001E1UL, 0x6C728AFFUL,
|
||||
0x71EAE2A1UL, 0x1F9AF36EUL, 0xCFCBD12FUL, 0xC1DE8417UL,
|
||||
0xAC07BE6BUL, 0xCB44A1D8UL, 0x8B9B0F56UL, 0x013988C3UL,
|
||||
0xB1C52FCAUL, 0xB4BE31CDUL, 0xD8782806UL, 0x12A3A4E2UL,
|
||||
0x6F7DE532UL, 0x58FD7EB6UL, 0xD01EE900UL, 0x24ADFFC2UL,
|
||||
0xF4990FC5UL, 0x9711AAC5UL, 0x001D7B95UL, 0x82E5E7D2UL,
|
||||
0x109873F6UL, 0x00613096UL, 0xC32D9521UL, 0xADA121FFUL,
|
||||
0x29908415UL, 0x7FBB977FUL, 0xAF9EB3DBUL, 0x29C9ED2AUL,
|
||||
0x5CE2A465UL, 0xA730F32CUL, 0xD0AA3FE8UL, 0x8A5CC091UL,
|
||||
0xD49E2CE7UL, 0x0CE454A9UL, 0xD60ACD86UL, 0x015F1919UL,
|
||||
0x77079103UL, 0xDEA03AF6UL, 0x78A8565EUL, 0xDEE356DFUL,
|
||||
0x21F05CBEUL, 0x8B75E387UL, 0xB3C50651UL, 0xB8A5C3EFUL,
|
||||
0xD8EEB6D2UL, 0xE523BE77UL, 0xC2154529UL, 0x2F69EFDFUL,
|
||||
0xAFE67AFBUL, 0xF470C4B2UL, 0xF3E0EB5BUL, 0xD6CC9876UL,
|
||||
0x39E4460CUL, 0x1FDA8538UL, 0x1987832FUL, 0xCA007367UL,
|
||||
0xA99144F8UL, 0x296B299EUL, 0x492FC295UL, 0x9266BEABUL,
|
||||
0xB5676E69UL, 0x9BD3DDDAUL, 0xDF7E052FUL, 0xDB25701CUL,
|
||||
0x1B5E51EEUL, 0xF65324E6UL, 0x6AFCE36CUL, 0x0316CC04UL,
|
||||
0x8644213EUL, 0xB7DC59D0UL, 0x7965291FUL, 0xCCD6FD43UL,
|
||||
0x41823979UL, 0x932BCDF6UL, 0xB657C34DUL, 0x4EDFD282UL,
|
||||
0x7AE5290CUL, 0x3CB9536BUL, 0x851E20FEUL, 0x9833557EUL,
|
||||
0x13ECF0B0UL, 0xD3FFB372UL, 0x3F85C5C1UL, 0x0AEF7ED2UL
|
||||
},
|
||||
|
||||
{
|
||||
0x7EC90C04UL, 0x2C6E74B9UL, 0x9B0E66DFUL, 0xA6337911UL,
|
||||
0xB86A7FFFUL, 0x1DD358F5UL, 0x44DD9D44UL, 0x1731167FUL,
|
||||
0x08FBF1FAUL, 0xE7F511CCUL, 0xD2051B00UL, 0x735ABA00UL,
|
||||
0x2AB722D8UL, 0x386381CBUL, 0xACF6243AUL, 0x69BEFD7AUL,
|
||||
0xE6A2E77FUL, 0xF0C720CDUL, 0xC4494816UL, 0xCCF5C180UL,
|
||||
0x38851640UL, 0x15B0A848UL, 0xE68B18CBUL, 0x4CAADEFFUL,
|
||||
0x5F480A01UL, 0x0412B2AAUL, 0x259814FCUL, 0x41D0EFE2UL,
|
||||
0x4E40B48DUL, 0x248EB6FBUL, 0x8DBA1CFEUL, 0x41A99B02UL,
|
||||
0x1A550A04UL, 0xBA8F65CBUL, 0x7251F4E7UL, 0x95A51725UL,
|
||||
0xC106ECD7UL, 0x97A5980AUL, 0xC539B9AAUL, 0x4D79FE6AUL,
|
||||
0xF2F3F763UL, 0x68AF8040UL, 0xED0C9E56UL, 0x11B4958BUL,
|
||||
0xE1EB5A88UL, 0x8709E6B0UL, 0xD7E07156UL, 0x4E29FEA7UL,
|
||||
0x6366E52DUL, 0x02D1C000UL, 0xC4AC8E05UL, 0x9377F571UL,
|
||||
0x0C05372AUL, 0x578535F2UL, 0x2261BE02UL, 0xD642A0C9UL,
|
||||
0xDF13A280UL, 0x74B55BD2UL, 0x682199C0UL, 0xD421E5ECUL,
|
||||
0x53FB3CE8UL, 0xC8ADEDB3UL, 0x28A87FC9UL, 0x3D959981UL,
|
||||
0x5C1FF900UL, 0xFE38D399UL, 0x0C4EFF0BUL, 0x062407EAUL,
|
||||
0xAA2F4FB1UL, 0x4FB96976UL, 0x90C79505UL, 0xB0A8A774UL,
|
||||
0xEF55A1FFUL, 0xE59CA2C2UL, 0xA6B62D27UL, 0xE66A4263UL,
|
||||
0xDF65001FUL, 0x0EC50966UL, 0xDFDD55BCUL, 0x29DE0655UL,
|
||||
0x911E739AUL, 0x17AF8975UL, 0x32C7911CUL, 0x89F89468UL,
|
||||
0x0D01E980UL, 0x524755F4UL, 0x03B63CC9UL, 0x0CC844B2UL,
|
||||
0xBCF3F0AAUL, 0x87AC36E9UL, 0xE53A7426UL, 0x01B3D82BUL,
|
||||
0x1A9E7449UL, 0x64EE2D7EUL, 0xCDDBB1DAUL, 0x01C94910UL,
|
||||
0xB868BF80UL, 0x0D26F3FDUL, 0x9342EDE7UL, 0x04A5C284UL,
|
||||
0x636737B6UL, 0x50F5B616UL, 0xF24766E3UL, 0x8ECA36C1UL,
|
||||
0x136E05DBUL, 0xFEF18391UL, 0xFB887A37UL, 0xD6E7F7D4UL,
|
||||
0xC7FB7DC9UL, 0x3063FCDFUL, 0xB6F589DEUL, 0xEC2941DAUL,
|
||||
0x26E46695UL, 0xB7566419UL, 0xF654EFC5UL, 0xD08D58B7UL,
|
||||
0x48925401UL, 0xC1BACB7FUL, 0xE5FF550FUL, 0xB6083049UL,
|
||||
0x5BB5D0E8UL, 0x87D72E5AUL, 0xAB6A6EE1UL, 0x223A66CEUL,
|
||||
0xC62BF3CDUL, 0x9E0885F9UL, 0x68CB3E47UL, 0x086C010FUL,
|
||||
0xA21DE820UL, 0xD18B69DEUL, 0xF3F65777UL, 0xFA02C3F6UL,
|
||||
0x407EDAC3UL, 0xCBB3D550UL, 0x1793084DUL, 0xB0D70EBAUL,
|
||||
0x0AB378D5UL, 0xD951FB0CUL, 0xDED7DA56UL, 0x4124BBE4UL,
|
||||
0x94CA0B56UL, 0x0F5755D1UL, 0xE0E1E56EUL, 0x6184B5BEUL,
|
||||
0x580A249FUL, 0x94F74BC0UL, 0xE327888EUL, 0x9F7B5561UL,
|
||||
0xC3DC0280UL, 0x05687715UL, 0x646C6BD7UL, 0x44904DB3UL,
|
||||
0x66B4F0A3UL, 0xC0F1648AUL, 0x697ED5AFUL, 0x49E92FF6UL,
|
||||
0x309E374FUL, 0x2CB6356AUL, 0x85808573UL, 0x4991F840UL,
|
||||
0x76F0AE02UL, 0x083BE84DUL, 0x28421C9AUL, 0x44489406UL,
|
||||
0x736E4CB8UL, 0xC1092910UL, 0x8BC95FC6UL, 0x7D869CF4UL,
|
||||
0x134F616FUL, 0x2E77118DUL, 0xB31B2BE1UL, 0xAA90B472UL,
|
||||
0x3CA5D717UL, 0x7D161BBAUL, 0x9CAD9010UL, 0xAF462BA2UL,
|
||||
0x9FE459D2UL, 0x45D34559UL, 0xD9F2DA13UL, 0xDBC65487UL,
|
||||
0xF3E4F94EUL, 0x176D486FUL, 0x097C13EAUL, 0x631DA5C7UL,
|
||||
0x445F7382UL, 0x175683F4UL, 0xCDC66A97UL, 0x70BE0288UL,
|
||||
0xB3CDCF72UL, 0x6E5DD2F3UL, 0x20936079UL, 0x459B80A5UL,
|
||||
0xBE60E2DBUL, 0xA9C23101UL, 0xEBA5315CUL, 0x224E42F2UL,
|
||||
0x1C5C1572UL, 0xF6721B2CUL, 0x1AD2FFF3UL, 0x8C25404EUL,
|
||||
0x324ED72FUL, 0x4067B7FDUL, 0x0523138EUL, 0x5CA3BC78UL,
|
||||
0xDC0FD66EUL, 0x75922283UL, 0x784D6B17UL, 0x58EBB16EUL,
|
||||
0x44094F85UL, 0x3F481D87UL, 0xFCFEAE7BUL, 0x77B5FF76UL,
|
||||
0x8C2302BFUL, 0xAAF47556UL, 0x5F46B02AUL, 0x2B092801UL,
|
||||
0x3D38F5F7UL, 0x0CA81F36UL, 0x52AF4A8AUL, 0x66D5E7C0UL,
|
||||
0xDF3B0874UL, 0x95055110UL, 0x1B5AD7A8UL, 0xF61ED5ADUL,
|
||||
0x6CF6E479UL, 0x20758184UL, 0xD0CEFA65UL, 0x88F7BE58UL,
|
||||
0x4A046826UL, 0x0FF6F8F3UL, 0xA09C7F70UL, 0x5346ABA0UL,
|
||||
0x5CE96C28UL, 0xE176EDA3UL, 0x6BAC307FUL, 0x376829D2UL,
|
||||
0x85360FA9UL, 0x17E3FE2AUL, 0x24B79767UL, 0xF5A96B20UL,
|
||||
0xD6CD2595UL, 0x68FF1EBFUL, 0x7555442CUL, 0xF19F06BEUL,
|
||||
0xF9E0659AUL, 0xEEB9491DUL, 0x34010718UL, 0xBB30CAB8UL,
|
||||
0xE822FE15UL, 0x88570983UL, 0x750E6249UL, 0xDA627E55UL,
|
||||
0x5E76FFA8UL, 0xB1534546UL, 0x6D47DE08UL, 0xEFE9E7D4UL
|
||||
},
|
||||
|
||||
{
|
||||
0xF6FA8F9DUL, 0x2CAC6CE1UL, 0x4CA34867UL, 0xE2337F7CUL,
|
||||
0x95DB08E7UL, 0x016843B4UL, 0xECED5CBCUL, 0x325553ACUL,
|
||||
0xBF9F0960UL, 0xDFA1E2EDUL, 0x83F0579DUL, 0x63ED86B9UL,
|
||||
0x1AB6A6B8UL, 0xDE5EBE39UL, 0xF38FF732UL, 0x8989B138UL,
|
||||
0x33F14961UL, 0xC01937BDUL, 0xF506C6DAUL, 0xE4625E7EUL,
|
||||
0xA308EA99UL, 0x4E23E33CUL, 0x79CBD7CCUL, 0x48A14367UL,
|
||||
0xA3149619UL, 0xFEC94BD5UL, 0xA114174AUL, 0xEAA01866UL,
|
||||
0xA084DB2DUL, 0x09A8486FUL, 0xA888614AUL, 0x2900AF98UL,
|
||||
0x01665991UL, 0xE1992863UL, 0xC8F30C60UL, 0x2E78EF3CUL,
|
||||
0xD0D51932UL, 0xCF0FEC14UL, 0xF7CA07D2UL, 0xD0A82072UL,
|
||||
0xFD41197EUL, 0x9305A6B0UL, 0xE86BE3DAUL, 0x74BED3CDUL,
|
||||
0x372DA53CUL, 0x4C7F4448UL, 0xDAB5D440UL, 0x6DBA0EC3UL,
|
||||
0x083919A7UL, 0x9FBAEED9UL, 0x49DBCFB0UL, 0x4E670C53UL,
|
||||
0x5C3D9C01UL, 0x64BDB941UL, 0x2C0E636AUL, 0xBA7DD9CDUL,
|
||||
0xEA6F7388UL, 0xE70BC762UL, 0x35F29ADBUL, 0x5C4CDD8DUL,
|
||||
0xF0D48D8CUL, 0xB88153E2UL, 0x08A19866UL, 0x1AE2EAC8UL,
|
||||
0x284CAF89UL, 0xAA928223UL, 0x9334BE53UL, 0x3B3A21BFUL,
|
||||
0x16434BE3UL, 0x9AEA3906UL, 0xEFE8C36EUL, 0xF890CDD9UL,
|
||||
0x80226DAEUL, 0xC340A4A3UL, 0xDF7E9C09UL, 0xA694A807UL,
|
||||
0x5B7C5ECCUL, 0x221DB3A6UL, 0x9A69A02FUL, 0x68818A54UL,
|
||||
0xCEB2296FUL, 0x53C0843AUL, 0xFE893655UL, 0x25BFE68AUL,
|
||||
0xB4628ABCUL, 0xCF222EBFUL, 0x25AC6F48UL, 0xA9A99387UL,
|
||||
0x53BDDB65UL, 0xE76FFBE7UL, 0xE967FD78UL, 0x0BA93563UL,
|
||||
0x8E342BC1UL, 0xE8A11BE9UL, 0x4980740DUL, 0xC8087DFCUL,
|
||||
0x8DE4BF99UL, 0xA11101A0UL, 0x7FD37975UL, 0xDA5A26C0UL,
|
||||
0xE81F994FUL, 0x9528CD89UL, 0xFD339FEDUL, 0xB87834BFUL,
|
||||
0x5F04456DUL, 0x22258698UL, 0xC9C4C83BUL, 0x2DC156BEUL,
|
||||
0x4F628DAAUL, 0x57F55EC5UL, 0xE2220ABEUL, 0xD2916EBFUL,
|
||||
0x4EC75B95UL, 0x24F2C3C0UL, 0x42D15D99UL, 0xCD0D7FA0UL,
|
||||
0x7B6E27FFUL, 0xA8DC8AF0UL, 0x7345C106UL, 0xF41E232FUL,
|
||||
0x35162386UL, 0xE6EA8926UL, 0x3333B094UL, 0x157EC6F2UL,
|
||||
0x372B74AFUL, 0x692573E4UL, 0xE9A9D848UL, 0xF3160289UL,
|
||||
0x3A62EF1DUL, 0xA787E238UL, 0xF3A5F676UL, 0x74364853UL,
|
||||
0x20951063UL, 0x4576698DUL, 0xB6FAD407UL, 0x592AF950UL,
|
||||
0x36F73523UL, 0x4CFB6E87UL, 0x7DA4CEC0UL, 0x6C152DAAUL,
|
||||
0xCB0396A8UL, 0xC50DFE5DUL, 0xFCD707ABUL, 0x0921C42FUL,
|
||||
0x89DFF0BBUL, 0x5FE2BE78UL, 0x448F4F33UL, 0x754613C9UL,
|
||||
0x2B05D08DUL, 0x48B9D585UL, 0xDC049441UL, 0xC8098F9BUL,
|
||||
0x7DEDE786UL, 0xC39A3373UL, 0x42410005UL, 0x6A091751UL,
|
||||
0x0EF3C8A6UL, 0x890072D6UL, 0x28207682UL, 0xA9A9F7BEUL,
|
||||
0xBF32679DUL, 0xD45B5B75UL, 0xB353FD00UL, 0xCBB0E358UL,
|
||||
0x830F220AUL, 0x1F8FB214UL, 0xD372CF08UL, 0xCC3C4A13UL,
|
||||
0x8CF63166UL, 0x061C87BEUL, 0x88C98F88UL, 0x6062E397UL,
|
||||
0x47CF8E7AUL, 0xB6C85283UL, 0x3CC2ACFBUL, 0x3FC06976UL,
|
||||
0x4E8F0252UL, 0x64D8314DUL, 0xDA3870E3UL, 0x1E665459UL,
|
||||
0xC10908F0UL, 0x513021A5UL, 0x6C5B68B7UL, 0x822F8AA0UL,
|
||||
0x3007CD3EUL, 0x74719EEFUL, 0xDC872681UL, 0x073340D4UL,
|
||||
0x7E432FD9UL, 0x0C5EC241UL, 0x8809286CUL, 0xF592D891UL,
|
||||
0x08A930F6UL, 0x957EF305UL, 0xB7FBFFBDUL, 0xC266E96FUL,
|
||||
0x6FE4AC98UL, 0xB173ECC0UL, 0xBC60B42AUL, 0x953498DAUL,
|
||||
0xFBA1AE12UL, 0x2D4BD736UL, 0x0F25FAABUL, 0xA4F3FCEBUL,
|
||||
0xE2969123UL, 0x257F0C3DUL, 0x9348AF49UL, 0x361400BCUL,
|
||||
0xE8816F4AUL, 0x3814F200UL, 0xA3F94043UL, 0x9C7A54C2UL,
|
||||
0xBC704F57UL, 0xDA41E7F9UL, 0xC25AD33AUL, 0x54F4A084UL,
|
||||
0xB17F5505UL, 0x59357CBEUL, 0xEDBD15C8UL, 0x7F97C5ABUL,
|
||||
0xBA5AC7B5UL, 0xB6F6DEAFUL, 0x3A479C3AUL, 0x5302DA25UL,
|
||||
0x653D7E6AUL, 0x54268D49UL, 0x51A477EAUL, 0x5017D55BUL,
|
||||
0xD7D25D88UL, 0x44136C76UL, 0x0404A8C8UL, 0xB8E5A121UL,
|
||||
0xB81A928AUL, 0x60ED5869UL, 0x97C55B96UL, 0xEAEC991BUL,
|
||||
0x29935913UL, 0x01FDB7F1UL, 0x088E8DFAUL, 0x9AB6F6F5UL,
|
||||
0x3B4CBF9FUL, 0x4A5DE3ABUL, 0xE6051D35UL, 0xA0E1D855UL,
|
||||
0xD36B4CF1UL, 0xF544EDEBUL, 0xB0E93524UL, 0xBEBB8FBDUL,
|
||||
0xA2D762CFUL, 0x49C92F54UL, 0x38B5F331UL, 0x7128A454UL,
|
||||
0x48392905UL, 0xA65B1DB8UL, 0x851C97BDUL, 0xD675CF2FUL
|
||||
},
|
||||
|
||||
{
|
||||
0x85E04019UL, 0x332BF567UL, 0x662DBFFFUL, 0xCFC65693UL,
|
||||
0x2A8D7F6FUL, 0xAB9BC912UL, 0xDE6008A1UL, 0x2028DA1FUL,
|
||||
0x0227BCE7UL, 0x4D642916UL, 0x18FAC300UL, 0x50F18B82UL,
|
||||
0x2CB2CB11UL, 0xB232E75CUL, 0x4B3695F2UL, 0xB28707DEUL,
|
||||
0xA05FBCF6UL, 0xCD4181E9UL, 0xE150210CUL, 0xE24EF1BDUL,
|
||||
0xB168C381UL, 0xFDE4E789UL, 0x5C79B0D8UL, 0x1E8BFD43UL,
|
||||
0x4D495001UL, 0x38BE4341UL, 0x913CEE1DUL, 0x92A79C3FUL,
|
||||
0x089766BEUL, 0xBAEEADF4UL, 0x1286BECFUL, 0xB6EACB19UL,
|
||||
0x2660C200UL, 0x7565BDE4UL, 0x64241F7AUL, 0x8248DCA9UL,
|
||||
0xC3B3AD66UL, 0x28136086UL, 0x0BD8DFA8UL, 0x356D1CF2UL,
|
||||
0x107789BEUL, 0xB3B2E9CEUL, 0x0502AA8FUL, 0x0BC0351EUL,
|
||||
0x166BF52AUL, 0xEB12FF82UL, 0xE3486911UL, 0xD34D7516UL,
|
||||
0x4E7B3AFFUL, 0x5F43671BUL, 0x9CF6E037UL, 0x4981AC83UL,
|
||||
0x334266CEUL, 0x8C9341B7UL, 0xD0D854C0UL, 0xCB3A6C88UL,
|
||||
0x47BC2829UL, 0x4725BA37UL, 0xA66AD22BUL, 0x7AD61F1EUL,
|
||||
0x0C5CBAFAUL, 0x4437F107UL, 0xB6E79962UL, 0x42D2D816UL,
|
||||
0x0A961288UL, 0xE1A5C06EUL, 0x13749E67UL, 0x72FC081AUL,
|
||||
0xB1D139F7UL, 0xF9583745UL, 0xCF19DF58UL, 0xBEC3F756UL,
|
||||
0xC06EBA30UL, 0x07211B24UL, 0x45C28829UL, 0xC95E317FUL,
|
||||
0xBC8EC511UL, 0x38BC46E9UL, 0xC6E6FA14UL, 0xBAE8584AUL,
|
||||
0xAD4EBC46UL, 0x468F508BUL, 0x7829435FUL, 0xF124183BUL,
|
||||
0x821DBA9FUL, 0xAFF60FF4UL, 0xEA2C4E6DUL, 0x16E39264UL,
|
||||
0x92544A8BUL, 0x009B4FC3UL, 0xABA68CEDUL, 0x9AC96F78UL,
|
||||
0x06A5B79AUL, 0xB2856E6EUL, 0x1AEC3CA9UL, 0xBE838688UL,
|
||||
0x0E0804E9UL, 0x55F1BE56UL, 0xE7E5363BUL, 0xB3A1F25DUL,
|
||||
0xF7DEBB85UL, 0x61FE033CUL, 0x16746233UL, 0x3C034C28UL,
|
||||
0xDA6D0C74UL, 0x79AAC56CUL, 0x3CE4E1ADUL, 0x51F0C802UL,
|
||||
0x98F8F35AUL, 0x1626A49FUL, 0xEED82B29UL, 0x1D382FE3UL,
|
||||
0x0C4FB99AUL, 0xBB325778UL, 0x3EC6D97BUL, 0x6E77A6A9UL,
|
||||
0xCB658B5CUL, 0xD45230C7UL, 0x2BD1408BUL, 0x60C03EB7UL,
|
||||
0xB9068D78UL, 0xA33754F4UL, 0xF430C87DUL, 0xC8A71302UL,
|
||||
0xB96D8C32UL, 0xEBD4E7BEUL, 0xBE8B9D2DUL, 0x7979FB06UL,
|
||||
0xE7225308UL, 0x8B75CF77UL, 0x11EF8DA4UL, 0xE083C858UL,
|
||||
0x8D6B786FUL, 0x5A6317A6UL, 0xFA5CF7A0UL, 0x5DDA0033UL,
|
||||
0xF28EBFB0UL, 0xF5B9C310UL, 0xA0EAC280UL, 0x08B9767AUL,
|
||||
0xA3D9D2B0UL, 0x79D34217UL, 0x021A718DUL, 0x9AC6336AUL,
|
||||
0x2711FD60UL, 0x438050E3UL, 0x069908A8UL, 0x3D7FEDC4UL,
|
||||
0x826D2BEFUL, 0x4EEB8476UL, 0x488DCF25UL, 0x36C9D566UL,
|
||||
0x28E74E41UL, 0xC2610ACAUL, 0x3D49A9CFUL, 0xBAE3B9DFUL,
|
||||
0xB65F8DE6UL, 0x92AEAF64UL, 0x3AC7D5E6UL, 0x9EA80509UL,
|
||||
0xF22B017DUL, 0xA4173F70UL, 0xDD1E16C3UL, 0x15E0D7F9UL,
|
||||
0x50B1B887UL, 0x2B9F4FD5UL, 0x625ABA82UL, 0x6A017962UL,
|
||||
0x2EC01B9CUL, 0x15488AA9UL, 0xD716E740UL, 0x40055A2CUL,
|
||||
0x93D29A22UL, 0xE32DBF9AUL, 0x058745B9UL, 0x3453DC1EUL,
|
||||
0xD699296EUL, 0x496CFF6FUL, 0x1C9F4986UL, 0xDFE2ED07UL,
|
||||
0xB87242D1UL, 0x19DE7EAEUL, 0x053E561AUL, 0x15AD6F8CUL,
|
||||
0x66626C1CUL, 0x7154C24CUL, 0xEA082B2AUL, 0x93EB2939UL,
|
||||
0x17DCB0F0UL, 0x58D4F2AEUL, 0x9EA294FBUL, 0x52CF564CUL,
|
||||
0x9883FE66UL, 0x2EC40581UL, 0x763953C3UL, 0x01D6692EUL,
|
||||
0xD3A0C108UL, 0xA1E7160EUL, 0xE4F2DFA6UL, 0x693ED285UL,
|
||||
0x74904698UL, 0x4C2B0EDDUL, 0x4F757656UL, 0x5D393378UL,
|
||||
0xA132234FUL, 0x3D321C5DUL, 0xC3F5E194UL, 0x4B269301UL,
|
||||
0xC79F022FUL, 0x3C997E7EUL, 0x5E4F9504UL, 0x3FFAFBBDUL,
|
||||
0x76F7AD0EUL, 0x296693F4UL, 0x3D1FCE6FUL, 0xC61E45BEUL,
|
||||
0xD3B5AB34UL, 0xF72BF9B7UL, 0x1B0434C0UL, 0x4E72B567UL,
|
||||
0x5592A33DUL, 0xB5229301UL, 0xCFD2A87FUL, 0x60AEB767UL,
|
||||
0x1814386BUL, 0x30BCC33DUL, 0x38A0C07DUL, 0xFD1606F2UL,
|
||||
0xC363519BUL, 0x589DD390UL, 0x5479F8E6UL, 0x1CB8D647UL,
|
||||
0x97FD61A9UL, 0xEA7759F4UL, 0x2D57539DUL, 0x569A58CFUL,
|
||||
0xE84E63ADUL, 0x462E1B78UL, 0x6580F87EUL, 0xF3817914UL,
|
||||
0x91DA55F4UL, 0x40A230F3UL, 0xD1988F35UL, 0xB6E318D2UL,
|
||||
0x3FFA50BCUL, 0x3D40F021UL, 0xC3C0BDAEUL, 0x4958C24CUL,
|
||||
0x518F36B2UL, 0x84B1D370UL, 0x0FEDCE83UL, 0x878DDADAUL,
|
||||
0xF2A279C7UL, 0x94E01BE8UL, 0x90716F4BUL, 0x954B8AA3UL
|
||||
},
|
||||
|
||||
{
|
||||
0xE216300DUL, 0xBBDDFFFCUL, 0xA7EBDABDUL, 0x35648095UL,
|
||||
0x7789F8B7UL, 0xE6C1121BUL, 0x0E241600UL, 0x052CE8B5UL,
|
||||
0x11A9CFB0UL, 0xE5952F11UL, 0xECE7990AUL, 0x9386D174UL,
|
||||
0x2A42931CUL, 0x76E38111UL, 0xB12DEF3AUL, 0x37DDDDFCUL,
|
||||
0xDE9ADEB1UL, 0x0A0CC32CUL, 0xBE197029UL, 0x84A00940UL,
|
||||
0xBB243A0FUL, 0xB4D137CFUL, 0xB44E79F0UL, 0x049EEDFDUL,
|
||||
0x0B15A15DUL, 0x480D3168UL, 0x8BBBDE5AUL, 0x669DED42UL,
|
||||
0xC7ECE831UL, 0x3F8F95E7UL, 0x72DF191BUL, 0x7580330DUL,
|
||||
0x94074251UL, 0x5C7DCDFAUL, 0xABBE6D63UL, 0xAA402164UL,
|
||||
0xB301D40AUL, 0x02E7D1CAUL, 0x53571DAEUL, 0x7A3182A2UL,
|
||||
0x12A8DDECUL, 0xFDAA335DUL, 0x176F43E8UL, 0x71FB46D4UL,
|
||||
0x38129022UL, 0xCE949AD4UL, 0xB84769ADUL, 0x965BD862UL,
|
||||
0x82F3D055UL, 0x66FB9767UL, 0x15B80B4EUL, 0x1D5B47A0UL,
|
||||
0x4CFDE06FUL, 0xC28EC4B8UL, 0x57E8726EUL, 0x647A78FCUL,
|
||||
0x99865D44UL, 0x608BD593UL, 0x6C200E03UL, 0x39DC5FF6UL,
|
||||
0x5D0B00A3UL, 0xAE63AFF2UL, 0x7E8BD632UL, 0x70108C0CUL,
|
||||
0xBBD35049UL, 0x2998DF04UL, 0x980CF42AUL, 0x9B6DF491UL,
|
||||
0x9E7EDD53UL, 0x06918548UL, 0x58CB7E07UL, 0x3B74EF2EUL,
|
||||
0x522FFFB1UL, 0xD24708CCUL, 0x1C7E27CDUL, 0xA4EB215BUL,
|
||||
0x3CF1D2E2UL, 0x19B47A38UL, 0x424F7618UL, 0x35856039UL,
|
||||
0x9D17DEE7UL, 0x27EB35E6UL, 0xC9AFF67BUL, 0x36BAF5B8UL,
|
||||
0x09C467CDUL, 0xC18910B1UL, 0xE11DBF7BUL, 0x06CD1AF8UL,
|
||||
0x7170C608UL, 0x2D5E3354UL, 0xD4DE495AUL, 0x64C6D006UL,
|
||||
0xBCC0C62CUL, 0x3DD00DB3UL, 0x708F8F34UL, 0x77D51B42UL,
|
||||
0x264F620FUL, 0x24B8D2BFUL, 0x15C1B79EUL, 0x46A52564UL,
|
||||
0xF8D7E54EUL, 0x3E378160UL, 0x7895CDA5UL, 0x859C15A5UL,
|
||||
0xE6459788UL, 0xC37BC75FUL, 0xDB07BA0CUL, 0x0676A3ABUL,
|
||||
0x7F229B1EUL, 0x31842E7BUL, 0x24259FD7UL, 0xF8BEF472UL,
|
||||
0x835FFCB8UL, 0x6DF4C1F2UL, 0x96F5B195UL, 0xFD0AF0FCUL,
|
||||
0xB0FE134CUL, 0xE2506D3DUL, 0x4F9B12EAUL, 0xF215F225UL,
|
||||
0xA223736FUL, 0x9FB4C428UL, 0x25D04979UL, 0x34C713F8UL,
|
||||
0xC4618187UL, 0xEA7A6E98UL, 0x7CD16EFCUL, 0x1436876CUL,
|
||||
0xF1544107UL, 0xBEDEEE14UL, 0x56E9AF27UL, 0xA04AA441UL,
|
||||
0x3CF7C899UL, 0x92ECBAE6UL, 0xDD67016DUL, 0x151682EBUL,
|
||||
0xA842EEDFUL, 0xFDBA60B4UL, 0xF1907B75UL, 0x20E3030FUL,
|
||||
0x24D8C29EUL, 0xE139673BUL, 0xEFA63FB8UL, 0x71873054UL,
|
||||
0xB6F2CF3BUL, 0x9F326442UL, 0xCB15A4CCUL, 0xB01A4504UL,
|
||||
0xF1E47D8DUL, 0x844A1BE5UL, 0xBAE7DFDCUL, 0x42CBDA70UL,
|
||||
0xCD7DAE0AUL, 0x57E85B7AUL, 0xD53F5AF6UL, 0x20CF4D8CUL,
|
||||
0xCEA4D428UL, 0x79D130A4UL, 0x3486EBFBUL, 0x33D3CDDCUL,
|
||||
0x77853B53UL, 0x37EFFCB5UL, 0xC5068778UL, 0xE580B3E6UL,
|
||||
0x4E68B8F4UL, 0xC5C8B37EUL, 0x0D809EA2UL, 0x398FEB7CUL,
|
||||
0x132A4F94UL, 0x43B7950EUL, 0x2FEE7D1CUL, 0x223613BDUL,
|
||||
0xDD06CAA2UL, 0x37DF932BUL, 0xC4248289UL, 0xACF3EBC3UL,
|
||||
0x5715F6B7UL, 0xEF3478DDUL, 0xF267616FUL, 0xC148CBE4UL,
|
||||
0x9052815EUL, 0x5E410FABUL, 0xB48A2465UL, 0x2EDA7FA4UL,
|
||||
0xE87B40E4UL, 0xE98EA084UL, 0x5889E9E1UL, 0xEFD390FCUL,
|
||||
0xDD07D35BUL, 0xDB485694UL, 0x38D7E5B2UL, 0x57720101UL,
|
||||
0x730EDEBCUL, 0x5B643113UL, 0x94917E4FUL, 0x503C2FBAUL,
|
||||
0x646F1282UL, 0x7523D24AUL, 0xE0779695UL, 0xF9C17A8FUL,
|
||||
0x7A5B2121UL, 0xD187B896UL, 0x29263A4DUL, 0xBA510CDFUL,
|
||||
0x81F47C9FUL, 0xAD1163EDUL, 0xEA7B5965UL, 0x1A00726EUL,
|
||||
0x11403092UL, 0x00DA6D77UL, 0x4A0CDD61UL, 0xAD1F4603UL,
|
||||
0x605BDFB0UL, 0x9EEDC364UL, 0x22EBE6A8UL, 0xCEE7D28AUL,
|
||||
0xA0E736A0UL, 0x5564A6B9UL, 0x10853209UL, 0xC7EB8F37UL,
|
||||
0x2DE705CAUL, 0x8951570FUL, 0xDF09822BUL, 0xBD691A6CUL,
|
||||
0xAA12E4F2UL, 0x87451C0FUL, 0xE0F6A27AUL, 0x3ADA4819UL,
|
||||
0x4CF1764FUL, 0x0D771C2BUL, 0x67CDB156UL, 0x350D8384UL,
|
||||
0x5938FA0FUL, 0x42399EF3UL, 0x36997B07UL, 0x0E84093DUL,
|
||||
0x4AA93E61UL, 0x8360D87BUL, 0x1FA98B0CUL, 0x1149382CUL,
|
||||
0xE97625A5UL, 0x0614D1B7UL, 0x0E25244BUL, 0x0C768347UL,
|
||||
0x589E8D82UL, 0x0D2059D1UL, 0xA466BB1EUL, 0xF8DA0A82UL,
|
||||
0x04F19130UL, 0xBA6E4EC0UL, 0x99265164UL, 0x1EE7230DUL,
|
||||
0x50B2AD80UL, 0xEAEE6801UL, 0x8DB2A283UL, 0xEA8BF59EUL
|
||||
}};
|
||||
|
||||
NAMESPACE_END
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#include "pch.h"
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
#include "cbcmac.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
void CBC_MAC_Base::UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms)
|
||||
{
|
||||
AccessCipher().SetKey(key, length, params);
|
||||
m_reg.CleanNew(AccessCipher().BlockSize());
|
||||
m_counter = 0;
|
||||
}
|
||||
|
||||
void CBC_MAC_Base::Update(const byte *input, size_t length)
|
||||
{
|
||||
unsigned int blockSize = AccessCipher().BlockSize();
|
||||
|
||||
while (m_counter && length)
|
||||
{
|
||||
m_reg[m_counter++] ^= *input++;
|
||||
if (m_counter == blockSize)
|
||||
ProcessBuf();
|
||||
length--;
|
||||
}
|
||||
|
||||
if (length >= blockSize)
|
||||
{
|
||||
size_t leftOver = AccessCipher().AdvancedProcessBlocks(m_reg, input, m_reg, length, BlockTransformation::BT_DontIncrementInOutPointers|BlockTransformation::BT_XorInput);
|
||||
input += (length - leftOver);
|
||||
length = leftOver;
|
||||
}
|
||||
|
||||
while (length--)
|
||||
{
|
||||
m_reg[m_counter++] ^= *input++;
|
||||
if (m_counter == blockSize)
|
||||
ProcessBuf();
|
||||
}
|
||||
}
|
||||
|
||||
void CBC_MAC_Base::TruncatedFinal(byte *mac, size_t size)
|
||||
{
|
||||
ThrowIfInvalidTruncatedSize(size);
|
||||
|
||||
if (m_counter)
|
||||
ProcessBuf();
|
||||
|
||||
memcpy(mac, m_reg, size);
|
||||
memset(m_reg, 0, AccessCipher().BlockSize());
|
||||
}
|
||||
|
||||
void CBC_MAC_Base::ProcessBuf()
|
||||
{
|
||||
AccessCipher().ProcessBlock(m_reg);
|
||||
m_counter = 0;
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
// cbcmac.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file
|
||||
/// \brief Classes for CBC MAC
|
||||
/// \since Crypto++ 3.1
|
||||
|
||||
#ifndef CRYPTOPP_CBCMAC_H
|
||||
#define CRYPTOPP_CBCMAC_H
|
||||
|
||||
#include "seckey.h"
|
||||
#include "secblock.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief CBC-MAC base class
|
||||
/// \since Crypto++ 3.1
|
||||
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_MAC_Base : public MessageAuthenticationCode
|
||||
{
|
||||
public:
|
||||
CBC_MAC_Base() : m_counter(0) {}
|
||||
|
||||
void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms);
|
||||
void Update(const byte *input, size_t length);
|
||||
void TruncatedFinal(byte *mac, size_t size);
|
||||
unsigned int DigestSize() const {return const_cast<CBC_MAC_Base*>(this)->AccessCipher().BlockSize();}
|
||||
|
||||
protected:
|
||||
virtual BlockCipher & AccessCipher() =0;
|
||||
|
||||
private:
|
||||
void ProcessBuf();
|
||||
SecByteBlock m_reg;
|
||||
unsigned int m_counter;
|
||||
};
|
||||
|
||||
/// \brief CBC-MAC
|
||||
/// \tparam T BlockCipherDocumentation derived class
|
||||
/// \details CBC-MAC is compatible with FIPS 113. The MAC is secure only for fixed
|
||||
/// length messages. For variable length messages use CMAC or DMAC.
|
||||
/// \sa <a href="http://www.weidai.com/scan-mirror/mac.html#CBC-MAC">CBC-MAC</a>
|
||||
/// \since Crypto++ 3.1
|
||||
template <class T>
|
||||
class CBC_MAC : public MessageAuthenticationCodeImpl<CBC_MAC_Base, CBC_MAC<T> >, public SameKeyLengthAs<T>
|
||||
{
|
||||
public:
|
||||
CBC_MAC() {}
|
||||
CBC_MAC(const byte *key, size_t length=SameKeyLengthAs<T>::DEFAULT_KEYLENGTH)
|
||||
{this->SetKey(key, length);}
|
||||
|
||||
static std::string StaticAlgorithmName() {return std::string("CBC-MAC(") + T::StaticAlgorithmName() + ")";}
|
||||
|
||||
private:
|
||||
BlockCipher & AccessCipher() {return m_cipher;}
|
||||
typename T::Encryption m_cipher;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
// ccm.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
#include "ccm.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
void CCM_Base::SetKeyWithoutResync(const byte *userKey, size_t keylength, const NameValuePairs ¶ms)
|
||||
{
|
||||
BlockCipher &blockCipher = AccessBlockCipher();
|
||||
blockCipher.SetKey(userKey, keylength, params);
|
||||
|
||||
if (blockCipher.BlockSize() != REQUIRED_BLOCKSIZE)
|
||||
throw InvalidArgument(AlgorithmName() + ": block size of underlying block cipher is not 16");
|
||||
|
||||
m_digestSize = params.GetIntValueWithDefault(Name::DigestSize(), DefaultDigestSize());
|
||||
if (m_digestSize % 2 > 0 || m_digestSize < 4 || m_digestSize > 16)
|
||||
throw InvalidArgument(AlgorithmName() + ": DigestSize must be 4, 6, 8, 10, 12, 14, or 16");
|
||||
|
||||
m_buffer.Grow(2*REQUIRED_BLOCKSIZE);
|
||||
m_L = 8;
|
||||
}
|
||||
|
||||
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);
|
||||
if (m_L > 8)
|
||||
m_L = 8;
|
||||
|
||||
m_buffer[0] = byte(m_L-1); // flag
|
||||
memcpy(m_buffer+1, iv, len);
|
||||
memset(m_buffer+1+len, 0, REQUIRED_BLOCKSIZE-1-len);
|
||||
|
||||
if (m_state >= State_IVSet)
|
||||
m_ctr.Resynchronize(m_buffer, REQUIRED_BLOCKSIZE);
|
||||
else
|
||||
m_ctr.SetCipherWithIV(cipher, m_buffer);
|
||||
|
||||
m_ctr.Seek(REQUIRED_BLOCKSIZE);
|
||||
m_aadLength = 0;
|
||||
m_messageLength = 0;
|
||||
}
|
||||
|
||||
void CCM_Base::UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword /*footerLength*/)
|
||||
{
|
||||
if (m_state != State_IVSet)
|
||||
throw BadState(AlgorithmName(), "SpecifyDataLengths", "or after State_IVSet");
|
||||
|
||||
m_aadLength = headerLength;
|
||||
m_messageLength = messageLength;
|
||||
|
||||
byte *cbcBuffer = CBC_Buffer();
|
||||
const BlockCipher &cipher = GetBlockCipher();
|
||||
|
||||
cbcBuffer[0] = byte(64*(headerLength>0) + 8*((m_digestSize-2)/2) + (m_L-1)); // flag
|
||||
PutWord<word64>(true, BIG_ENDIAN_ORDER, cbcBuffer+REQUIRED_BLOCKSIZE-8, m_messageLength);
|
||||
memcpy(cbcBuffer+1, m_buffer+1, REQUIRED_BLOCKSIZE-1-m_L);
|
||||
cipher.ProcessBlock(cbcBuffer);
|
||||
|
||||
if (headerLength>0)
|
||||
{
|
||||
CRYPTOPP_ASSERT(m_bufferedDataLength == 0);
|
||||
|
||||
if (headerLength < ((1<<16) - (1<<8)))
|
||||
{
|
||||
PutWord<word16>(true, BIG_ENDIAN_ORDER, m_buffer, (word16)headerLength);
|
||||
m_bufferedDataLength = 2;
|
||||
}
|
||||
else if (headerLength < (W64LIT(1)<<32))
|
||||
{
|
||||
m_buffer[0] = 0xff;
|
||||
m_buffer[1] = 0xfe;
|
||||
PutWord<word32>(false, BIG_ENDIAN_ORDER, m_buffer+2, (word32)headerLength);
|
||||
m_bufferedDataLength = 6;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_buffer[0] = 0xff;
|
||||
m_buffer[1] = 0xff;
|
||||
PutWord<word64>(false, BIG_ENDIAN_ORDER, m_buffer+2, headerLength);
|
||||
m_bufferedDataLength = 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
size_t CCM_Base::AuthenticateBlocks(const byte *data, size_t len)
|
||||
{
|
||||
byte *cbcBuffer = CBC_Buffer();
|
||||
const BlockCipher &cipher = GetBlockCipher();
|
||||
return cipher.AdvancedProcessBlocks(cbcBuffer, data, cbcBuffer, len, BlockTransformation::BT_DontIncrementInOutPointers|BlockTransformation::BT_XorInput);
|
||||
}
|
||||
|
||||
void CCM_Base::AuthenticateLastHeaderBlock()
|
||||
{
|
||||
byte *cbcBuffer = CBC_Buffer();
|
||||
const BlockCipher &cipher = GetBlockCipher();
|
||||
|
||||
if (m_aadLength != m_totalHeaderLength)
|
||||
throw InvalidArgument(AlgorithmName() + ": header length doesn't match that given in SpecifyDataLengths");
|
||||
|
||||
if (m_bufferedDataLength > 0)
|
||||
{
|
||||
xorbuf(cbcBuffer, m_buffer, m_bufferedDataLength);
|
||||
cipher.ProcessBlock(cbcBuffer);
|
||||
m_bufferedDataLength = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void CCM_Base::AuthenticateLastConfidentialBlock()
|
||||
{
|
||||
byte *cbcBuffer = CBC_Buffer();
|
||||
const BlockCipher &cipher = GetBlockCipher();
|
||||
|
||||
if (m_messageLength != m_totalMessageLength)
|
||||
throw InvalidArgument(AlgorithmName() + ": message length doesn't match that given in SpecifyDataLengths");
|
||||
|
||||
if (m_bufferedDataLength > 0)
|
||||
{
|
||||
xorbuf(cbcBuffer, m_buffer, m_bufferedDataLength);
|
||||
cipher.ProcessBlock(cbcBuffer);
|
||||
m_bufferedDataLength = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void CCM_Base::AuthenticateLastFooterBlock(byte *mac, size_t macSize)
|
||||
{
|
||||
m_ctr.Seek(0);
|
||||
m_ctr.ProcessData(mac, CBC_Buffer(), macSize);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
Vendored
+123
@@ -0,0 +1,123 @@
|
||||
// ccm.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file ccm.h
|
||||
/// \brief CCM block cipher mode of operation
|
||||
/// \since Crypto++ 5.6.0
|
||||
|
||||
#ifndef CRYPTOPP_CCM_H
|
||||
#define CRYPTOPP_CCM_H
|
||||
|
||||
#include "authenc.h"
|
||||
#include "modes.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief CCM block cipher base implementation
|
||||
/// \details Base implementation of the AuthenticatedSymmetricCipher interface
|
||||
/// \since Crypto++ 5.6.0
|
||||
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CCM_Base : public AuthenticatedSymmetricCipherBase
|
||||
{
|
||||
public:
|
||||
CCM_Base()
|
||||
: m_digestSize(0), m_L(0), m_messageLength(0), m_aadLength(0) {}
|
||||
|
||||
// AuthenticatedSymmetricCipher
|
||||
std::string AlgorithmName() const
|
||||
{return GetBlockCipher().AlgorithmName() + std::string("/CCM");}
|
||||
std::string AlgorithmProvider() const
|
||||
{return GetBlockCipher().AlgorithmProvider();}
|
||||
size_t MinKeyLength() const
|
||||
{return GetBlockCipher().MinKeyLength();}
|
||||
size_t MaxKeyLength() const
|
||||
{return GetBlockCipher().MaxKeyLength();}
|
||||
size_t DefaultKeyLength() const
|
||||
{return GetBlockCipher().DefaultKeyLength();}
|
||||
size_t GetValidKeyLength(size_t keylength) const
|
||||
{return GetBlockCipher().GetValidKeyLength(keylength);}
|
||||
bool IsValidKeyLength(size_t keylength) const
|
||||
{return GetBlockCipher().IsValidKeyLength(keylength);}
|
||||
unsigned int OptimalDataAlignment() const
|
||||
{return GetBlockCipher().OptimalDataAlignment();}
|
||||
IV_Requirement IVRequirement() const
|
||||
{return UNIQUE_IV;}
|
||||
unsigned int IVSize() const
|
||||
{return 8;}
|
||||
unsigned int MinIVLength() const
|
||||
{return 7;}
|
||||
unsigned int MaxIVLength() const
|
||||
{return 13;}
|
||||
unsigned int DigestSize() const
|
||||
{return m_digestSize;}
|
||||
lword MaxHeaderLength() const
|
||||
{return W64LIT(0)-1;}
|
||||
lword MaxMessageLength() const
|
||||
{return m_L<8 ? (W64LIT(1)<<(8*m_L))-1 : W64LIT(0)-1;}
|
||||
bool NeedsPrespecifiedDataLengths() const
|
||||
{return true;}
|
||||
void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength);
|
||||
|
||||
protected:
|
||||
// AuthenticatedSymmetricCipherBase
|
||||
bool AuthenticationIsOnPlaintext() const
|
||||
{return true;}
|
||||
unsigned int AuthenticationBlockSize() const
|
||||
{return GetBlockCipher().BlockSize();}
|
||||
void SetKeyWithoutResync(const byte *userKey, size_t keylength, const NameValuePairs ¶ms);
|
||||
void Resync(const byte *iv, size_t len);
|
||||
size_t AuthenticateBlocks(const byte *data, size_t len);
|
||||
void AuthenticateLastHeaderBlock();
|
||||
void AuthenticateLastConfidentialBlock();
|
||||
void AuthenticateLastFooterBlock(byte *mac, size_t macSize);
|
||||
SymmetricCipher & AccessSymmetricCipher() {return m_ctr;}
|
||||
|
||||
virtual BlockCipher & AccessBlockCipher() =0;
|
||||
virtual int DefaultDigestSize() const =0;
|
||||
|
||||
const BlockCipher & GetBlockCipher() const {return const_cast<CCM_Base *>(this)->AccessBlockCipher();}
|
||||
byte *CBC_Buffer() {return m_buffer+REQUIRED_BLOCKSIZE;}
|
||||
|
||||
enum {REQUIRED_BLOCKSIZE = 16};
|
||||
int m_digestSize, m_L;
|
||||
word64 m_messageLength, m_aadLength;
|
||||
CTR_Mode_ExternalCipher::Encryption m_ctr;
|
||||
};
|
||||
|
||||
/// \brief CCM block cipher final implementation
|
||||
/// \tparam T_BlockCipher block cipher
|
||||
/// \tparam T_DefaultDigestSize default digest size, in bytes
|
||||
/// \tparam T_IsEncryption direction in which to operate the cipher
|
||||
/// \since Crypto++ 5.6.0
|
||||
template <class T_BlockCipher, int T_DefaultDigestSize, bool T_IsEncryption>
|
||||
class CCM_Final : public CCM_Base
|
||||
{
|
||||
public:
|
||||
static std::string StaticAlgorithmName()
|
||||
{return T_BlockCipher::StaticAlgorithmName() + std::string("/CCM");}
|
||||
bool IsForwardTransformation() const
|
||||
{return T_IsEncryption;}
|
||||
|
||||
private:
|
||||
BlockCipher & AccessBlockCipher() {return m_cipher;}
|
||||
int DefaultDigestSize() const {return T_DefaultDigestSize;}
|
||||
typename T_BlockCipher::Encryption m_cipher;
|
||||
};
|
||||
|
||||
/// \brief CCM block cipher mode of operation
|
||||
/// \tparam T_BlockCipher block cipher
|
||||
/// \tparam T_DefaultDigestSize default digest size, in bytes
|
||||
/// \details \p CCM provides the \p Encryption and \p Decryption typedef. See GCM_Base
|
||||
/// and GCM_Final for the AuthenticatedSymmetricCipher implementation.
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/CCM_Mode">CCM Mode</a> and
|
||||
/// <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
|
||||
/// on the Crypto++ wiki.
|
||||
/// \since Crypto++ 5.6.0
|
||||
template <class T_BlockCipher, int T_DefaultDigestSize = 16>
|
||||
struct CCM : public AuthenticatedSymmetricCipherDocumentation
|
||||
{
|
||||
typedef CCM_Final<T_BlockCipher, T_DefaultDigestSize, true> Encryption;
|
||||
typedef CCM_Final<T_BlockCipher, T_DefaultDigestSize, false> Decryption;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+568
@@ -0,0 +1,568 @@
|
||||
// chacha.cpp - written and placed in the public domain by Jeffrey Walton.
|
||||
// Based on Wei Dai's Salsa20, Botan's SSE2 implementation,
|
||||
// and Bernstein's reference ChaCha family implementation at
|
||||
// http://cr.yp.to/chacha.html.
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
#include "chacha.h"
|
||||
#include "argnames.h"
|
||||
#include "misc.h"
|
||||
#include "cpu.h"
|
||||
|
||||
// Internal compiler error in GCC 3.3 and below
|
||||
#if defined(__GNUC__) && (__GNUC__ < 4)
|
||||
# undef CRYPTOPP_SSE2_INTRIN_AVAILABLE
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
extern void ChaCha_OperateKeystream_NEON(const word32 *state, const byte* input, byte *output, unsigned int rounds);
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_AVX2_AVAILABLE)
|
||||
extern void ChaCha_OperateKeystream_AVX2(const word32 *state, const byte* input, byte *output, unsigned int rounds);
|
||||
#endif
|
||||
#if (CRYPTOPP_SSE2_INTRIN_AVAILABLE)
|
||||
extern void ChaCha_OperateKeystream_SSE2(const word32 *state, const byte* input, byte *output, unsigned int rounds);
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_ALTIVEC_AVAILABLE)
|
||||
extern void ChaCha_OperateKeystream_ALTIVEC(const word32 *state, const byte* input, byte *output, unsigned int rounds);
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_DEBUG) && !defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
void ChaCha_TestInstantiations()
|
||||
{
|
||||
ChaCha::Encryption x;
|
||||
ChaChaTLS::Encryption y;
|
||||
XChaCha20::Encryption z;
|
||||
}
|
||||
#endif
|
||||
|
||||
NAMESPACE_END // CryptoPP
|
||||
|
||||
////////////////////////////// ChaCha Core //////////////////////////////
|
||||
|
||||
#define CHACHA_QUARTER_ROUND(a,b,c,d) \
|
||||
a += b; d ^= a; d = rotlConstant<16,word32>(d); \
|
||||
c += d; b ^= c; b = rotlConstant<12,word32>(b); \
|
||||
a += b; d ^= a; d = rotlConstant<8,word32>(d); \
|
||||
c += d; b ^= c; b = rotlConstant<7,word32>(b);
|
||||
|
||||
#define CHACHA_OUTPUT(x){\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 0, x0 + state[0]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 1, x1 + state[1]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 2, x2 + state[2]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 3, x3 + state[3]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 4, x4 + state[4]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 5, x5 + state[5]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 6, x6 + state[6]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 7, x7 + state[7]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 8, x8 + state[8]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 9, x9 + state[9]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 10, x10 + state[10]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 11, x11 + state[11]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 12, x12 + state[12]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 13, x13 + state[13]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 14, x14 + state[14]);\
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, LITTLE_ENDIAN_ORDER, 15, x15 + state[15]);}
|
||||
|
||||
ANONYMOUS_NAMESPACE_BEGIN
|
||||
|
||||
// Hacks... Bring in all symbols, and supply
|
||||
// the stuff the templates normally provide.
|
||||
using namespace CryptoPP;
|
||||
typedef word32 WordType;
|
||||
enum {BYTES_PER_ITERATION=64};
|
||||
|
||||
// MultiBlockSafe detects a condition that can arise in the SIMD
|
||||
// implementations where we overflow one of the 32-bit state words during
|
||||
// addition in an intermediate result. Preconditions for the issue include
|
||||
// a user seeks to around 2^32 blocks (256 GB of data) for ChaCha; or a
|
||||
// user specifies an arbitrarily large initial counter block for ChaChaTLS.
|
||||
// Also see https://github.com/weidai11/cryptopp/issues/732.
|
||||
inline bool MultiBlockSafe(unsigned int ctrLow, unsigned int blocks)
|
||||
{
|
||||
return 0xffffffff - ctrLow > blocks;
|
||||
}
|
||||
|
||||
// OperateKeystream always produces a key stream. The key stream is written
|
||||
// to output. Optionally a message may be supplied to xor with the key stream.
|
||||
// The message is input, and output = output ^ input.
|
||||
void ChaCha_OperateKeystream(KeystreamOperation operation,
|
||||
word32 state[16], word32& ctrLow, word32& ctrHigh, word32 rounds,
|
||||
byte *output, const byte *input, size_t iterationCount)
|
||||
{
|
||||
do
|
||||
{
|
||||
#if (CRYPTOPP_AVX2_AVAILABLE)
|
||||
if (HasAVX2())
|
||||
{
|
||||
while (iterationCount >= 8 && MultiBlockSafe(state[12], 8))
|
||||
{
|
||||
const bool xorInput = (operation & INPUT_NULL) != INPUT_NULL;
|
||||
ChaCha_OperateKeystream_AVX2(state, xorInput ? input : NULLPTR, output, rounds);
|
||||
|
||||
// MultiBlockSafe avoids overflow on the counter words
|
||||
state[12] += 8;
|
||||
|
||||
input += (!!xorInput) * 8 * BYTES_PER_ITERATION;
|
||||
output += 8 * BYTES_PER_ITERATION;
|
||||
iterationCount -= 8;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_SSE2_INTRIN_AVAILABLE)
|
||||
if (HasSSE2())
|
||||
{
|
||||
while (iterationCount >= 4 && MultiBlockSafe(state[12], 4))
|
||||
{
|
||||
const bool xorInput = (operation & INPUT_NULL) != INPUT_NULL;
|
||||
ChaCha_OperateKeystream_SSE2(state, xorInput ? input : NULLPTR, output, rounds);
|
||||
|
||||
// MultiBlockSafe avoids overflow on the counter words
|
||||
state[12] += 4;
|
||||
|
||||
input += (!!xorInput)*4*BYTES_PER_ITERATION;
|
||||
output += 4*BYTES_PER_ITERATION;
|
||||
iterationCount -= 4;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
if (HasNEON())
|
||||
{
|
||||
while (iterationCount >= 4 && MultiBlockSafe(state[12], 4))
|
||||
{
|
||||
const bool xorInput = (operation & INPUT_NULL) != INPUT_NULL;
|
||||
ChaCha_OperateKeystream_NEON(state, xorInput ? input : NULLPTR, output, rounds);
|
||||
|
||||
// MultiBlockSafe avoids overflow on the counter words
|
||||
state[12] += 4;
|
||||
|
||||
input += (!!xorInput)*4*BYTES_PER_ITERATION;
|
||||
output += 4*BYTES_PER_ITERATION;
|
||||
iterationCount -= 4;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_ALTIVEC_AVAILABLE)
|
||||
if (HasAltivec())
|
||||
{
|
||||
while (iterationCount >= 4 && MultiBlockSafe(state[12], 4))
|
||||
{
|
||||
const bool xorInput = (operation & INPUT_NULL) != INPUT_NULL;
|
||||
ChaCha_OperateKeystream_ALTIVEC(state, xorInput ? input : NULLPTR, output, rounds);
|
||||
|
||||
// MultiBlockSafe avoids overflow on the counter words
|
||||
state[12] += 4;
|
||||
|
||||
input += (!!xorInput)*4*BYTES_PER_ITERATION;
|
||||
output += 4*BYTES_PER_ITERATION;
|
||||
iterationCount -= 4;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (iterationCount)
|
||||
{
|
||||
word32 x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15;
|
||||
|
||||
x0 = state[0]; x1 = state[1]; x2 = state[2]; x3 = state[3];
|
||||
x4 = state[4]; x5 = state[5]; x6 = state[6]; x7 = state[7];
|
||||
x8 = state[8]; x9 = state[9]; x10 = state[10]; x11 = state[11];
|
||||
x12 = state[12]; x13 = state[13]; x14 = state[14]; x15 = state[15];
|
||||
|
||||
for (int i = static_cast<int>(rounds); i > 0; i -= 2)
|
||||
{
|
||||
CHACHA_QUARTER_ROUND(x0, x4, x8, x12);
|
||||
CHACHA_QUARTER_ROUND(x1, x5, x9, x13);
|
||||
CHACHA_QUARTER_ROUND(x2, x6, x10, x14);
|
||||
CHACHA_QUARTER_ROUND(x3, x7, x11, x15);
|
||||
|
||||
CHACHA_QUARTER_ROUND(x0, x5, x10, x15);
|
||||
CHACHA_QUARTER_ROUND(x1, x6, x11, x12);
|
||||
CHACHA_QUARTER_ROUND(x2, x7, x8, x13);
|
||||
CHACHA_QUARTER_ROUND(x3, x4, x9, x14);
|
||||
}
|
||||
|
||||
CRYPTOPP_KEYSTREAM_OUTPUT_SWITCH(CHACHA_OUTPUT, BYTES_PER_ITERATION);
|
||||
|
||||
// This is state[12] and state[13] from ChaCha. In the case of
|
||||
// ChaChaTLS ctrHigh is a reference to a discard value.
|
||||
if (++ctrLow == 0)
|
||||
ctrHigh++;
|
||||
}
|
||||
|
||||
// We may re-enter a SIMD keystream operation from here.
|
||||
} while (iterationCount--);
|
||||
}
|
||||
|
||||
// XChaCha key derivation
|
||||
void HChaCha_OperateKeystream(const word32 state[16], word32 output[8])
|
||||
{
|
||||
word32 x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15;
|
||||
|
||||
x0 = state[0]; x1 = state[1]; x2 = state[2]; x3 = state[3];
|
||||
x4 = state[4]; x5 = state[5]; x6 = state[6]; x7 = state[7];
|
||||
x8 = state[8]; x9 = state[9]; x10 = state[10]; x11 = state[11];
|
||||
x12 = state[12]; x13 = state[13]; x14 = state[14]; x15 = state[15];
|
||||
|
||||
for (int i = 20; i > 0; i -= 2)
|
||||
{
|
||||
CHACHA_QUARTER_ROUND(x0, x4, x8, x12);
|
||||
CHACHA_QUARTER_ROUND(x1, x5, x9, x13);
|
||||
CHACHA_QUARTER_ROUND(x2, x6, x10, x14);
|
||||
CHACHA_QUARTER_ROUND(x3, x7, x11, x15);
|
||||
|
||||
CHACHA_QUARTER_ROUND(x0, x5, x10, x15);
|
||||
CHACHA_QUARTER_ROUND(x1, x6, x11, x12);
|
||||
CHACHA_QUARTER_ROUND(x2, x7, x8, x13);
|
||||
CHACHA_QUARTER_ROUND(x3, x4, x9, x14);
|
||||
}
|
||||
|
||||
output[0] = x0; output[1] = x1;
|
||||
output[2] = x2; output[3] = x3;
|
||||
output[4] = x12; output[5] = x13;
|
||||
output[6] = x14; output[7] = x15;
|
||||
}
|
||||
|
||||
std::string ChaCha_AlgorithmProvider()
|
||||
{
|
||||
#if (CRYPTOPP_AVX2_AVAILABLE)
|
||||
if (HasAVX2())
|
||||
return "AVX2";
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_SSE2_INTRIN_AVAILABLE)
|
||||
if (HasSSE2())
|
||||
return "SSE2";
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
if (HasNEON())
|
||||
return "NEON";
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ALTIVEC_AVAILABLE)
|
||||
if (HasAltivec())
|
||||
return "Altivec";
|
||||
else
|
||||
#endif
|
||||
return "C++";
|
||||
}
|
||||
|
||||
unsigned int ChaCha_GetAlignment()
|
||||
{
|
||||
#if (CRYPTOPP_AVX2_AVAILABLE)
|
||||
if (HasAVX2())
|
||||
return 16;
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_SSE2_INTRIN_AVAILABLE)
|
||||
if (HasSSE2())
|
||||
return 16;
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ALTIVEC_AVAILABLE)
|
||||
if (HasAltivec())
|
||||
return 16;
|
||||
else
|
||||
#endif
|
||||
return GetAlignmentOf<word32>();
|
||||
}
|
||||
|
||||
unsigned int ChaCha_GetOptimalBlockSize()
|
||||
{
|
||||
#if (CRYPTOPP_AVX2_AVAILABLE)
|
||||
if (HasAVX2())
|
||||
return 8 * BYTES_PER_ITERATION;
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_SSE2_INTRIN_AVAILABLE)
|
||||
if (HasSSE2())
|
||||
return 4*BYTES_PER_ITERATION;
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
|
||||
if (HasNEON())
|
||||
return 4*BYTES_PER_ITERATION;
|
||||
else
|
||||
#endif
|
||||
#if (CRYPTOPP_ALTIVEC_AVAILABLE)
|
||||
if (HasAltivec())
|
||||
return 4*BYTES_PER_ITERATION;
|
||||
else
|
||||
#endif
|
||||
return BYTES_PER_ITERATION;
|
||||
}
|
||||
|
||||
ANONYMOUS_NAMESPACE_END
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
////////////////////////////// Bernstein ChaCha //////////////////////////////
|
||||
|
||||
std::string ChaCha_Policy::AlgorithmName() const
|
||||
{
|
||||
return std::string("ChaCha")+IntToString(m_rounds);
|
||||
}
|
||||
|
||||
std::string ChaCha_Policy::AlgorithmProvider() const
|
||||
{
|
||||
return ChaCha_AlgorithmProvider();
|
||||
}
|
||||
|
||||
void ChaCha_Policy::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length)
|
||||
{
|
||||
CRYPTOPP_ASSERT(key); CRYPTOPP_ASSERT(length == 16 || length == 32);
|
||||
CRYPTOPP_UNUSED(key); CRYPTOPP_UNUSED(length);
|
||||
|
||||
// Use previous rounds as the default value
|
||||
int rounds = params.GetIntValueWithDefault(Name::Rounds(), m_rounds);
|
||||
if (rounds != 20 && rounds != 12 && rounds != 8)
|
||||
throw InvalidRounds(ChaCha::StaticAlgorithmName(), rounds);
|
||||
|
||||
// Latch a good value
|
||||
m_rounds = rounds;
|
||||
|
||||
// "expand 16-byte k" or "expand 32-byte k"
|
||||
m_state[0] = 0x61707865;
|
||||
m_state[1] = (length == 16) ? 0x3120646e : 0x3320646e;
|
||||
m_state[2] = (length == 16) ? 0x79622d36 : 0x79622d32;
|
||||
m_state[3] = 0x6b206574;
|
||||
|
||||
GetBlock<word32, LittleEndian> get1(key);
|
||||
get1(m_state[4])(m_state[5])(m_state[6])(m_state[7]);
|
||||
|
||||
GetBlock<word32, LittleEndian> get2(key + ((length == 32) ? 16 : 0));
|
||||
get2(m_state[8])(m_state[9])(m_state[10])(m_state[11]);
|
||||
}
|
||||
|
||||
void ChaCha_Policy::CipherResynchronize(byte *keystreamBuffer, const byte *IV, size_t length)
|
||||
{
|
||||
CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(length);
|
||||
CRYPTOPP_ASSERT(length==8); CRYPTOPP_UNUSED(length);
|
||||
|
||||
GetBlock<word32, LittleEndian> get(IV);
|
||||
m_state[12] = m_state[13] = 0;
|
||||
get(m_state[14])(m_state[15]);
|
||||
}
|
||||
|
||||
void ChaCha_Policy::SeekToIteration(lword iterationCount)
|
||||
{
|
||||
m_state[12] = (word32)iterationCount; // low word
|
||||
m_state[13] = (word32)SafeRightShift<32>(iterationCount);
|
||||
}
|
||||
|
||||
unsigned int ChaCha_Policy::GetAlignment() const
|
||||
{
|
||||
return ChaCha_GetAlignment();
|
||||
}
|
||||
|
||||
unsigned int ChaCha_Policy::GetOptimalBlockSize() const
|
||||
{
|
||||
return ChaCha_GetOptimalBlockSize();
|
||||
}
|
||||
|
||||
void ChaCha_Policy::OperateKeystream(KeystreamOperation operation,
|
||||
byte *output, const byte *input, size_t iterationCount)
|
||||
{
|
||||
ChaCha_OperateKeystream(operation, m_state, m_state[12], m_state[13],
|
||||
m_rounds, output, input, iterationCount);
|
||||
}
|
||||
|
||||
////////////////////////////// IETF ChaChaTLS //////////////////////////////
|
||||
|
||||
std::string ChaChaTLS_Policy::AlgorithmName() const
|
||||
{
|
||||
return std::string("ChaChaTLS");
|
||||
}
|
||||
|
||||
std::string ChaChaTLS_Policy::AlgorithmProvider() const
|
||||
{
|
||||
return ChaCha_AlgorithmProvider();
|
||||
}
|
||||
|
||||
void ChaChaTLS_Policy::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length)
|
||||
{
|
||||
CRYPTOPP_ASSERT(key); CRYPTOPP_ASSERT(length == 32);
|
||||
CRYPTOPP_UNUSED(length);
|
||||
|
||||
// ChaChaTLS is always 20 rounds. Fetch Rounds() to avoid a spurious failure.
|
||||
int rounds = params.GetIntValueWithDefault(Name::Rounds(), ROUNDS);
|
||||
if (rounds != 20)
|
||||
throw InvalidRounds(ChaChaTLS::StaticAlgorithmName(), rounds);
|
||||
|
||||
// RFC 8439 test vectors use an initial block counter. However, the counter
|
||||
// can be an arbitrary value per RFC 8439 Section 2.4. We stash the counter
|
||||
// away in state[16] and use it for a Resynchronize() operation. I think
|
||||
// the initial counter is used more like a Tweak when non-0, and it should
|
||||
// be provided in Resynchronize() (light-weight re-keying). However,
|
||||
// Resynchronize() does not have an overload that allows us to pass it into
|
||||
// the function, so we have to use the heavier-weight SetKey to change it.
|
||||
word64 block;
|
||||
if (params.GetValue("InitialBlock", block))
|
||||
m_counter = static_cast<word32>(block);
|
||||
else
|
||||
m_counter = 0;
|
||||
|
||||
// State words are defined in RFC 8439, Section 2.3. Key is 32-bytes.
|
||||
GetBlock<word32, LittleEndian> get(key);
|
||||
get(m_state[KEY+0])(m_state[KEY+1])(m_state[KEY+2])(m_state[KEY+3])
|
||||
(m_state[KEY+4])(m_state[KEY+5])(m_state[KEY+6])(m_state[KEY+7]);
|
||||
}
|
||||
|
||||
void ChaChaTLS_Policy::CipherResynchronize(byte *keystreamBuffer, const byte *IV, size_t length)
|
||||
{
|
||||
CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(length);
|
||||
CRYPTOPP_ASSERT(length==12);
|
||||
|
||||
// State words are defined in RFC 8439, Section 2.3.
|
||||
m_state[0] = 0x61707865; m_state[1] = 0x3320646e;
|
||||
m_state[2] = 0x79622d32; m_state[3] = 0x6b206574;
|
||||
|
||||
// Copy saved key into state
|
||||
std::memcpy(m_state+4, m_state+KEY, 8*sizeof(word32));
|
||||
|
||||
// State words are defined in RFC 8439, Section 2.3
|
||||
GetBlock<word32, LittleEndian> get(IV);
|
||||
m_state[12] = m_counter;
|
||||
get(m_state[13])(m_state[14])(m_state[15]);
|
||||
}
|
||||
|
||||
void ChaChaTLS_Policy::SeekToIteration(lword iterationCount)
|
||||
{
|
||||
// Should we throw here??? If the initial block counter is
|
||||
// large then we can wrap and process more data as long as
|
||||
// data processed in the security context does not exceed
|
||||
// 2^32 blocks or approximately 256 GB of data.
|
||||
CRYPTOPP_ASSERT(iterationCount <= std::numeric_limits<word32>::max());
|
||||
m_state[12] = (word32)iterationCount; // low word
|
||||
}
|
||||
|
||||
unsigned int ChaChaTLS_Policy::GetAlignment() const
|
||||
{
|
||||
return ChaCha_GetAlignment();
|
||||
}
|
||||
|
||||
unsigned int ChaChaTLS_Policy::GetOptimalBlockSize() const
|
||||
{
|
||||
return ChaCha_GetOptimalBlockSize();
|
||||
}
|
||||
|
||||
void ChaChaTLS_Policy::OperateKeystream(KeystreamOperation operation,
|
||||
byte *output, const byte *input, size_t iterationCount)
|
||||
{
|
||||
word32 discard=0;
|
||||
ChaCha_OperateKeystream(operation, m_state, m_state[12], discard,
|
||||
ROUNDS, output, input, iterationCount);
|
||||
|
||||
// If this fires it means ChaCha_OperateKeystream generated a counter
|
||||
// block carry that was discarded. The problem is, the RFC does not
|
||||
// specify what should happen when the counter block wraps. All we can
|
||||
// do is inform the user that something bad may happen because we don't
|
||||
// know what we should do.
|
||||
// Also see https://github.com/weidai11/cryptopp/issues/790 and
|
||||
// https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU
|
||||
// CRYPTOPP_ASSERT(discard==0);
|
||||
}
|
||||
|
||||
////////////////////////////// IETF XChaCha20 //////////////////////////////
|
||||
|
||||
std::string XChaCha20_Policy::AlgorithmName() const
|
||||
{
|
||||
return std::string("XChaCha20");
|
||||
}
|
||||
|
||||
std::string XChaCha20_Policy::AlgorithmProvider() const
|
||||
{
|
||||
return ChaCha_AlgorithmProvider();
|
||||
}
|
||||
|
||||
void XChaCha20_Policy::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length)
|
||||
{
|
||||
CRYPTOPP_ASSERT(key); CRYPTOPP_ASSERT(length == 32);
|
||||
CRYPTOPP_UNUSED(length);
|
||||
|
||||
// Use previous rounds as the default value
|
||||
int rounds = params.GetIntValueWithDefault(Name::Rounds(), m_rounds);
|
||||
if (rounds != 20 && rounds != 12)
|
||||
throw InvalidRounds(ChaCha::StaticAlgorithmName(), rounds);
|
||||
|
||||
// Latch a good value
|
||||
m_rounds = rounds;
|
||||
|
||||
word64 block;
|
||||
if (params.GetValue("InitialBlock", block))
|
||||
m_counter = static_cast<word32>(block);
|
||||
else
|
||||
m_counter = 1;
|
||||
|
||||
// Stash key away for use in CipherResynchronize
|
||||
GetBlock<word32, LittleEndian> get(key);
|
||||
get(m_state[KEY+0])(m_state[KEY+1])(m_state[KEY+2])(m_state[KEY+3])
|
||||
(m_state[KEY+4])(m_state[KEY+5])(m_state[KEY+6])(m_state[KEY+7]);
|
||||
}
|
||||
|
||||
void XChaCha20_Policy::CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length)
|
||||
{
|
||||
CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(length);
|
||||
CRYPTOPP_ASSERT(length==24);
|
||||
|
||||
// HChaCha derivation
|
||||
m_state[0] = 0x61707865; m_state[1] = 0x3320646e;
|
||||
m_state[2] = 0x79622d32; m_state[3] = 0x6b206574;
|
||||
|
||||
// Copy saved key into state
|
||||
std::memcpy(m_state+4, m_state+KEY, 8*sizeof(word32));
|
||||
|
||||
GetBlock<word32, LittleEndian> get(iv);
|
||||
get(m_state[12])(m_state[13])(m_state[14])(m_state[15]);
|
||||
|
||||
// Operate the keystream without adding state back in.
|
||||
// This function also gathers the key words into a
|
||||
// contiguous 8-word block.
|
||||
HChaCha_OperateKeystream(m_state, m_state+4);
|
||||
|
||||
// XChaCha state
|
||||
m_state[0] = 0x61707865; m_state[1] = 0x3320646e;
|
||||
m_state[2] = 0x79622d32; m_state[3] = 0x6b206574;
|
||||
|
||||
// Setup new IV
|
||||
m_state[12] = m_counter;
|
||||
m_state[13] = 0;
|
||||
m_state[14] = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, iv+16);
|
||||
m_state[15] = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, iv+20);
|
||||
}
|
||||
|
||||
void XChaCha20_Policy::SeekToIteration(lword iterationCount)
|
||||
{
|
||||
// Should we throw here??? XChaCha does not have a block
|
||||
// counter, so I'm not sure how to seek on it.
|
||||
CRYPTOPP_ASSERT(0); CRYPTOPP_UNUSED(iterationCount);
|
||||
}
|
||||
|
||||
unsigned int XChaCha20_Policy::GetAlignment() const
|
||||
{
|
||||
return ChaCha_GetAlignment();
|
||||
}
|
||||
|
||||
unsigned int XChaCha20_Policy::GetOptimalBlockSize() const
|
||||
{
|
||||
return ChaCha_GetOptimalBlockSize();
|
||||
}
|
||||
|
||||
void XChaCha20_Policy::OperateKeystream(KeystreamOperation operation,
|
||||
byte *output, const byte *input, size_t iterationCount)
|
||||
{
|
||||
ChaCha_OperateKeystream(operation, m_state, m_state[12], m_state[13],
|
||||
m_rounds, output, input, iterationCount);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
// chacha.h - written and placed in the public domain by Jeffrey Walton.
|
||||
// Based on Wei Dai's Salsa20, Botan's SSE2 implementation,
|
||||
// and Bernstein's reference ChaCha family implementation at
|
||||
// http://cr.yp.to/chacha.html.
|
||||
|
||||
// The library added Bernstein's ChaCha classses at Crypto++ 5.6.4. The IETF
|
||||
// uses a slightly different implementation than Bernstein, and the IETF
|
||||
// ChaCha and XChaCha classes were added at Crypto++ 8.1. We wanted to maintain
|
||||
// ABI compatibility at the 8.1 release so the original ChaCha classes were not
|
||||
// disturbed. Instead new classes were added for IETF ChaCha. The back-end
|
||||
// implementation shares code as expected, however.
|
||||
|
||||
/// \file chacha.h
|
||||
/// \brief Classes for ChaCha8, ChaCha12 and ChaCha20 stream ciphers
|
||||
/// \details Crypto++ provides Bernstein and ECRYPT's ChaCha from <a
|
||||
/// href="http://cr.yp.to/chacha/chacha-20080128.pdf">ChaCha, a
|
||||
/// variant of Salsa20</a> (2008.01.28). Crypto++ also provides the
|
||||
/// IETF implementation of ChaCha using the ChaChaTLS name. Bernstein's
|
||||
/// implementation is _slightly_ different from the TLS working group's
|
||||
/// implementation for cipher suites
|
||||
/// <tt>TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>,
|
||||
/// <tt>TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256</tt>,
|
||||
/// and <tt>TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>. Finally,
|
||||
/// the library provides <a
|
||||
/// href="https://tools.ietf.org/html/draft-arciszewski-xchacha">XChaCha:
|
||||
/// eXtended-nonce ChaCha and AEAD_XChaCha20_Poly1305 (rev. 03)</a>.
|
||||
/// \since ChaCha since Crypto++ 5.6.4, ChaChaTLS and XChaCha20 since Crypto++ 8.1
|
||||
|
||||
#ifndef CRYPTOPP_CHACHA_H
|
||||
#define CRYPTOPP_CHACHA_H
|
||||
|
||||
#include "strciphr.h"
|
||||
#include "secblock.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
////////////////////////////// Bernstein ChaCha //////////////////////////////
|
||||
|
||||
/// \brief ChaCha stream cipher information
|
||||
/// \since Crypto++ 5.6.4
|
||||
struct ChaCha_Info : public VariableKeyLength<32, 16, 32, 16, SimpleKeyingInterface::UNIQUE_IV, 8>
|
||||
{
|
||||
/// \brief The algorithm name
|
||||
/// \return the algorithm name
|
||||
/// \details StaticAlgorithmName returns the algorithm's name as a static
|
||||
/// member function.
|
||||
/// \details Bernstein named the cipher variants ChaCha8, ChaCha12 and
|
||||
/// ChaCha20. More generally, Bernstein called the family ChaCha{r}.
|
||||
/// AlgorithmName() provides the exact name once rounds are set.
|
||||
static const char* StaticAlgorithmName() {
|
||||
return "ChaCha";
|
||||
}
|
||||
};
|
||||
|
||||
/// \brief ChaCha stream cipher implementation
|
||||
/// \since Crypto++ 5.6.4
|
||||
class CRYPTOPP_NO_VTABLE ChaCha_Policy : public AdditiveCipherConcretePolicy<word32, 16>
|
||||
{
|
||||
public:
|
||||
virtual ~ChaCha_Policy() {}
|
||||
ChaCha_Policy() : m_rounds(ROUNDS) {}
|
||||
|
||||
protected:
|
||||
void CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length);
|
||||
void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount);
|
||||
void CipherResynchronize(byte *keystreamBuffer, const byte *IV, size_t length);
|
||||
bool CipherIsRandomAccess() const {return true;}
|
||||
void SeekToIteration(lword iterationCount);
|
||||
unsigned int GetAlignment() const;
|
||||
unsigned int GetOptimalBlockSize() const;
|
||||
|
||||
std::string AlgorithmName() const;
|
||||
std::string AlgorithmProvider() const;
|
||||
|
||||
CRYPTOPP_CONSTANT(ROUNDS = 20); // Default rounds
|
||||
FixedSizeAlignedSecBlock<word32, 16> m_state;
|
||||
unsigned int m_rounds;
|
||||
};
|
||||
|
||||
/// \brief ChaCha stream cipher
|
||||
/// \details This is Bernstein and ECRYPT's ChaCha. It is _slightly_ different
|
||||
/// from the IETF's version of ChaCha called ChaChaTLS.
|
||||
/// \sa <a href="http://cr.yp.to/chacha/chacha-20080208.pdf">ChaCha, a variant
|
||||
/// of Salsa20</a> (2008.01.28).
|
||||
/// \since Crypto++ 5.6.4
|
||||
struct ChaCha : public ChaCha_Info, public SymmetricCipherDocumentation
|
||||
{
|
||||
/// \brief ChaCha Encryption
|
||||
typedef SymmetricCipherFinal<ConcretePolicyHolder<ChaCha_Policy, AdditiveCipherTemplate<> >, ChaCha_Info > Encryption;
|
||||
/// \brief ChaCha Decryption
|
||||
typedef Encryption Decryption;
|
||||
};
|
||||
|
||||
////////////////////////////// IETF ChaChaTLS //////////////////////////////
|
||||
|
||||
/// \brief IETF ChaCha20 stream cipher information
|
||||
/// \since Crypto++ 8.1
|
||||
struct ChaChaTLS_Info : public FixedKeyLength<32, SimpleKeyingInterface::UNIQUE_IV, 12>, FixedRounds<20>
|
||||
{
|
||||
/// \brief The algorithm name
|
||||
/// \return the algorithm name
|
||||
/// \details StaticAlgorithmName returns the algorithm's name as a static
|
||||
/// member function.
|
||||
/// \details This is the IETF's variant of Bernstein's ChaCha from RFC
|
||||
/// 8439. IETF ChaCha is called ChaChaTLS in the Crypto++ library. It
|
||||
/// is _slightly_ different from Bernstein's implementation.
|
||||
static const char* StaticAlgorithmName() {
|
||||
return "ChaChaTLS";
|
||||
}
|
||||
};
|
||||
|
||||
/// \brief IETF ChaCha20 stream cipher implementation
|
||||
/// \since Crypto++ 8.1
|
||||
class CRYPTOPP_NO_VTABLE ChaChaTLS_Policy : public AdditiveCipherConcretePolicy<word32, 16>
|
||||
{
|
||||
public:
|
||||
virtual ~ChaChaTLS_Policy() {}
|
||||
ChaChaTLS_Policy() : m_counter(0) {}
|
||||
|
||||
protected:
|
||||
void CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length);
|
||||
void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount);
|
||||
void CipherResynchronize(byte *keystreamBuffer, const byte *IV, size_t length);
|
||||
bool CipherIsRandomAccess() const {return true;}
|
||||
void SeekToIteration(lword iterationCount);
|
||||
unsigned int GetAlignment() const;
|
||||
unsigned int GetOptimalBlockSize() const;
|
||||
|
||||
std::string AlgorithmName() const;
|
||||
std::string AlgorithmProvider() const;
|
||||
|
||||
FixedSizeAlignedSecBlock<word32, 16+8> m_state;
|
||||
unsigned int m_counter;
|
||||
CRYPTOPP_CONSTANT(ROUNDS = ChaChaTLS_Info::ROUNDS);
|
||||
CRYPTOPP_CONSTANT(KEY = 16); // Index into m_state
|
||||
CRYPTOPP_CONSTANT(CTR = 24); // Index into m_state
|
||||
};
|
||||
|
||||
/// \brief IETF ChaCha20 stream cipher
|
||||
/// \details This is the IETF's variant of Bernstein's ChaCha from RFC 8439.
|
||||
/// IETF ChaCha is called ChaChaTLS in the Crypto++ library. It is
|
||||
/// _slightly_ different from the Bernstein implementation. ChaCha-TLS
|
||||
/// can be used for cipher suites
|
||||
/// <tt>TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>,
|
||||
/// <tt>TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256</tt>, and
|
||||
/// <tt>TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>.
|
||||
/// \sa <a href="https://tools.ietf.org/html/rfc8439">RFC 8439, ChaCha20 and
|
||||
/// Poly1305 for IETF Protocols</a>, <A
|
||||
/// HREF="https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU">How
|
||||
/// to handle block counter wrap in IETF's ChaCha algorithm?</A> and
|
||||
/// <A HREF="https://github.com/weidai11/cryptopp/issues/790">Issue
|
||||
/// 790, ChaChaTLS results when counter block wraps</A>.
|
||||
/// \since Crypto++ 8.1
|
||||
struct ChaChaTLS : public ChaChaTLS_Info, public SymmetricCipherDocumentation
|
||||
{
|
||||
/// \brief ChaCha-TLS Encryption
|
||||
typedef SymmetricCipherFinal<ConcretePolicyHolder<ChaChaTLS_Policy, AdditiveCipherTemplate<> >, ChaChaTLS_Info > Encryption;
|
||||
/// \brief ChaCha-TLS Decryption
|
||||
typedef Encryption Decryption;
|
||||
};
|
||||
|
||||
////////////////////////////// IETF XChaCha20 draft //////////////////////////////
|
||||
|
||||
/// \brief IETF XChaCha20 stream cipher information
|
||||
/// \since Crypto++ 8.1
|
||||
struct XChaCha20_Info : public FixedKeyLength<32, SimpleKeyingInterface::UNIQUE_IV, 24>
|
||||
{
|
||||
/// \brief The algorithm name
|
||||
/// \return the algorithm name
|
||||
/// \details StaticAlgorithmName returns the algorithm's name as a static
|
||||
/// member function.
|
||||
/// \details This is the IETF's XChaCha from draft-arciszewski-xchacha.
|
||||
static const char* StaticAlgorithmName() {
|
||||
return "XChaCha20";
|
||||
}
|
||||
};
|
||||
|
||||
/// \brief IETF XChaCha20 stream cipher implementation
|
||||
/// \since Crypto++ 8.1
|
||||
class CRYPTOPP_NO_VTABLE XChaCha20_Policy : public AdditiveCipherConcretePolicy<word32, 16>
|
||||
{
|
||||
public:
|
||||
virtual ~XChaCha20_Policy() {}
|
||||
XChaCha20_Policy() : m_counter(0), m_rounds(ROUNDS) {}
|
||||
|
||||
protected:
|
||||
void CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length);
|
||||
void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount);
|
||||
void CipherResynchronize(byte *keystreamBuffer, const byte *IV, size_t length);
|
||||
bool CipherIsRandomAccess() const {return false;}
|
||||
void SeekToIteration(lword iterationCount);
|
||||
unsigned int GetAlignment() const;
|
||||
unsigned int GetOptimalBlockSize() const;
|
||||
|
||||
std::string AlgorithmName() const;
|
||||
std::string AlgorithmProvider() const;
|
||||
|
||||
FixedSizeAlignedSecBlock<word32, 16+8> m_state;
|
||||
unsigned int m_counter, m_rounds;
|
||||
CRYPTOPP_CONSTANT(ROUNDS = 20); // Default rounds
|
||||
CRYPTOPP_CONSTANT(KEY = 16); // Index into m_state
|
||||
};
|
||||
|
||||
/// \brief IETF XChaCha20 stream cipher
|
||||
/// \details This is the IETF's XChaCha from draft-arciszewski-xchacha.
|
||||
/// \sa <a href="https://tools.ietf.org/html/draft-arciszewski-xchacha">XChaCha:
|
||||
/// eXtended-nonce ChaCha and AEAD_XChaCha20_Poly1305 (rev. 03)</a>, <A
|
||||
/// HREF="https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU">How
|
||||
/// to handle block counter wrap in IETF's ChaCha algorithm?</A> and
|
||||
/// <A HREF="https://github.com/weidai11/cryptopp/issues/790">Issue
|
||||
/// 790, ChaCha20 results when counter block wraps</A>.
|
||||
/// \since Crypto++ 8.1
|
||||
struct XChaCha20 : public XChaCha20_Info, public SymmetricCipherDocumentation
|
||||
{
|
||||
/// \brief XChaCha Encryption
|
||||
typedef SymmetricCipherFinal<ConcretePolicyHolder<XChaCha20_Policy, AdditiveCipherTemplate<> >, XChaCha20_Info > Encryption;
|
||||
/// \brief XChaCha Decryption
|
||||
typedef Encryption Decryption;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif // CRYPTOPP_CHACHA_H
|
||||
+421
@@ -0,0 +1,421 @@
|
||||
// chacha_avx.cpp - written and placed in the public domain by
|
||||
// Jack Lloyd and Jeffrey Walton
|
||||
//
|
||||
// This source file uses intrinsics and built-ins to gain access to
|
||||
// AVX2 instructions. A separate source file is needed because
|
||||
// additional CXXFLAGS are required to enable the appropriate
|
||||
// instructions sets in some build configurations.
|
||||
//
|
||||
// AVX2 implementation based on Botan's chacha_avx.cpp. Many thanks
|
||||
// to Jack Lloyd and the Botan team for allowing us to use it.
|
||||
//
|
||||
// Here are some relative numbers for ChaCha8:
|
||||
// * Intel Skylake, 3.0 GHz: AVX2 at 4411 MB/s; 0.57 cpb.
|
||||
// * Intel Broadwell, 2.3 GHz: AVX2 at 3828 MB/s; 0.58 cpb.
|
||||
// * AMD Bulldozer, 3.3 GHz: AVX2 at 1680 MB/s; 1.47 cpb.
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
|
||||
#include "chacha.h"
|
||||
#include "misc.h"
|
||||
|
||||
#if defined(CRYPTOPP_AVX2_AVAILABLE)
|
||||
# include <xmmintrin.h>
|
||||
# include <emmintrin.h>
|
||||
# include <immintrin.h>
|
||||
#endif
|
||||
|
||||
// Squash MS LNK4221 and libtool warnings
|
||||
extern const char CHACHA_AVX_FNAME[] = __FILE__;
|
||||
|
||||
// Sun Studio 12.4 OK, 12.5 and 12.6 compile error.
|
||||
#if (__SUNPRO_CC >= 0x5140) && (__SUNPRO_CC <= 0x5150)
|
||||
# define MAYBE_CONST
|
||||
#else
|
||||
# define MAYBE_CONST const
|
||||
#endif
|
||||
|
||||
// VS2017 and global optimization bug. TODO, figure out when
|
||||
// we can re-enable full optimizations for VS2017. Also see
|
||||
// https://github.com/weidai11/cryptopp/issues/649 and
|
||||
// https://github.com/weidai11/cryptopp/issues/735. The
|
||||
// 649 issue affects AES but it is the same here. The 735
|
||||
// issue is ChaCha AVX2 cut-in where it surfaced again.
|
||||
#if (_MSC_VER >= 1910)
|
||||
# ifndef CRYPTOPP_DEBUG
|
||||
# pragma optimize("", off)
|
||||
# pragma optimize("ts", on)
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// The data is aligned, but Clang issues warning based on type
|
||||
// and not the actual alignment of the variable and data.
|
||||
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
|
||||
# pragma GCC diagnostic ignored "-Wcast-align"
|
||||
#endif
|
||||
|
||||
ANONYMOUS_NAMESPACE_BEGIN
|
||||
|
||||
#if (CRYPTOPP_AVX2_AVAILABLE)
|
||||
|
||||
template <unsigned int R>
|
||||
inline __m256i RotateLeft(const __m256i val)
|
||||
{
|
||||
return _mm256_or_si256(_mm256_slli_epi32(val, R), _mm256_srli_epi32(val, 32-R));
|
||||
}
|
||||
|
||||
template <>
|
||||
inline __m256i RotateLeft<8>(const __m256i val)
|
||||
{
|
||||
const __m256i mask = _mm256_set_epi8(14,13,12,15, 10,9,8,11, 6,5,4,7, 2,1,0,3,
|
||||
14,13,12,15, 10,9,8,11, 6,5,4,7, 2,1,0,3);
|
||||
return _mm256_shuffle_epi8(val, mask);
|
||||
}
|
||||
|
||||
template <>
|
||||
inline __m256i RotateLeft<16>(const __m256i val)
|
||||
{
|
||||
const __m256i mask = _mm256_set_epi8(13,12,15,14, 9,8,11,10, 5,4,7,6, 1,0,3,2,
|
||||
13,12,15,14, 9,8,11,10, 5,4,7,6, 1,0,3,2);
|
||||
return _mm256_shuffle_epi8(val, mask);
|
||||
}
|
||||
|
||||
#endif // CRYPTOPP_AVX2_AVAILABLE
|
||||
|
||||
ANONYMOUS_NAMESPACE_END
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
#if (CRYPTOPP_AVX2_AVAILABLE)
|
||||
|
||||
void ChaCha_OperateKeystream_AVX2(const word32 *state, const byte* input, byte *output, unsigned int rounds)
|
||||
{
|
||||
const __m256i state0 = _mm256_broadcastsi128_si256(
|
||||
_mm_loadu_si128(reinterpret_cast<const __m128i*>(state+0*4)));
|
||||
const __m256i state1 = _mm256_broadcastsi128_si256(
|
||||
_mm_loadu_si128(reinterpret_cast<const __m128i*>(state+1*4)));
|
||||
const __m256i state2 = _mm256_broadcastsi128_si256(
|
||||
_mm_loadu_si128(reinterpret_cast<const __m128i*>(state+2*4)));
|
||||
const __m256i state3 = _mm256_broadcastsi128_si256(
|
||||
_mm_loadu_si128(reinterpret_cast<const __m128i*>(state+3*4)));
|
||||
|
||||
const __m256i CTR0 = _mm256_set_epi32(0, 0, 0, 0, 0, 0, 0, 4);
|
||||
const __m256i CTR1 = _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 5);
|
||||
const __m256i CTR2 = _mm256_set_epi32(0, 0, 0, 2, 0, 0, 0, 6);
|
||||
const __m256i CTR3 = _mm256_set_epi32(0, 0, 0, 3, 0, 0, 0, 7);
|
||||
|
||||
__m256i X0_0 = state0;
|
||||
__m256i X0_1 = state1;
|
||||
__m256i X0_2 = state2;
|
||||
__m256i X0_3 = _mm256_add_epi64(state3, CTR0);
|
||||
|
||||
__m256i X1_0 = state0;
|
||||
__m256i X1_1 = state1;
|
||||
__m256i X1_2 = state2;
|
||||
__m256i X1_3 = _mm256_add_epi64(state3, CTR1);
|
||||
|
||||
__m256i X2_0 = state0;
|
||||
__m256i X2_1 = state1;
|
||||
__m256i X2_2 = state2;
|
||||
__m256i X2_3 = _mm256_add_epi64(state3, CTR2);
|
||||
|
||||
__m256i X3_0 = state0;
|
||||
__m256i X3_1 = state1;
|
||||
__m256i X3_2 = state2;
|
||||
__m256i X3_3 = _mm256_add_epi64(state3, CTR3);
|
||||
|
||||
for (int i = static_cast<int>(rounds); i > 0; i -= 2)
|
||||
{
|
||||
X0_0 = _mm256_add_epi32(X0_0, X0_1);
|
||||
X1_0 = _mm256_add_epi32(X1_0, X1_1);
|
||||
X2_0 = _mm256_add_epi32(X2_0, X2_1);
|
||||
X3_0 = _mm256_add_epi32(X3_0, X3_1);
|
||||
|
||||
X0_3 = _mm256_xor_si256(X0_3, X0_0);
|
||||
X1_3 = _mm256_xor_si256(X1_3, X1_0);
|
||||
X2_3 = _mm256_xor_si256(X2_3, X2_0);
|
||||
X3_3 = _mm256_xor_si256(X3_3, X3_0);
|
||||
|
||||
X0_3 = RotateLeft<16>(X0_3);
|
||||
X1_3 = RotateLeft<16>(X1_3);
|
||||
X2_3 = RotateLeft<16>(X2_3);
|
||||
X3_3 = RotateLeft<16>(X3_3);
|
||||
|
||||
X0_2 = _mm256_add_epi32(X0_2, X0_3);
|
||||
X1_2 = _mm256_add_epi32(X1_2, X1_3);
|
||||
X2_2 = _mm256_add_epi32(X2_2, X2_3);
|
||||
X3_2 = _mm256_add_epi32(X3_2, X3_3);
|
||||
|
||||
X0_1 = _mm256_xor_si256(X0_1, X0_2);
|
||||
X1_1 = _mm256_xor_si256(X1_1, X1_2);
|
||||
X2_1 = _mm256_xor_si256(X2_1, X2_2);
|
||||
X3_1 = _mm256_xor_si256(X3_1, X3_2);
|
||||
|
||||
X0_1 = RotateLeft<12>(X0_1);
|
||||
X1_1 = RotateLeft<12>(X1_1);
|
||||
X2_1 = RotateLeft<12>(X2_1);
|
||||
X3_1 = RotateLeft<12>(X3_1);
|
||||
|
||||
X0_0 = _mm256_add_epi32(X0_0, X0_1);
|
||||
X1_0 = _mm256_add_epi32(X1_0, X1_1);
|
||||
X2_0 = _mm256_add_epi32(X2_0, X2_1);
|
||||
X3_0 = _mm256_add_epi32(X3_0, X3_1);
|
||||
|
||||
X0_3 = _mm256_xor_si256(X0_3, X0_0);
|
||||
X1_3 = _mm256_xor_si256(X1_3, X1_0);
|
||||
X2_3 = _mm256_xor_si256(X2_3, X2_0);
|
||||
X3_3 = _mm256_xor_si256(X3_3, X3_0);
|
||||
|
||||
X0_3 = RotateLeft<8>(X0_3);
|
||||
X1_3 = RotateLeft<8>(X1_3);
|
||||
X2_3 = RotateLeft<8>(X2_3);
|
||||
X3_3 = RotateLeft<8>(X3_3);
|
||||
|
||||
X0_2 = _mm256_add_epi32(X0_2, X0_3);
|
||||
X1_2 = _mm256_add_epi32(X1_2, X1_3);
|
||||
X2_2 = _mm256_add_epi32(X2_2, X2_3);
|
||||
X3_2 = _mm256_add_epi32(X3_2, X3_3);
|
||||
|
||||
X0_1 = _mm256_xor_si256(X0_1, X0_2);
|
||||
X1_1 = _mm256_xor_si256(X1_1, X1_2);
|
||||
X2_1 = _mm256_xor_si256(X2_1, X2_2);
|
||||
X3_1 = _mm256_xor_si256(X3_1, X3_2);
|
||||
|
||||
X0_1 = RotateLeft<7>(X0_1);
|
||||
X1_1 = RotateLeft<7>(X1_1);
|
||||
X2_1 = RotateLeft<7>(X2_1);
|
||||
X3_1 = RotateLeft<7>(X3_1);
|
||||
|
||||
X0_1 = _mm256_shuffle_epi32(X0_1, _MM_SHUFFLE(0, 3, 2, 1));
|
||||
X0_2 = _mm256_shuffle_epi32(X0_2, _MM_SHUFFLE(1, 0, 3, 2));
|
||||
X0_3 = _mm256_shuffle_epi32(X0_3, _MM_SHUFFLE(2, 1, 0, 3));
|
||||
|
||||
X1_1 = _mm256_shuffle_epi32(X1_1, _MM_SHUFFLE(0, 3, 2, 1));
|
||||
X1_2 = _mm256_shuffle_epi32(X1_2, _MM_SHUFFLE(1, 0, 3, 2));
|
||||
X1_3 = _mm256_shuffle_epi32(X1_3, _MM_SHUFFLE(2, 1, 0, 3));
|
||||
|
||||
X2_1 = _mm256_shuffle_epi32(X2_1, _MM_SHUFFLE(0, 3, 2, 1));
|
||||
X2_2 = _mm256_shuffle_epi32(X2_2, _MM_SHUFFLE(1, 0, 3, 2));
|
||||
X2_3 = _mm256_shuffle_epi32(X2_3, _MM_SHUFFLE(2, 1, 0, 3));
|
||||
|
||||
X3_1 = _mm256_shuffle_epi32(X3_1, _MM_SHUFFLE(0, 3, 2, 1));
|
||||
X3_2 = _mm256_shuffle_epi32(X3_2, _MM_SHUFFLE(1, 0, 3, 2));
|
||||
X3_3 = _mm256_shuffle_epi32(X3_3, _MM_SHUFFLE(2, 1, 0, 3));
|
||||
|
||||
X0_0 = _mm256_add_epi32(X0_0, X0_1);
|
||||
X1_0 = _mm256_add_epi32(X1_0, X1_1);
|
||||
X2_0 = _mm256_add_epi32(X2_0, X2_1);
|
||||
X3_0 = _mm256_add_epi32(X3_0, X3_1);
|
||||
|
||||
X0_3 = _mm256_xor_si256(X0_3, X0_0);
|
||||
X1_3 = _mm256_xor_si256(X1_3, X1_0);
|
||||
X2_3 = _mm256_xor_si256(X2_3, X2_0);
|
||||
X3_3 = _mm256_xor_si256(X3_3, X3_0);
|
||||
|
||||
X0_3 = RotateLeft<16>(X0_3);
|
||||
X1_3 = RotateLeft<16>(X1_3);
|
||||
X2_3 = RotateLeft<16>(X2_3);
|
||||
X3_3 = RotateLeft<16>(X3_3);
|
||||
|
||||
X0_2 = _mm256_add_epi32(X0_2, X0_3);
|
||||
X1_2 = _mm256_add_epi32(X1_2, X1_3);
|
||||
X2_2 = _mm256_add_epi32(X2_2, X2_3);
|
||||
X3_2 = _mm256_add_epi32(X3_2, X3_3);
|
||||
|
||||
X0_1 = _mm256_xor_si256(X0_1, X0_2);
|
||||
X1_1 = _mm256_xor_si256(X1_1, X1_2);
|
||||
X2_1 = _mm256_xor_si256(X2_1, X2_2);
|
||||
X3_1 = _mm256_xor_si256(X3_1, X3_2);
|
||||
|
||||
X0_1 = RotateLeft<12>(X0_1);
|
||||
X1_1 = RotateLeft<12>(X1_1);
|
||||
X2_1 = RotateLeft<12>(X2_1);
|
||||
X3_1 = RotateLeft<12>(X3_1);
|
||||
|
||||
X0_0 = _mm256_add_epi32(X0_0, X0_1);
|
||||
X1_0 = _mm256_add_epi32(X1_0, X1_1);
|
||||
X2_0 = _mm256_add_epi32(X2_0, X2_1);
|
||||
X3_0 = _mm256_add_epi32(X3_0, X3_1);
|
||||
|
||||
X0_3 = _mm256_xor_si256(X0_3, X0_0);
|
||||
X1_3 = _mm256_xor_si256(X1_3, X1_0);
|
||||
X2_3 = _mm256_xor_si256(X2_3, X2_0);
|
||||
X3_3 = _mm256_xor_si256(X3_3, X3_0);
|
||||
|
||||
X0_3 = RotateLeft<8>(X0_3);
|
||||
X1_3 = RotateLeft<8>(X1_3);
|
||||
X2_3 = RotateLeft<8>(X2_3);
|
||||
X3_3 = RotateLeft<8>(X3_3);
|
||||
|
||||
X0_2 = _mm256_add_epi32(X0_2, X0_3);
|
||||
X1_2 = _mm256_add_epi32(X1_2, X1_3);
|
||||
X2_2 = _mm256_add_epi32(X2_2, X2_3);
|
||||
X3_2 = _mm256_add_epi32(X3_2, X3_3);
|
||||
|
||||
X0_1 = _mm256_xor_si256(X0_1, X0_2);
|
||||
X1_1 = _mm256_xor_si256(X1_1, X1_2);
|
||||
X2_1 = _mm256_xor_si256(X2_1, X2_2);
|
||||
X3_1 = _mm256_xor_si256(X3_1, X3_2);
|
||||
|
||||
X0_1 = RotateLeft<7>(X0_1);
|
||||
X1_1 = RotateLeft<7>(X1_1);
|
||||
X2_1 = RotateLeft<7>(X2_1);
|
||||
X3_1 = RotateLeft<7>(X3_1);
|
||||
|
||||
X0_1 = _mm256_shuffle_epi32(X0_1, _MM_SHUFFLE(2, 1, 0, 3));
|
||||
X0_2 = _mm256_shuffle_epi32(X0_2, _MM_SHUFFLE(1, 0, 3, 2));
|
||||
X0_3 = _mm256_shuffle_epi32(X0_3, _MM_SHUFFLE(0, 3, 2, 1));
|
||||
|
||||
X1_1 = _mm256_shuffle_epi32(X1_1, _MM_SHUFFLE(2, 1, 0, 3));
|
||||
X1_2 = _mm256_shuffle_epi32(X1_2, _MM_SHUFFLE(1, 0, 3, 2));
|
||||
X1_3 = _mm256_shuffle_epi32(X1_3, _MM_SHUFFLE(0, 3, 2, 1));
|
||||
|
||||
X2_1 = _mm256_shuffle_epi32(X2_1, _MM_SHUFFLE(2, 1, 0, 3));
|
||||
X2_2 = _mm256_shuffle_epi32(X2_2, _MM_SHUFFLE(1, 0, 3, 2));
|
||||
X2_3 = _mm256_shuffle_epi32(X2_3, _MM_SHUFFLE(0, 3, 2, 1));
|
||||
|
||||
X3_1 = _mm256_shuffle_epi32(X3_1, _MM_SHUFFLE(2, 1, 0, 3));
|
||||
X3_2 = _mm256_shuffle_epi32(X3_2, _MM_SHUFFLE(1, 0, 3, 2));
|
||||
X3_3 = _mm256_shuffle_epi32(X3_3, _MM_SHUFFLE(0, 3, 2, 1));
|
||||
}
|
||||
|
||||
X0_0 = _mm256_add_epi32(X0_0, state0);
|
||||
X0_1 = _mm256_add_epi32(X0_1, state1);
|
||||
X0_2 = _mm256_add_epi32(X0_2, state2);
|
||||
X0_3 = _mm256_add_epi32(X0_3, state3);
|
||||
X0_3 = _mm256_add_epi64(X0_3, CTR0);
|
||||
|
||||
X1_0 = _mm256_add_epi32(X1_0, state0);
|
||||
X1_1 = _mm256_add_epi32(X1_1, state1);
|
||||
X1_2 = _mm256_add_epi32(X1_2, state2);
|
||||
X1_3 = _mm256_add_epi32(X1_3, state3);
|
||||
X1_3 = _mm256_add_epi64(X1_3, CTR1);
|
||||
|
||||
X2_0 = _mm256_add_epi32(X2_0, state0);
|
||||
X2_1 = _mm256_add_epi32(X2_1, state1);
|
||||
X2_2 = _mm256_add_epi32(X2_2, state2);
|
||||
X2_3 = _mm256_add_epi32(X2_3, state3);
|
||||
X2_3 = _mm256_add_epi64(X2_3, CTR2);
|
||||
|
||||
X3_0 = _mm256_add_epi32(X3_0, state0);
|
||||
X3_1 = _mm256_add_epi32(X3_1, state1);
|
||||
X3_2 = _mm256_add_epi32(X3_2, state2);
|
||||
X3_3 = _mm256_add_epi32(X3_3, state3);
|
||||
X3_3 = _mm256_add_epi64(X3_3, CTR3);
|
||||
|
||||
if (input)
|
||||
{
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+0*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X0_0, X0_1, 1 + (3 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+0*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+1*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X0_2, X0_3, 1 + (3 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+1*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+2*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X1_0, X1_1, 1 + (3 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+2*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+3*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X1_2, X1_3, 1 + (3 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+3*32)))));
|
||||
}
|
||||
else
|
||||
{
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+0*32),
|
||||
_mm256_permute2x128_si256(X0_0, X0_1, 1 + (3 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+1*32),
|
||||
_mm256_permute2x128_si256(X0_2, X0_3, 1 + (3 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+2*32),
|
||||
_mm256_permute2x128_si256(X1_0, X1_1, 1 + (3 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+3*32),
|
||||
_mm256_permute2x128_si256(X1_2, X1_3, 1 + (3 << 4)));
|
||||
}
|
||||
|
||||
if (input)
|
||||
{
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+4*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X2_0, X2_1, 1 + (3 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+4*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+5*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X2_2, X2_3, 1 + (3 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+5*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+6*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X3_0, X3_1, 1 + (3 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+6*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+7*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X3_2, X3_3, 1 + (3 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+7*32)))));
|
||||
}
|
||||
else
|
||||
{
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+4*32),
|
||||
_mm256_permute2x128_si256(X2_0, X2_1, 1 + (3 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+5*32),
|
||||
_mm256_permute2x128_si256(X2_2, X2_3, 1 + (3 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+6*32),
|
||||
_mm256_permute2x128_si256(X3_0, X3_1, 1 + (3 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+7*32),
|
||||
_mm256_permute2x128_si256(X3_2, X3_3, 1 + (3 << 4)));
|
||||
}
|
||||
|
||||
if (input)
|
||||
{
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+ 8*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X0_0, X0_1, 0 + (2 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+8*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+ 9*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X0_2, X0_3, 0 + (2 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+9*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+10*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X1_0, X1_1, 0 + (2 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+10*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+11*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X1_2, X1_3, 0 + (2 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+11*32)))));
|
||||
}
|
||||
else
|
||||
{
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+ 8*32),
|
||||
_mm256_permute2x128_si256(X0_0, X0_1, 0 + (2 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+ 9*32),
|
||||
_mm256_permute2x128_si256(X0_2, X0_3, 0 + (2 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+10*32),
|
||||
_mm256_permute2x128_si256(X1_0, X1_1, 0 + (2 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+11*32),
|
||||
_mm256_permute2x128_si256(X1_2, X1_3, 0 + (2 << 4)));
|
||||
}
|
||||
|
||||
if (input)
|
||||
{
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+12*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X2_0, X2_1, 0 + (2 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+12*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+13*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X2_2, X2_3, 0 + (2 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+13*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+14*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X3_0, X3_1, 0 + (2 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+14*32)))));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+15*32),
|
||||
_mm256_xor_si256(_mm256_permute2x128_si256(X3_2, X3_3, 0 + (2 << 4)),
|
||||
_mm256_loadu_si256(const_cast<MAYBE_CONST __m256i*>(reinterpret_cast<const __m256i*>(input+15*32)))));
|
||||
}
|
||||
else
|
||||
{
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+12*32),
|
||||
_mm256_permute2x128_si256(X2_0, X2_1, 0 + (2 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+13*32),
|
||||
_mm256_permute2x128_si256(X2_2, X2_3, 0 + (2 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+14*32),
|
||||
_mm256_permute2x128_si256(X3_0, X3_1, 0 + (2 << 4)));
|
||||
_mm256_storeu_si256(reinterpret_cast<__m256i*>(output+15*32),
|
||||
_mm256_permute2x128_si256(X3_2, X3_3, 0 + (2 << 4)));
|
||||
}
|
||||
|
||||
// https://software.intel.com/en-us/articles/avoiding-avx-sse-transition-penalties
|
||||
_mm256_zeroupper();
|
||||
}
|
||||
|
||||
#endif // CRYPTOPP_AVX2_AVAILABLE
|
||||
|
||||
NAMESPACE_END
|
||||
+1109
File diff suppressed because it is too large
Load Diff
+211
@@ -0,0 +1,211 @@
|
||||
// chachapoly.cpp - written and placed in the public domain by Jeffrey Walton
|
||||
// RFC 8439, Section 2.8, AEAD Construction, http://tools.ietf.org/html/rfc8439
|
||||
|
||||
#include "pch.h"
|
||||
#include "chachapoly.h"
|
||||
#include "algparam.h"
|
||||
#include "misc.h"
|
||||
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(disable: 4244)
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
////////////////////////////// IETF ChaChaTLS //////////////////////////////
|
||||
|
||||
// RekeyCipherAndMac is heavier-weight than we like. The Authenc framework was
|
||||
// predicated on BlockCiphers, where the key and key schedule could be
|
||||
// calculated independent of the IV being used. However, the ChaCha and
|
||||
// ChaCha20Poly1305 construction combines key setup and IV. That is, both are
|
||||
// needed to key or rekey the cipher. Even a simple Resync() requires us to
|
||||
// regenerate the initial state for both ChaCha20 and Poly1305.
|
||||
void ChaCha20Poly1305_Base::RekeyCipherAndMac(const byte *userKey, size_t keylength, const NameValuePairs ¶ms)
|
||||
{
|
||||
// Derive MAC key
|
||||
AlgorithmParameters block0 = MakeParameters("InitialBlock", (word64)0, true);
|
||||
AccessSymmetricCipher().SetKey(userKey, keylength, CombinedNameValuePairs(params, block0));
|
||||
|
||||
// Only the first 256-bits are used to key the MAC
|
||||
SecByteBlock derived(NULLPTR, 32);
|
||||
AccessSymmetricCipher().ProcessString(derived, derived.size());
|
||||
|
||||
// Key the Poly1305 MAC
|
||||
AccessMAC().SetKey(derived, derived.size(), params);
|
||||
|
||||
// Key the ChaCha20 cipher
|
||||
AlgorithmParameters block1 = MakeParameters("InitialBlock", (word64)1, true);
|
||||
AccessSymmetricCipher().SetKey(userKey, keylength, CombinedNameValuePairs(params, block1));
|
||||
}
|
||||
|
||||
void ChaCha20Poly1305_Base::SetKeyWithoutResync(const byte *userKey, size_t userKeyLength, const NameValuePairs ¶ms)
|
||||
{
|
||||
CRYPTOPP_ASSERT(userKey && userKeyLength == 32);
|
||||
m_userKey.Assign(userKey, userKeyLength);
|
||||
|
||||
// ChaCha/Poly1305 initial state depends on both the key and IV. The
|
||||
// IV may or may not be present during the call to SetKeyWithoutResync.
|
||||
// If the IV is present, the framework will call SetKeyWithoutResync
|
||||
// followed by Resynchronize which calls Resync. In this case we defer
|
||||
// calculating the initial state until the call to Resynchronize.
|
||||
// If the IV is not present, it avoids calling ChaCha's SetKey without
|
||||
// an IV, which results in an exception. In this case the user will need
|
||||
// to call Resynchronize to key ChaCha and Poly1305.
|
||||
// RekeyCipherAndMac(userKey, userKeyLength, params);
|
||||
CRYPTOPP_UNUSED(params);
|
||||
}
|
||||
|
||||
void ChaCha20Poly1305_Base::Resync(const byte *iv, size_t len)
|
||||
{
|
||||
CRYPTOPP_ASSERT(iv && len == 12);
|
||||
RekeyCipherAndMac(m_userKey, m_userKey.SizeInBytes(),
|
||||
MakeParameters(Name::IV(), ConstByteArrayParameter(iv,len)));
|
||||
}
|
||||
|
||||
size_t ChaCha20Poly1305_Base::AuthenticateBlocks(const byte *data, size_t len)
|
||||
{
|
||||
AccessMAC().Update(data, len);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ChaCha20Poly1305_Base::AuthenticateLastHeaderBlock()
|
||||
{
|
||||
// Pad to a multiple of 16 or 0
|
||||
const byte zero[16] = {0};
|
||||
size_t pad = (16U - (m_totalHeaderLength % 16)) % 16;
|
||||
AccessMAC().Update(zero, pad);
|
||||
}
|
||||
|
||||
void ChaCha20Poly1305_Base::AuthenticateLastConfidentialBlock()
|
||||
{
|
||||
// Pad to a multiple of 16 or 0
|
||||
const byte zero[16] = {0};
|
||||
size_t pad = (16U - (m_totalMessageLength % 16)) % 16;
|
||||
AccessMAC().Update(zero, pad);
|
||||
}
|
||||
|
||||
void ChaCha20Poly1305_Base::AuthenticateLastFooterBlock(byte *mac, size_t macSize)
|
||||
{
|
||||
CRYPTOPP_ALIGN_DATA(8) byte length[2*sizeof(word64)];
|
||||
PutWord(true, LITTLE_ENDIAN_ORDER, length+0, m_totalHeaderLength);
|
||||
PutWord(true, LITTLE_ENDIAN_ORDER, length+8, m_totalMessageLength);
|
||||
AccessMAC().Update(length, sizeof(length));
|
||||
AccessMAC().TruncatedFinal(mac, macSize);
|
||||
m_state = State_KeySet;
|
||||
}
|
||||
|
||||
void ChaCha20Poly1305_Base::EncryptAndAuthenticate(byte *ciphertext, byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *aad, size_t aadLength, const byte *message, size_t messageLength)
|
||||
{
|
||||
Resynchronize(iv, ivLength);
|
||||
Update(aad, aadLength);
|
||||
ProcessString(ciphertext, message, messageLength);
|
||||
TruncatedFinal(mac, macSize);
|
||||
}
|
||||
|
||||
bool ChaCha20Poly1305_Base::DecryptAndVerify(byte *message, const byte *mac, size_t macLength, const byte *iv, int ivLength, const byte *aad, size_t aadLength, const byte *ciphertext, size_t ciphertextLength)
|
||||
{
|
||||
Resynchronize(iv, ivLength);
|
||||
Update(aad, aadLength);
|
||||
ProcessString(message, ciphertext, ciphertextLength);
|
||||
return TruncatedVerify(mac, macLength);
|
||||
}
|
||||
|
||||
////////////////////////////// IETF XChaCha20 draft //////////////////////////////
|
||||
|
||||
// RekeyCipherAndMac is heavier-weight than we like. The Authenc framework was
|
||||
// predicated on BlockCiphers, where the key and key schedule could be
|
||||
// calculated independent of the IV being used. However, the ChaCha and
|
||||
// ChaCha20Poly1305 construction combines key setup and IV. That is, both are
|
||||
// needed to key or rekey the cipher. Even a simple Resync() requires us to
|
||||
// regenerate the initial state for both ChaCha20 and Poly1305.
|
||||
void XChaCha20Poly1305_Base::RekeyCipherAndMac(const byte *userKey, size_t keylength, const NameValuePairs ¶ms)
|
||||
{
|
||||
// Derive MAC key
|
||||
AlgorithmParameters block0 = MakeParameters("InitialBlock", (word64)0, true);
|
||||
AccessSymmetricCipher().SetKey(userKey, keylength, CombinedNameValuePairs(params, block0));
|
||||
|
||||
// Only the first 256-bits are used to key the MAC
|
||||
SecByteBlock derived(NULLPTR, 32);
|
||||
AccessSymmetricCipher().ProcessString(derived, derived.size());
|
||||
|
||||
// Key the Poly1305 MAC
|
||||
AccessMAC().SetKey(derived, derived.size(), params);
|
||||
|
||||
// Key the ChaCha20 cipher
|
||||
AlgorithmParameters block1 = MakeParameters("InitialBlock", (word64)1, true);
|
||||
AccessSymmetricCipher().SetKey(userKey, keylength, CombinedNameValuePairs(params, block1));
|
||||
}
|
||||
|
||||
void XChaCha20Poly1305_Base::SetKeyWithoutResync(const byte *userKey, size_t userKeyLength, const NameValuePairs ¶ms)
|
||||
{
|
||||
CRYPTOPP_ASSERT(userKey && userKeyLength == 32);
|
||||
m_userKey.Assign(userKey, userKeyLength);
|
||||
|
||||
// XChaCha20/Poly1305 initial state depends on both the key and IV. The
|
||||
// IV may or may not be present during the call to SetKeyWithoutResync.
|
||||
// If the IV is present, the framework will call SetKeyWithoutResync
|
||||
// followed by Resynchronize which calls Resync. In this case we defer
|
||||
// calculating the initial state until the call to Resynchronize.
|
||||
// If the IV is not present, it avoids calling ChaCha's SetKey without
|
||||
// an IV, which results in an exception. In this case the user will need
|
||||
// to call Resynchronize to key ChaCha and Poly1305.
|
||||
// RekeyCipherAndMac(userKey, userKeyLength, params);
|
||||
CRYPTOPP_UNUSED(params);
|
||||
}
|
||||
|
||||
void XChaCha20Poly1305_Base::Resync(const byte *iv, size_t len)
|
||||
{
|
||||
CRYPTOPP_ASSERT(iv && len == 24);
|
||||
RekeyCipherAndMac(m_userKey, m_userKey.SizeInBytes(),
|
||||
MakeParameters(Name::IV(), ConstByteArrayParameter(iv,len)));
|
||||
}
|
||||
|
||||
size_t XChaCha20Poly1305_Base::AuthenticateBlocks(const byte *data, size_t len)
|
||||
{
|
||||
AccessMAC().Update(data, len);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void XChaCha20Poly1305_Base::AuthenticateLastHeaderBlock()
|
||||
{
|
||||
// Pad to a multiple of 16 or 0
|
||||
const byte zero[16] = {0};
|
||||
size_t pad = (16 - (m_totalHeaderLength % 16)) % 16;
|
||||
AccessMAC().Update(zero, pad);
|
||||
}
|
||||
|
||||
void XChaCha20Poly1305_Base::AuthenticateLastConfidentialBlock()
|
||||
{
|
||||
// Pad to a multiple of 16 or 0
|
||||
const byte zero[16] = {0};
|
||||
size_t pad = (16 - (m_totalMessageLength % 16)) % 16;
|
||||
AccessMAC().Update(zero, pad);
|
||||
}
|
||||
|
||||
void XChaCha20Poly1305_Base::AuthenticateLastFooterBlock(byte *mac, size_t macSize)
|
||||
{
|
||||
CRYPTOPP_ALIGN_DATA(8) byte length[2*sizeof(word64)];
|
||||
PutWord(true, LITTLE_ENDIAN_ORDER, length+0, m_totalHeaderLength);
|
||||
PutWord(true, LITTLE_ENDIAN_ORDER, length+8, m_totalMessageLength);
|
||||
AccessMAC().Update(length, sizeof(length));
|
||||
AccessMAC().TruncatedFinal(mac, macSize);
|
||||
m_state = State_KeySet;
|
||||
}
|
||||
|
||||
void XChaCha20Poly1305_Base::EncryptAndAuthenticate(byte *ciphertext, byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *aad, size_t aadLength, const byte *message, size_t messageLength)
|
||||
{
|
||||
Resynchronize(iv, ivLength);
|
||||
Update(aad, aadLength);
|
||||
ProcessString(ciphertext, message, messageLength);
|
||||
TruncatedFinal(mac, macSize);
|
||||
}
|
||||
|
||||
bool XChaCha20Poly1305_Base::DecryptAndVerify(byte *message, const byte *mac, size_t macLength, const byte *iv, int ivLength, const byte *aad, size_t aadLength, const byte *ciphertext, size_t ciphertextLength)
|
||||
{
|
||||
Resynchronize(iv, ivLength);
|
||||
Update(aad, aadLength);
|
||||
ProcessString(message, ciphertext, ciphertextLength);
|
||||
return TruncatedVerify(mac, macLength);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
// chachapoly.h - written and placed in the public domain by Jeffrey Walton
|
||||
// RFC 8439, Section 2.8, AEAD Construction, http://tools.ietf.org/html/rfc8439
|
||||
|
||||
/// \file chachapoly.h
|
||||
/// \brief IETF ChaCha20/Poly1305 AEAD scheme
|
||||
/// \details ChaCha20Poly1305 is an authenticated encryption scheme that combines
|
||||
/// ChaCha20TLS and Poly1305TLS. The scheme is defined in RFC 8439, section 2.8,
|
||||
/// AEAD_CHACHA20_POLY1305 construction, and uses the IETF versions of ChaCha20
|
||||
/// and Poly1305.
|
||||
/// \sa <A HREF="http://tools.ietf.org/html/rfc8439">RFC 8439, ChaCha20 and Poly1305
|
||||
/// for IETF Protocols</A>.
|
||||
/// \since Crypto++ 8.1
|
||||
|
||||
#ifndef CRYPTOPP_CHACHA_POLY1305_H
|
||||
#define CRYPTOPP_CHACHA_POLY1305_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "authenc.h"
|
||||
#include "chacha.h"
|
||||
#include "poly1305.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
////////////////////////////// IETF ChaChaTLS //////////////////////////////
|
||||
|
||||
/// \brief IETF ChaCha20Poly1305 cipher base implementation
|
||||
/// \details Base implementation of the AuthenticatedSymmetricCipher interface
|
||||
/// \since Crypto++ 8.1
|
||||
class ChaCha20Poly1305_Base : public AuthenticatedSymmetricCipherBase
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName()
|
||||
{return "ChaCha20/Poly1305";}
|
||||
|
||||
virtual ~ChaCha20Poly1305_Base() {}
|
||||
|
||||
// AuthenticatedSymmetricCipher
|
||||
std::string AlgorithmName() const
|
||||
{return std::string("ChaCha20/Poly1305");}
|
||||
std::string AlgorithmProvider() const
|
||||
{return GetSymmetricCipher().AlgorithmProvider();}
|
||||
size_t MinKeyLength() const
|
||||
{return 32;}
|
||||
size_t MaxKeyLength() const
|
||||
{return 32;}
|
||||
size_t DefaultKeyLength() const
|
||||
{return 32;}
|
||||
size_t GetValidKeyLength(size_t n) const
|
||||
{CRYPTOPP_UNUSED(n); return 32;}
|
||||
bool IsValidKeyLength(size_t n) const
|
||||
{return n==32;}
|
||||
unsigned int OptimalDataAlignment() const
|
||||
{return GetSymmetricCipher().OptimalDataAlignment();}
|
||||
IV_Requirement IVRequirement() const
|
||||
{return UNIQUE_IV;}
|
||||
unsigned int IVSize() const
|
||||
{return 12;}
|
||||
unsigned int MinIVLength() const
|
||||
{return 12;}
|
||||
unsigned int MaxIVLength() const
|
||||
{return 12;}
|
||||
unsigned int DigestSize() const
|
||||
{return 16;}
|
||||
lword MaxHeaderLength() const
|
||||
{return LWORD_MAX;} // 2^64-1 bytes
|
||||
lword MaxMessageLength() const
|
||||
{return W64LIT(274877906880);} // 2^38-1 blocks
|
||||
lword MaxFooterLength() const
|
||||
{return 0;}
|
||||
|
||||
/// \brief Encrypts and calculates a MAC in one call
|
||||
/// \param ciphertext the encryption buffer
|
||||
/// \param mac the mac buffer
|
||||
/// \param macSize the size of the MAC buffer, in bytes
|
||||
/// \param iv the iv buffer
|
||||
/// \param ivLength the size of the IV buffer, in bytes
|
||||
/// \param aad the AAD buffer
|
||||
/// \param aadLength the size of the AAD buffer, in bytes
|
||||
/// \param message the message buffer
|
||||
/// \param messageLength the size of the messagetext buffer, in bytes
|
||||
/// \details EncryptAndAuthenticate() encrypts and generates the MAC in one call. The function
|
||||
/// truncates the MAC if <tt>macSize < TagSize()</tt>.
|
||||
virtual void EncryptAndAuthenticate(byte *ciphertext, byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *aad, size_t aadLength, const byte *message, size_t messageLength);
|
||||
|
||||
/// \brief Decrypts and verifies a MAC in one call
|
||||
/// \param message the decryption buffer
|
||||
/// \param mac the mac buffer
|
||||
/// \param macSize the size of the MAC buffer, in bytes
|
||||
/// \param iv the iv buffer
|
||||
/// \param ivLength the size of the IV buffer, in bytes
|
||||
/// \param aad the AAD buffer
|
||||
/// \param aadLength the size of the AAD buffer, in bytes
|
||||
/// \param ciphertext the cipher buffer
|
||||
/// \param ciphertextLength the size of the ciphertext buffer, in bytes
|
||||
/// \return true if the MAC is valid and the decoding succeeded, false otherwise
|
||||
/// \details DecryptAndVerify() decrypts and verifies the MAC in one call.
|
||||
/// <tt>message</tt> is a decryption buffer and should be at least as large as the ciphertext buffer.
|
||||
/// \details The function returns true iff MAC is valid. DecryptAndVerify() assumes the MAC
|
||||
/// is truncated if <tt>macLength < TagSize()</tt>.
|
||||
virtual bool DecryptAndVerify(byte *message, const byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *aad, size_t aadLength, const byte *ciphertext, size_t ciphertextLength);
|
||||
|
||||
protected:
|
||||
// AuthenticatedSymmetricCipherBase
|
||||
bool AuthenticationIsOnPlaintext() const {return false;}
|
||||
unsigned int AuthenticationBlockSize() const {return 1;}
|
||||
void SetKeyWithoutResync(const byte *userKey, size_t keylength, const NameValuePairs ¶ms);
|
||||
void Resync(const byte *iv, size_t len);
|
||||
size_t AuthenticateBlocks(const byte *data, size_t len);
|
||||
void AuthenticateLastHeaderBlock();
|
||||
void AuthenticateLastConfidentialBlock();
|
||||
void AuthenticateLastFooterBlock(byte *mac, size_t macSize);
|
||||
|
||||
// See comments in chachapoly.cpp
|
||||
void RekeyCipherAndMac(const byte *userKey, size_t userKeyLength, const NameValuePairs ¶ms);
|
||||
|
||||
virtual const MessageAuthenticationCode & GetMAC() const = 0;
|
||||
virtual MessageAuthenticationCode & AccessMAC() = 0;
|
||||
|
||||
private:
|
||||
SecByteBlock m_userKey;
|
||||
};
|
||||
|
||||
/// \brief IETF ChaCha20Poly1305 cipher final implementation
|
||||
/// \tparam T_IsEncryption flag indicating cipher direction
|
||||
/// \details ChaCha20Poly1305 is an authenticated encryption scheme that combines
|
||||
/// ChaCha20TLS and Poly1305TLS. The scheme is defined in RFC 8439, section 2.8,
|
||||
/// AEAD_CHACHA20_POLY1305 construction, and uses the IETF versions of ChaCha20
|
||||
/// and Poly1305.
|
||||
/// \sa <A HREF="http://tools.ietf.org/html/rfc8439">RFC 8439, ChaCha20 and Poly1305
|
||||
/// for IETF Protocols</A>.
|
||||
/// \since Crypto++ 8.1
|
||||
template <bool T_IsEncryption>
|
||||
class ChaCha20Poly1305_Final : public ChaCha20Poly1305_Base
|
||||
{
|
||||
public:
|
||||
virtual ~ChaCha20Poly1305_Final() {}
|
||||
|
||||
protected:
|
||||
const SymmetricCipher & GetSymmetricCipher()
|
||||
{return const_cast<ChaCha20Poly1305_Final *>(this)->AccessSymmetricCipher();}
|
||||
SymmetricCipher & AccessSymmetricCipher()
|
||||
{return m_cipher;}
|
||||
bool IsForwardTransformation() const
|
||||
{return T_IsEncryption;}
|
||||
|
||||
const MessageAuthenticationCode & GetMAC() const
|
||||
{return const_cast<ChaCha20Poly1305_Final *>(this)->AccessMAC();}
|
||||
MessageAuthenticationCode & AccessMAC()
|
||||
{return m_mac;}
|
||||
|
||||
private:
|
||||
ChaChaTLS::Encryption m_cipher;
|
||||
Poly1305TLS m_mac;
|
||||
};
|
||||
|
||||
/// \brief IETF ChaCha20/Poly1305 AEAD scheme
|
||||
/// \details ChaCha20Poly1305 is an authenticated encryption scheme that combines
|
||||
/// ChaCha20TLS and Poly1305TLS. The scheme is defined in RFC 8439, section 2.8,
|
||||
/// AEAD_CHACHA20_POLY1305 construction, and uses the IETF versions of ChaCha20
|
||||
/// and Poly1305.
|
||||
/// \sa <A HREF="http://tools.ietf.org/html/rfc8439">RFC 8439, ChaCha20 and Poly1305
|
||||
/// for IETF Protocols</A>.
|
||||
/// \since Crypto++ 8.1
|
||||
struct ChaCha20Poly1305 : public AuthenticatedSymmetricCipherDocumentation
|
||||
{
|
||||
/// \brief ChaCha20Poly1305 encryption
|
||||
typedef ChaCha20Poly1305_Final<true> Encryption;
|
||||
/// \brief ChaCha20Poly1305 decryption
|
||||
typedef ChaCha20Poly1305_Final<false> Decryption;
|
||||
};
|
||||
|
||||
////////////////////////////// IETF XChaCha20 draft //////////////////////////////
|
||||
|
||||
/// \brief IETF XChaCha20Poly1305 cipher base implementation
|
||||
/// \details Base implementation of the AuthenticatedSymmetricCipher interface
|
||||
/// \since Crypto++ 8.1
|
||||
class XChaCha20Poly1305_Base : public AuthenticatedSymmetricCipherBase
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName()
|
||||
{return "XChaCha20/Poly1305";}
|
||||
|
||||
virtual ~XChaCha20Poly1305_Base() {}
|
||||
|
||||
// AuthenticatedSymmetricCipher
|
||||
std::string AlgorithmName() const
|
||||
{return std::string("XChaCha20/Poly1305");}
|
||||
std::string AlgorithmProvider() const
|
||||
{return GetSymmetricCipher().AlgorithmProvider();}
|
||||
size_t MinKeyLength() const
|
||||
{return 32;}
|
||||
size_t MaxKeyLength() const
|
||||
{return 32;}
|
||||
size_t DefaultKeyLength() const
|
||||
{return 32;}
|
||||
size_t GetValidKeyLength(size_t n) const
|
||||
{CRYPTOPP_UNUSED(n); return 32;}
|
||||
bool IsValidKeyLength(size_t n) const
|
||||
{return n==32;}
|
||||
unsigned int OptimalDataAlignment() const
|
||||
{return GetSymmetricCipher().OptimalDataAlignment();}
|
||||
IV_Requirement IVRequirement() const
|
||||
{return UNIQUE_IV;}
|
||||
unsigned int IVSize() const
|
||||
{return 24;}
|
||||
unsigned int MinIVLength() const
|
||||
{return 24;}
|
||||
unsigned int MaxIVLength() const
|
||||
{return 24;}
|
||||
unsigned int DigestSize() const
|
||||
{return 16;}
|
||||
lword MaxHeaderLength() const
|
||||
{return LWORD_MAX;} // 2^64-1 bytes
|
||||
lword MaxMessageLength() const
|
||||
{return W64LIT(274877906880);} // 2^38-1 blocks
|
||||
lword MaxFooterLength() const
|
||||
{return 0;}
|
||||
|
||||
/// \brief Encrypts and calculates a MAC in one call
|
||||
/// \param ciphertext the encryption buffer
|
||||
/// \param mac the mac buffer
|
||||
/// \param macSize the size of the MAC buffer, in bytes
|
||||
/// \param iv the iv buffer
|
||||
/// \param ivLength the size of the IV buffer, in bytes
|
||||
/// \param aad the AAD buffer
|
||||
/// \param aadLength the size of the AAD buffer, in bytes
|
||||
/// \param message the message buffer
|
||||
/// \param messageLength the size of the messagetext buffer, in bytes
|
||||
/// \details EncryptAndAuthenticate() encrypts and generates the MAC in one call. The function
|
||||
/// truncates the MAC if <tt>macSize < TagSize()</tt>.
|
||||
virtual void EncryptAndAuthenticate(byte *ciphertext, byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *aad, size_t aadLength, const byte *message, size_t messageLength);
|
||||
|
||||
/// \brief Decrypts and verifies a MAC in one call
|
||||
/// \param message the decryption buffer
|
||||
/// \param mac the mac buffer
|
||||
/// \param macSize the size of the MAC buffer, in bytes
|
||||
/// \param iv the iv buffer
|
||||
/// \param ivLength the size of the IV buffer, in bytes
|
||||
/// \param aad the AAD buffer
|
||||
/// \param aadLength the size of the AAD buffer, in bytes
|
||||
/// \param ciphertext the cipher buffer
|
||||
/// \param ciphertextLength the size of the ciphertext buffer, in bytes
|
||||
/// \return true if the MAC is valid and the decoding succeeded, false otherwise
|
||||
/// \details DecryptAndVerify() decrypts and verifies the MAC in one call.
|
||||
/// <tt>message</tt> is a decryption buffer and should be at least as large as the ciphertext buffer.
|
||||
/// \details The function returns true iff MAC is valid. DecryptAndVerify() assumes the MAC
|
||||
/// is truncated if <tt>macLength < TagSize()</tt>.
|
||||
virtual bool DecryptAndVerify(byte *message, const byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *aad, size_t aadLength, const byte *ciphertext, size_t ciphertextLength);
|
||||
|
||||
protected:
|
||||
// AuthenticatedSymmetricCipherBase
|
||||
bool AuthenticationIsOnPlaintext() const {return false;}
|
||||
unsigned int AuthenticationBlockSize() const {return 1;}
|
||||
void SetKeyWithoutResync(const byte *userKey, size_t keylength, const NameValuePairs ¶ms);
|
||||
void Resync(const byte *iv, size_t len);
|
||||
size_t AuthenticateBlocks(const byte *data, size_t len);
|
||||
void AuthenticateLastHeaderBlock();
|
||||
void AuthenticateLastConfidentialBlock();
|
||||
void AuthenticateLastFooterBlock(byte *mac, size_t macSize);
|
||||
|
||||
// See comments in chachapoly.cpp
|
||||
void RekeyCipherAndMac(const byte *userKey, size_t userKeyLength, const NameValuePairs ¶ms);
|
||||
|
||||
virtual const MessageAuthenticationCode & GetMAC() const = 0;
|
||||
virtual MessageAuthenticationCode & AccessMAC() = 0;
|
||||
|
||||
private:
|
||||
SecByteBlock m_userKey;
|
||||
};
|
||||
|
||||
/// \brief IETF XChaCha20Poly1305 cipher final implementation
|
||||
/// \tparam T_IsEncryption flag indicating cipher direction
|
||||
/// \details XChaCha20Poly1305 is an authenticated encryption scheme that combines
|
||||
/// XChaCha20 and Poly1305-TLS. The scheme is defined in RFC 8439, section 2.8,
|
||||
/// AEAD_CHACHA20_POLY1305 construction, and uses the IETF versions of ChaCha20
|
||||
/// and Poly1305.
|
||||
/// \sa <A HREF="http://tools.ietf.org/html/rfc8439">RFC 8439, ChaCha20 and Poly1305
|
||||
/// for IETF Protocols</A>.
|
||||
/// \since Crypto++ 8.1
|
||||
template <bool T_IsEncryption>
|
||||
class XChaCha20Poly1305_Final : public XChaCha20Poly1305_Base
|
||||
{
|
||||
public:
|
||||
virtual ~XChaCha20Poly1305_Final() {}
|
||||
|
||||
protected:
|
||||
const SymmetricCipher & GetSymmetricCipher()
|
||||
{return const_cast<XChaCha20Poly1305_Final *>(this)->AccessSymmetricCipher();}
|
||||
SymmetricCipher & AccessSymmetricCipher()
|
||||
{return m_cipher;}
|
||||
bool IsForwardTransformation() const
|
||||
{return T_IsEncryption;}
|
||||
|
||||
const MessageAuthenticationCode & GetMAC() const
|
||||
{return const_cast<XChaCha20Poly1305_Final *>(this)->AccessMAC();}
|
||||
MessageAuthenticationCode & AccessMAC()
|
||||
{return m_mac;}
|
||||
|
||||
private:
|
||||
XChaCha20::Encryption m_cipher;
|
||||
Poly1305TLS m_mac;
|
||||
};
|
||||
|
||||
/// \brief IETF XChaCha20/Poly1305 AEAD scheme
|
||||
/// \details XChaCha20Poly1305 is an authenticated encryption scheme that combines
|
||||
/// XChaCha20 and Poly1305-TLS. The scheme is defined in RFC 8439, section 2.8,
|
||||
/// AEAD_XCHACHA20_POLY1305 construction, and uses the IETF versions of ChaCha20
|
||||
/// and Poly1305.
|
||||
/// \sa <A HREF="http://tools.ietf.org/html/rfc8439">RFC 8439, ChaCha20 and Poly1305
|
||||
/// for IETF Protocols</A>.
|
||||
/// \since Crypto++ 8.1
|
||||
struct XChaCha20Poly1305 : public AuthenticatedSymmetricCipherDocumentation
|
||||
{
|
||||
/// \brief XChaCha20Poly1305 encryption
|
||||
typedef XChaCha20Poly1305_Final<true> Encryption;
|
||||
/// \brief XChaCha20Poly1305 decryption
|
||||
typedef XChaCha20Poly1305_Final<false> Decryption;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif // CRYPTOPP_CHACHA_POLY1305_H
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
// cham.cpp - written and placed in the public domain by Kim Sung Hee and Jeffrey Walton
|
||||
// Based on "CHAM: A Family of Lightweight Block Ciphers for
|
||||
// Resource-Constrained Devices" by Bonwook Koo, Dongyoung Roh,
|
||||
// Hyeonjin Kim, Younghoon Jung, Dong-Geon Lee, and Daesung Kwon
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
|
||||
#include "cham.h"
|
||||
#include "misc.h"
|
||||
#include "cpu.h"
|
||||
|
||||
// CHAM table of parameters
|
||||
// +-------------------------------------------------
|
||||
// +cipher n k r w k/w
|
||||
// +-------------------------------------------------
|
||||
// +CHAM-64/128 64 128 80 16 8
|
||||
// +CHAM-128/128 128 128 80 32 4
|
||||
// +CHAM-128/256 128 256 96 32 8
|
||||
// +-------------------------------------------------
|
||||
|
||||
ANONYMOUS_NAMESPACE_BEGIN
|
||||
|
||||
using CryptoPP::rotlConstant;
|
||||
using CryptoPP::rotrConstant;
|
||||
|
||||
/// \brief CHAM encryption round
|
||||
/// \tparam RR the round number residue
|
||||
/// \tparam KW the number of key words
|
||||
/// \tparam T words type
|
||||
/// \param x the state array
|
||||
/// \param k the subkey table
|
||||
/// \param i the round number
|
||||
/// \details CHAM_EncRound applies the encryption round to the plain text.
|
||||
/// RR is the "round residue" and it is used modulo 4. ProcessAndXorBlock
|
||||
/// may provide a fully unrolled encryption transformation, or provide
|
||||
/// a transformation that loops using multiples of 4 encryption rounds.
|
||||
/// \details CHAM_EncRound calculates indexes into the x[] array based
|
||||
/// on the round number residue. There is no need for the assignments
|
||||
/// that shift values in preparations for the next round.
|
||||
/// \details CHAM_EncRound depends on the round number. The actual round
|
||||
/// being executed is passed through the parameter <tt>i</tt>. If
|
||||
/// ProcessAndXorBlock fully unrolled the loop then the parameter
|
||||
/// <tt>i</tt> would be unnecessary.
|
||||
template <unsigned int RR, unsigned int KW, class T>
|
||||
inline void CHAM_EncRound(T x[4], const T k[KW], unsigned int i)
|
||||
{
|
||||
CRYPTOPP_CONSTANT(IDX0 = (RR+0) % 4);
|
||||
CRYPTOPP_CONSTANT(IDX1 = (RR+1) % 4);
|
||||
CRYPTOPP_CONSTANT(IDX3 = (RR+3+1) % 4);
|
||||
CRYPTOPP_CONSTANT(R1 = (RR % 2 == 0) ? 1 : 8);
|
||||
CRYPTOPP_CONSTANT(R2 = (RR % 2 == 0) ? 8 : 1);
|
||||
|
||||
// Follows conventions in the ref impl
|
||||
const T kk = k[i % KW];
|
||||
const T aa = x[IDX0] ^ static_cast<T>(i);
|
||||
const T bb = rotlConstant<R1>(x[IDX1]) ^ kk;
|
||||
x[IDX3] = rotlConstant<R2>(static_cast<T>(aa + bb));
|
||||
}
|
||||
|
||||
/// \brief CHAM decryption round
|
||||
/// \tparam RR the round number residue
|
||||
/// \tparam KW the number of key words
|
||||
/// \tparam T words type
|
||||
/// \param x the state array
|
||||
/// \param k the subkey table
|
||||
/// \param i the round number
|
||||
/// \details CHAM_DecRound applies the decryption round to the cipher text.
|
||||
/// RR is the "round residue" and it is used modulo 4. ProcessAndXorBlock
|
||||
/// may provide a fully unrolled decryption transformation, or provide
|
||||
/// a transformation that loops using multiples of 4 decryption rounds.
|
||||
/// \details CHAM_DecRound calculates indexes into the x[] array based
|
||||
/// on the round number residue. There is no need for the assignments
|
||||
/// that shift values in preparations for the next round.
|
||||
/// \details CHAM_DecRound depends on the round number. The actual round
|
||||
/// being executed is passed through the parameter <tt>i</tt>. If
|
||||
/// ProcessAndXorBlock fully unrolled the loop then the parameter
|
||||
/// <tt>i</tt> would be unnecessary.
|
||||
template <unsigned int RR, unsigned int KW, class T>
|
||||
inline void CHAM_DecRound(T x[4], const T k[KW], unsigned int i)
|
||||
{
|
||||
CRYPTOPP_CONSTANT(IDX0 = (RR+0) % 4);
|
||||
CRYPTOPP_CONSTANT(IDX1 = (RR+1) % 4);
|
||||
CRYPTOPP_CONSTANT(IDX3 = (RR+3+1) % 4);
|
||||
CRYPTOPP_CONSTANT(R1 = (RR % 2 == 0) ? 8 : 1);
|
||||
CRYPTOPP_CONSTANT(R2 = (RR % 2 == 0) ? 1 : 8);
|
||||
|
||||
// Follows conventions in the ref impl
|
||||
const T kk = k[i % KW];
|
||||
const T aa = rotrConstant<R1>(x[IDX3]);
|
||||
const T bb = rotlConstant<R2>(x[IDX1]) ^ kk;
|
||||
x[IDX0] = static_cast<T>(aa - bb) ^ static_cast<T>(i);
|
||||
}
|
||||
|
||||
ANONYMOUS_NAMESPACE_END
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
#if CRYPTOPP_CHAM128_ADVANCED_PROCESS_BLOCKS
|
||||
# if (CRYPTOPP_SSSE3_AVAILABLE)
|
||||
extern size_t CHAM64_Enc_AdvancedProcessBlocks_SSSE3(const word16* subKeys, size_t rounds,
|
||||
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags);
|
||||
|
||||
extern size_t CHAM64_Dec_AdvancedProcessBlocks_SSSE3(const word16* subKeys, size_t rounds,
|
||||
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags);
|
||||
|
||||
extern size_t CHAM128_Enc_AdvancedProcessBlocks_SSSE3(const word32* subKeys, size_t rounds,
|
||||
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags);
|
||||
|
||||
extern size_t CHAM128_Dec_AdvancedProcessBlocks_SSSE3(const word32* subKeys, size_t rounds,
|
||||
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags);
|
||||
# endif // CRYPTOPP_SSSE3_AVAILABLE
|
||||
#endif // CRYPTOPP_CHAM128_ADVANCED_PROCESS_BLOCKS
|
||||
|
||||
void CHAM64::Base::UncheckedSetKey(const byte *userKey, unsigned int keyLength, const NameValuePairs ¶ms)
|
||||
{
|
||||
CRYPTOPP_UNUSED(params);
|
||||
m_kw = keyLength/sizeof(word16);
|
||||
m_rk.New(2*m_kw);
|
||||
|
||||
for (size_t i = 0; i < m_kw; userKey += sizeof(word32))
|
||||
{
|
||||
// Do not cast the buffer. It will SIGBUS on some ARM and SPARC.
|
||||
const word32 rk = GetWord<word32>(false, BIG_ENDIAN_ORDER, userKey);
|
||||
|
||||
const word16 rk1 = rk >> 16;
|
||||
m_rk[i] = rk1 ^ rotlConstant<1>(rk1) ^ rotlConstant<8>(rk1);
|
||||
m_rk[(i + m_kw) ^ 1] = rk1 ^ rotlConstant<1>(rk1) ^ rotlConstant<11>(rk1);
|
||||
i++;
|
||||
|
||||
const word16 rk2 = rk & 0xffff;
|
||||
m_rk[i] = rk2 ^ rotlConstant<1>(rk2) ^ rotlConstant<8>(rk2);
|
||||
m_rk[(i + m_kw) ^ 1] = rk2 ^ rotlConstant<1>(rk2) ^ rotlConstant<11>(rk2);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
void CHAM64::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
// Do not cast the buffer. It will SIGBUS on some ARM and SPARC.
|
||||
GetBlock<word16, BigEndian> iblock(inBlock);
|
||||
iblock(m_x[0])(m_x[1])(m_x[2])(m_x[3]);
|
||||
|
||||
const int R = 80;
|
||||
for (int i = 0; i < R; i+=16)
|
||||
{
|
||||
CHAM_EncRound< 0, 16>(m_x.begin(), m_rk.begin(), i+0);
|
||||
CHAM_EncRound< 1, 16>(m_x.begin(), m_rk.begin(), i+1);
|
||||
CHAM_EncRound< 2, 16>(m_x.begin(), m_rk.begin(), i+2);
|
||||
CHAM_EncRound< 3, 16>(m_x.begin(), m_rk.begin(), i+3);
|
||||
CHAM_EncRound< 4, 16>(m_x.begin(), m_rk.begin(), i+4);
|
||||
CHAM_EncRound< 5, 16>(m_x.begin(), m_rk.begin(), i+5);
|
||||
CHAM_EncRound< 6, 16>(m_x.begin(), m_rk.begin(), i+6);
|
||||
CHAM_EncRound< 7, 16>(m_x.begin(), m_rk.begin(), i+7);
|
||||
CHAM_EncRound< 8, 16>(m_x.begin(), m_rk.begin(), i+8);
|
||||
CHAM_EncRound< 9, 16>(m_x.begin(), m_rk.begin(), i+9);
|
||||
CHAM_EncRound<10, 16>(m_x.begin(), m_rk.begin(), i+10);
|
||||
CHAM_EncRound<11, 16>(m_x.begin(), m_rk.begin(), i+11);
|
||||
CHAM_EncRound<12, 16>(m_x.begin(), m_rk.begin(), i+12);
|
||||
CHAM_EncRound<13, 16>(m_x.begin(), m_rk.begin(), i+13);
|
||||
CHAM_EncRound<14, 16>(m_x.begin(), m_rk.begin(), i+14);
|
||||
CHAM_EncRound<15, 16>(m_x.begin(), m_rk.begin(), i+15);
|
||||
}
|
||||
|
||||
PutBlock<word16, BigEndian> oblock(xorBlock, outBlock);
|
||||
oblock(m_x[0])(m_x[1])(m_x[2])(m_x[3]);
|
||||
}
|
||||
|
||||
void CHAM64::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
// Do not cast the buffer. It will SIGBUS on some ARM and SPARC.
|
||||
GetBlock<word16, BigEndian> iblock(inBlock);
|
||||
iblock(m_x[0])(m_x[1])(m_x[2])(m_x[3]);
|
||||
|
||||
const int R = 80;
|
||||
for (int i = R-1; i >=0 ; i-=16)
|
||||
{
|
||||
CHAM_DecRound<15, 16>(m_x.begin(), m_rk.begin(), i-0);
|
||||
CHAM_DecRound<14, 16>(m_x.begin(), m_rk.begin(), i-1);
|
||||
CHAM_DecRound<13, 16>(m_x.begin(), m_rk.begin(), i-2);
|
||||
CHAM_DecRound<12, 16>(m_x.begin(), m_rk.begin(), i-3);
|
||||
CHAM_DecRound<11, 16>(m_x.begin(), m_rk.begin(), i-4);
|
||||
CHAM_DecRound<10, 16>(m_x.begin(), m_rk.begin(), i-5);
|
||||
CHAM_DecRound< 9, 16>(m_x.begin(), m_rk.begin(), i-6);
|
||||
CHAM_DecRound< 8, 16>(m_x.begin(), m_rk.begin(), i-7);
|
||||
CHAM_DecRound< 7, 16>(m_x.begin(), m_rk.begin(), i-8);
|
||||
CHAM_DecRound< 6, 16>(m_x.begin(), m_rk.begin(), i-9);
|
||||
CHAM_DecRound< 5, 16>(m_x.begin(), m_rk.begin(), i-10);
|
||||
CHAM_DecRound< 4, 16>(m_x.begin(), m_rk.begin(), i-11);
|
||||
CHAM_DecRound< 3, 16>(m_x.begin(), m_rk.begin(), i-12);
|
||||
CHAM_DecRound< 2, 16>(m_x.begin(), m_rk.begin(), i-13);
|
||||
CHAM_DecRound< 1, 16>(m_x.begin(), m_rk.begin(), i-14);
|
||||
CHAM_DecRound< 0, 16>(m_x.begin(), m_rk.begin(), i-15);
|
||||
}
|
||||
|
||||
PutBlock<word16, BigEndian> oblock(xorBlock, outBlock);
|
||||
oblock(m_x[0])(m_x[1])(m_x[2])(m_x[3]);
|
||||
}
|
||||
|
||||
std::string CHAM128::Base::AlgorithmProvider() const
|
||||
{
|
||||
#if defined(CRYPTOPP_SSSE3_AVAILABLE)
|
||||
if (HasSSSE3())
|
||||
return "SSSE3";
|
||||
#endif
|
||||
return "C++";
|
||||
}
|
||||
|
||||
void CHAM128::Base::UncheckedSetKey(const byte *userKey, unsigned int keyLength, const NameValuePairs ¶ms)
|
||||
{
|
||||
CRYPTOPP_UNUSED(params);
|
||||
m_kw = keyLength/sizeof(word32);
|
||||
m_rk.New(2*m_kw);
|
||||
|
||||
for (size_t i = 0; i < m_kw; userKey += sizeof(word32))
|
||||
{
|
||||
// Do not cast the buffer. It will SIGBUS on some ARM and SPARC.
|
||||
const word32 rk = GetWord<word32>(false, BIG_ENDIAN_ORDER, userKey);
|
||||
m_rk[i] = rk ^ rotlConstant<1>(rk) ^ rotlConstant<8>(rk);
|
||||
m_rk[(i + m_kw) ^ 1] = rk ^ rotlConstant<1>(rk) ^ rotlConstant<11>(rk);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
void CHAM128::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
// Do not cast the buffer. It will SIGBUS on some ARM and SPARC.
|
||||
GetBlock<word32, BigEndian> iblock(inBlock);
|
||||
iblock(m_x[0])(m_x[1])(m_x[2])(m_x[3]);
|
||||
|
||||
switch (m_kw)
|
||||
{
|
||||
case 4: // 128-bit key
|
||||
{
|
||||
const int R = 80;
|
||||
for (int i = 0; i < R; i+=8)
|
||||
{
|
||||
CHAM_EncRound<0, 8>(m_x.begin(), m_rk.begin(), i+0);
|
||||
CHAM_EncRound<1, 8>(m_x.begin(), m_rk.begin(), i+1);
|
||||
CHAM_EncRound<2, 8>(m_x.begin(), m_rk.begin(), i+2);
|
||||
CHAM_EncRound<3, 8>(m_x.begin(), m_rk.begin(), i+3);
|
||||
CHAM_EncRound<4, 8>(m_x.begin(), m_rk.begin(), i+4);
|
||||
CHAM_EncRound<5, 8>(m_x.begin(), m_rk.begin(), i+5);
|
||||
CHAM_EncRound<6, 8>(m_x.begin(), m_rk.begin(), i+6);
|
||||
CHAM_EncRound<7, 8>(m_x.begin(), m_rk.begin(), i+7);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 8: // 256-bit key
|
||||
{
|
||||
const int R = 96;
|
||||
for (int i = 0; i < R; i+=16)
|
||||
{
|
||||
CHAM_EncRound< 0, 16>(m_x.begin(), m_rk.begin(), i+0);
|
||||
CHAM_EncRound< 1, 16>(m_x.begin(), m_rk.begin(), i+1);
|
||||
CHAM_EncRound< 2, 16>(m_x.begin(), m_rk.begin(), i+2);
|
||||
CHAM_EncRound< 3, 16>(m_x.begin(), m_rk.begin(), i+3);
|
||||
CHAM_EncRound< 4, 16>(m_x.begin(), m_rk.begin(), i+4);
|
||||
CHAM_EncRound< 5, 16>(m_x.begin(), m_rk.begin(), i+5);
|
||||
CHAM_EncRound< 6, 16>(m_x.begin(), m_rk.begin(), i+6);
|
||||
CHAM_EncRound< 7, 16>(m_x.begin(), m_rk.begin(), i+7);
|
||||
CHAM_EncRound< 8, 16>(m_x.begin(), m_rk.begin(), i+8);
|
||||
CHAM_EncRound< 9, 16>(m_x.begin(), m_rk.begin(), i+9);
|
||||
CHAM_EncRound<10, 16>(m_x.begin(), m_rk.begin(), i+10);
|
||||
CHAM_EncRound<11, 16>(m_x.begin(), m_rk.begin(), i+11);
|
||||
CHAM_EncRound<12, 16>(m_x.begin(), m_rk.begin(), i+12);
|
||||
CHAM_EncRound<13, 16>(m_x.begin(), m_rk.begin(), i+13);
|
||||
CHAM_EncRound<14, 16>(m_x.begin(), m_rk.begin(), i+14);
|
||||
CHAM_EncRound<15, 16>(m_x.begin(), m_rk.begin(), i+15);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
CRYPTOPP_ASSERT(0);
|
||||
}
|
||||
|
||||
PutBlock<word32, BigEndian> oblock(xorBlock, outBlock);
|
||||
oblock(m_x[0])(m_x[1])(m_x[2])(m_x[3]);
|
||||
}
|
||||
|
||||
void CHAM128::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
// Do not cast the buffer. It will SIGBUS on some ARM and SPARC.
|
||||
GetBlock<word32, BigEndian> iblock(inBlock);
|
||||
iblock(m_x[0])(m_x[1])(m_x[2])(m_x[3]);
|
||||
|
||||
switch (m_kw)
|
||||
{
|
||||
case 4: // 128-bit key
|
||||
{
|
||||
const int R = 80;
|
||||
for (int i = R-1; i >= 0; i-=8)
|
||||
{
|
||||
CHAM_DecRound<7, 8>(m_x.begin(), m_rk.begin(), i-0);
|
||||
CHAM_DecRound<6, 8>(m_x.begin(), m_rk.begin(), i-1);
|
||||
CHAM_DecRound<5, 8>(m_x.begin(), m_rk.begin(), i-2);
|
||||
CHAM_DecRound<4, 8>(m_x.begin(), m_rk.begin(), i-3);
|
||||
CHAM_DecRound<3, 8>(m_x.begin(), m_rk.begin(), i-4);
|
||||
CHAM_DecRound<2, 8>(m_x.begin(), m_rk.begin(), i-5);
|
||||
CHAM_DecRound<1, 8>(m_x.begin(), m_rk.begin(), i-6);
|
||||
CHAM_DecRound<0, 8>(m_x.begin(), m_rk.begin(), i-7);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 8: // 256-bit key
|
||||
{
|
||||
const int R = 96;
|
||||
for (int i = R-1; i >= 0; i-=16)
|
||||
{
|
||||
CHAM_DecRound<15, 16>(m_x.begin(), m_rk.begin(), i-0);
|
||||
CHAM_DecRound<14, 16>(m_x.begin(), m_rk.begin(), i-1);
|
||||
CHAM_DecRound<13, 16>(m_x.begin(), m_rk.begin(), i-2);
|
||||
CHAM_DecRound<12, 16>(m_x.begin(), m_rk.begin(), i-3);
|
||||
CHAM_DecRound<11, 16>(m_x.begin(), m_rk.begin(), i-4);
|
||||
CHAM_DecRound<10, 16>(m_x.begin(), m_rk.begin(), i-5);
|
||||
CHAM_DecRound< 9, 16>(m_x.begin(), m_rk.begin(), i-6);
|
||||
CHAM_DecRound< 8, 16>(m_x.begin(), m_rk.begin(), i-7);
|
||||
CHAM_DecRound< 7, 16>(m_x.begin(), m_rk.begin(), i-8);
|
||||
CHAM_DecRound< 6, 16>(m_x.begin(), m_rk.begin(), i-9);
|
||||
CHAM_DecRound< 5, 16>(m_x.begin(), m_rk.begin(), i-10);
|
||||
CHAM_DecRound< 4, 16>(m_x.begin(), m_rk.begin(), i-11);
|
||||
CHAM_DecRound< 3, 16>(m_x.begin(), m_rk.begin(), i-12);
|
||||
CHAM_DecRound< 2, 16>(m_x.begin(), m_rk.begin(), i-13);
|
||||
CHAM_DecRound< 1, 16>(m_x.begin(), m_rk.begin(), i-14);
|
||||
CHAM_DecRound< 0, 16>(m_x.begin(), m_rk.begin(), i-15);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
CRYPTOPP_ASSERT(0);
|
||||
}
|
||||
|
||||
PutBlock<word32, BigEndian> oblock(xorBlock, outBlock);
|
||||
oblock(m_x[0])(m_x[1])(m_x[2])(m_x[3]);
|
||||
}
|
||||
|
||||
#if CRYPTOPP_CHAM128_ADVANCED_PROCESS_BLOCKS
|
||||
size_t CHAM128::Enc::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks,
|
||||
byte *outBlocks, size_t length, word32 flags) const
|
||||
{
|
||||
# if (CRYPTOPP_SSSE3_AVAILABLE)
|
||||
if (HasSSSE3()) {
|
||||
const size_t rounds = (m_kw == 4 ? 80 : 96);
|
||||
return CHAM128_Enc_AdvancedProcessBlocks_SSSE3(m_rk, rounds,
|
||||
inBlocks, xorBlocks, outBlocks, length, flags);
|
||||
}
|
||||
# endif // CRYPTOPP_SSSE3_AVAILABLE
|
||||
return BlockTransformation::AdvancedProcessBlocks(inBlocks, xorBlocks, outBlocks, length, flags);
|
||||
}
|
||||
|
||||
size_t CHAM128::Dec::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks,
|
||||
byte *outBlocks, size_t length, word32 flags) const
|
||||
{
|
||||
# if (CRYPTOPP_SSSE3_AVAILABLE)
|
||||
if (HasSSSE3()) {
|
||||
const size_t rounds = (m_kw == 4 ? 80 : 96);
|
||||
return CHAM128_Dec_AdvancedProcessBlocks_SSSE3(m_rk, rounds,
|
||||
inBlocks, xorBlocks, outBlocks, length, flags);
|
||||
}
|
||||
# endif // CRYPTOPP_SSSE3_AVAILABLE
|
||||
return BlockTransformation::AdvancedProcessBlocks(inBlocks, xorBlocks, outBlocks, length, flags);
|
||||
}
|
||||
#endif // CRYPTOPP_CHAM128_ADVANCED_PROCESS_BLOCKS
|
||||
|
||||
NAMESPACE_END
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
// cham.h - written and placed in the public domain by Kim Sung Hee and Jeffrey Walton
|
||||
// Based on "CHAM: A Family of Lightweight Block Ciphers for
|
||||
// Resource-Constrained Devices" by Bonwook Koo, Dongyoung Roh,
|
||||
// Hyeonjin Kim, Younghoon Jung, Dong-Geon Lee, and Daesung Kwon
|
||||
|
||||
/// \file cham.h
|
||||
/// \brief Classes for the CHAM block cipher
|
||||
/// \since Crypto++ 8.0
|
||||
|
||||
#ifndef CRYPTOPP_CHAM_H
|
||||
#define CRYPTOPP_CHAM_H
|
||||
|
||||
#include "config.h"
|
||||
#include "seckey.h"
|
||||
#include "secblock.h"
|
||||
#include "algparam.h"
|
||||
|
||||
#if (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86)
|
||||
# define CRYPTOPP_CHAM128_ADVANCED_PROCESS_BLOCKS 1
|
||||
#endif
|
||||
|
||||
// Yet another SunStudio/SunCC workaround. Failed self tests
|
||||
// in SSE code paths on i386 for SunStudio 12.3 and below.
|
||||
#if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x5120)
|
||||
# undef CRYPTOPP_CHAM128_ADVANCED_PROCESS_BLOCKS
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief CHAM block cipher information
|
||||
/// \since Crypto++ 8.0
|
||||
struct CHAM64_Info : public FixedBlockSize<8>, public FixedKeyLength<16>
|
||||
{
|
||||
/// \brief The algorithm name
|
||||
/// \return the algorithm name
|
||||
/// \details StaticAlgorithmName returns the algorithm's name as a static
|
||||
/// member function.
|
||||
static const std::string StaticAlgorithmName()
|
||||
{
|
||||
// Format is Cipher-Blocksize
|
||||
return "CHAM-64";
|
||||
}
|
||||
};
|
||||
|
||||
/// \brief CHAM block cipher information
|
||||
/// \since Crypto++ 8.0
|
||||
struct CHAM128_Info : public FixedBlockSize<16>, public VariableKeyLength<16,16,32,16>
|
||||
{
|
||||
/// \brief The algorithm name
|
||||
/// \return the algorithm name
|
||||
/// \details StaticAlgorithmName returns the algorithm's name as a static
|
||||
/// member function.
|
||||
static const std::string StaticAlgorithmName()
|
||||
{
|
||||
// Format is Cipher-Blocksize
|
||||
return "CHAM-128";
|
||||
}
|
||||
};
|
||||
|
||||
/// \brief CHAM 64-bit block cipher
|
||||
/// \details CHAM64 provides 64-bit block size. The valid key size is 128-bit.
|
||||
/// \note Crypto++ provides a byte oriented implementation
|
||||
/// \sa CHAM128, <a href="http://www.cryptopp.com/wiki/CHAM">CHAM</a>,
|
||||
/// <a href="https://pdfs.semanticscholar.org/2f57/61b5c2614cffd58a09cc83c375a2b32a2ed3.pdf">
|
||||
/// CHAM: A Family of Lightweight Block Ciphers for Resource-Constrained Devices</a>
|
||||
/// \since Crypto++ 8.0
|
||||
class CRYPTOPP_NO_VTABLE CHAM64 : public CHAM64_Info, public BlockCipherDocumentation
|
||||
{
|
||||
public:
|
||||
/// \brief CHAM block cipher transformation functions
|
||||
/// \details Provides implementation common to encryption and decryption
|
||||
/// \since Crypto++ 8.0
|
||||
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<CHAM64_Info>
|
||||
{
|
||||
protected:
|
||||
void UncheckedSetKey(const byte *userKey, unsigned int keyLength, const NameValuePairs ¶ms);
|
||||
|
||||
SecBlock<word16> m_rk;
|
||||
mutable FixedSizeSecBlock<word16, 4> m_x;
|
||||
unsigned int m_kw;
|
||||
};
|
||||
|
||||
/// \brief Encryption transformation
|
||||
/// \details Enc provides implementation for encryption transformation. All key and block
|
||||
/// sizes are supported.
|
||||
/// \since Crypto++ 8.0
|
||||
class CRYPTOPP_NO_VTABLE Enc : public Base
|
||||
{
|
||||
public:
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
};
|
||||
|
||||
/// \brief Decryption transformation
|
||||
/// \details Dec provides implementation for decryption transformation. All key and block
|
||||
/// sizes are supported.
|
||||
/// \since Crypto++ 8.0
|
||||
class CRYPTOPP_NO_VTABLE Dec : public Base
|
||||
{
|
||||
public:
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
};
|
||||
|
||||
/// \brief CHAM64 encryption
|
||||
typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
|
||||
/// \brief CHAM64 decryption
|
||||
typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
|
||||
};
|
||||
|
||||
/// \brief CHAM64 encryption
|
||||
typedef CHAM64::Encryption CHAM64Encryption;
|
||||
/// \brief CHAM64 decryption
|
||||
typedef CHAM64::Decryption CHAM64Decryption;
|
||||
|
||||
/// \brief CHAM 128-bit block cipher
|
||||
/// \details CHAM128 provides 128-bit block size. The valid key size is 128-bit and 256-bit.
|
||||
/// \note Crypto++ provides a byte oriented implementation
|
||||
/// \sa CHAM64, <a href="http://www.cryptopp.com/wiki/CHAM">CHAM</a>,
|
||||
/// <a href="https://pdfs.semanticscholar.org/2f57/61b5c2614cffd58a09cc83c375a2b32a2ed3.pdf">
|
||||
/// CHAM: A Family of Lightweight Block Ciphers for Resource-Constrained Devices</a>
|
||||
/// \since Crypto++ 8.0
|
||||
class CRYPTOPP_NO_VTABLE CHAM128 : public CHAM128_Info, public BlockCipherDocumentation
|
||||
{
|
||||
public:
|
||||
/// \brief CHAM block cipher transformation functions
|
||||
/// \details Provides implementation common to encryption and decryption
|
||||
/// \since Crypto++ 8.0
|
||||
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<CHAM128_Info>
|
||||
{
|
||||
protected:
|
||||
void UncheckedSetKey(const byte *userKey, unsigned int keyLength, const NameValuePairs ¶ms);
|
||||
std::string AlgorithmProvider() const;
|
||||
|
||||
SecBlock<word32> m_rk;
|
||||
mutable FixedSizeSecBlock<word32, 4> m_x;
|
||||
unsigned int m_kw;
|
||||
};
|
||||
|
||||
/// \brief Encryption transformation
|
||||
/// \details Enc provides implementation for encryption transformation. All key and block
|
||||
/// sizes are supported.
|
||||
/// \since Crypto++ 8.0
|
||||
class CRYPTOPP_NO_VTABLE Enc : public Base
|
||||
{
|
||||
public:
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
|
||||
#if CRYPTOPP_CHAM128_ADVANCED_PROCESS_BLOCKS
|
||||
size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
|
||||
#endif
|
||||
};
|
||||
|
||||
/// \brief Decryption transformation
|
||||
/// \details Dec provides implementation for decryption transformation. All key and block
|
||||
/// sizes are supported.
|
||||
/// \since Crypto++ 8.0
|
||||
class CRYPTOPP_NO_VTABLE Dec : public Base
|
||||
{
|
||||
public:
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
|
||||
#if CRYPTOPP_CHAM128_ADVANCED_PROCESS_BLOCKS
|
||||
size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
|
||||
#endif
|
||||
};
|
||||
|
||||
/// \brief CHAM128 encryption
|
||||
typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
|
||||
/// \brief CHAM128 decryption
|
||||
typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
|
||||
};
|
||||
|
||||
/// \brief CHAM128 encryption
|
||||
typedef CHAM128::Encryption CHAM128Encryption;
|
||||
/// \brief CHAM128 decryption
|
||||
typedef CHAM128::Decryption CHAM128Decryption;
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif // CRYPTOPP_CHAM_H
|
||||
+478
@@ -0,0 +1,478 @@
|
||||
// cham_simd.cpp - written and placed in the public domain by Jeffrey Walton
|
||||
//
|
||||
// This source file uses intrinsics and built-ins to gain access to
|
||||
// SSSE3, ARM NEON and ARMv8a, and Power7 Altivec instructions. A separate
|
||||
// source file is needed because additional CXXFLAGS are required to enable
|
||||
// the appropriate instructions sets in some build configurations.
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
|
||||
#include "cham.h"
|
||||
#include "misc.h"
|
||||
|
||||
// Uncomment for benchmarking C++ against SSE or NEON.
|
||||
// Do so in both simon.cpp and simon_simd.cpp.
|
||||
// #undef CRYPTOPP_SSSE3_AVAILABLE
|
||||
// #undef CRYPTOPP_ARM_NEON_AVAILABLE
|
||||
|
||||
#if (CRYPTOPP_SSSE3_AVAILABLE)
|
||||
#include "adv_simd.h"
|
||||
# include <pmmintrin.h>
|
||||
# include <tmmintrin.h>
|
||||
#endif
|
||||
|
||||
#if defined(__XOP__)
|
||||
# include <ammintrin.h>
|
||||
# if defined(__GNUC__)
|
||||
# include <x86intrin.h>
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// Clang intrinsic casts, http://bugs.llvm.org/show_bug.cgi?id=20670
|
||||
#define DOUBLE_CAST(x) ((double*)(void*)(x))
|
||||
#define CONST_DOUBLE_CAST(x) ((const double*)(const void*)(x))
|
||||
|
||||
// Squash MS LNK4221 and libtool warnings
|
||||
extern const char CHAM_SIMD_FNAME[] = __FILE__;
|
||||
|
||||
ANONYMOUS_NAMESPACE_BEGIN
|
||||
|
||||
using CryptoPP::word16;
|
||||
using CryptoPP::word32;
|
||||
|
||||
#if (CRYPTOPP_SSSE3_AVAILABLE)
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
NAMESPACE_BEGIN(W32) // CHAM128, 32-bit word size
|
||||
|
||||
template <unsigned int R>
|
||||
inline __m128i RotateLeft32(const __m128i& val)
|
||||
{
|
||||
#if defined(__XOP__)
|
||||
return _mm_roti_epi32(val, R);
|
||||
#else
|
||||
return _mm_or_si128(
|
||||
_mm_slli_epi32(val, R), _mm_srli_epi32(val, 32-R));
|
||||
#endif
|
||||
}
|
||||
|
||||
template <unsigned int R>
|
||||
inline __m128i RotateRight32(const __m128i& val)
|
||||
{
|
||||
#if defined(__XOP__)
|
||||
return _mm_roti_epi32(val, 32-R);
|
||||
#else
|
||||
return _mm_or_si128(
|
||||
_mm_slli_epi32(val, 32-R), _mm_srli_epi32(val, R));
|
||||
#endif
|
||||
}
|
||||
|
||||
// Faster than two Shifts and an Or. Thanks to Louis Wingers and Bryan Weeks.
|
||||
template <>
|
||||
inline __m128i RotateLeft32<8>(const __m128i& val)
|
||||
{
|
||||
#if defined(__XOP__)
|
||||
return _mm_roti_epi32(val, 8);
|
||||
#else
|
||||
const __m128i mask = _mm_set_epi8(14,13,12,15, 10,9,8,11, 6,5,4,7, 2,1,0,3);
|
||||
return _mm_shuffle_epi8(val, mask);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Faster than two Shifts and an Or. Thanks to Louis Wingers and Bryan Weeks.
|
||||
template <>
|
||||
inline __m128i RotateRight32<8>(const __m128i& val)
|
||||
{
|
||||
#if defined(__XOP__)
|
||||
return _mm_roti_epi32(val, 32-8);
|
||||
#else
|
||||
const __m128i mask = _mm_set_epi8(12,15,14,13, 8,11,10,9, 4,7,6,5, 0,3,2,1);
|
||||
return _mm_shuffle_epi8(val, mask);
|
||||
#endif
|
||||
}
|
||||
|
||||
template <unsigned int IDX>
|
||||
inline __m128i UnpackXMM(const __m128i& a, const __m128i& b, const __m128i& c, const __m128i& d)
|
||||
{
|
||||
// Should not be instantiated
|
||||
CRYPTOPP_UNUSED(a); CRYPTOPP_UNUSED(b);
|
||||
CRYPTOPP_UNUSED(c); CRYPTOPP_UNUSED(d);
|
||||
CRYPTOPP_ASSERT(0);
|
||||
return _mm_setzero_si128();
|
||||
}
|
||||
|
||||
template <>
|
||||
inline __m128i UnpackXMM<0>(const __m128i& a, const __m128i& b, const __m128i& c, const __m128i& d)
|
||||
{
|
||||
// The shuffle converts to and from little-endian for SSE. A specialized
|
||||
// CHAM implementation can avoid the shuffle by framing the data for
|
||||
// encryption, decryption and benchmarks. The library cannot take the
|
||||
// speed-up because of the byte oriented API.
|
||||
const __m128i r1 = _mm_unpacklo_epi32(a, b);
|
||||
const __m128i r2 = _mm_unpacklo_epi32(c, d);
|
||||
return _mm_shuffle_epi8(_mm_unpacklo_epi64(r1, r2),
|
||||
_mm_set_epi8(12,13,14,15, 8,9,10,11, 4,5,6,7, 0,1,2,3));
|
||||
}
|
||||
|
||||
template <>
|
||||
inline __m128i UnpackXMM<1>(const __m128i& a, const __m128i& b, const __m128i& c, const __m128i& d)
|
||||
{
|
||||
// The shuffle converts to and from little-endian for SSE. A specialized
|
||||
// CHAM implementation can avoid the shuffle by framing the data for
|
||||
// encryption, decryption and benchmarks. The library cannot take the
|
||||
// speed-up because of the byte oriented API.
|
||||
const __m128i r1 = _mm_unpacklo_epi32(a, b);
|
||||
const __m128i r2 = _mm_unpacklo_epi32(c, d);
|
||||
return _mm_shuffle_epi8(_mm_unpackhi_epi64(r1, r2),
|
||||
_mm_set_epi8(12,13,14,15, 8,9,10,11, 4,5,6,7, 0,1,2,3));
|
||||
}
|
||||
|
||||
template <>
|
||||
inline __m128i UnpackXMM<2>(const __m128i& a, const __m128i& b, const __m128i& c, const __m128i& d)
|
||||
{
|
||||
// The shuffle converts to and from little-endian for SSE. A specialized
|
||||
// CHAM implementation can avoid the shuffle by framing the data for
|
||||
// encryption, decryption and benchmarks. The library cannot take the
|
||||
// speed-up because of the byte oriented API.
|
||||
const __m128i r1 = _mm_unpackhi_epi32(a, b);
|
||||
const __m128i r2 = _mm_unpackhi_epi32(c, d);
|
||||
return _mm_shuffle_epi8(_mm_unpacklo_epi64(r1, r2),
|
||||
_mm_set_epi8(12,13,14,15, 8,9,10,11, 4,5,6,7, 0,1,2,3));
|
||||
}
|
||||
|
||||
template <>
|
||||
inline __m128i UnpackXMM<3>(const __m128i& a, const __m128i& b, const __m128i& c, const __m128i& d)
|
||||
{
|
||||
// The shuffle converts to and from little-endian for SSE. A specialized
|
||||
// CHAM implementation can avoid the shuffle by framing the data for
|
||||
// encryption, decryption and benchmarks. The library cannot take the
|
||||
// speed-up because of the byte oriented API.
|
||||
const __m128i r1 = _mm_unpackhi_epi32(a, b);
|
||||
const __m128i r2 = _mm_unpackhi_epi32(c, d);
|
||||
return _mm_shuffle_epi8(_mm_unpackhi_epi64(r1, r2),
|
||||
_mm_set_epi8(12,13,14,15, 8,9,10,11, 4,5,6,7, 0,1,2,3));
|
||||
}
|
||||
|
||||
template <unsigned int IDX>
|
||||
inline __m128i UnpackXMM(const __m128i& v)
|
||||
{
|
||||
// Should not be instantiated
|
||||
CRYPTOPP_UNUSED(v); CRYPTOPP_ASSERT(0);
|
||||
return _mm_setzero_si128();
|
||||
}
|
||||
|
||||
template <>
|
||||
inline __m128i UnpackXMM<0>(const __m128i& v)
|
||||
{
|
||||
return _mm_shuffle_epi8(v, _mm_set_epi8(0,1,2,3, 0,1,2,3, 0,1,2,3, 0,1,2,3));
|
||||
}
|
||||
|
||||
template <>
|
||||
inline __m128i UnpackXMM<1>(const __m128i& v)
|
||||
{
|
||||
return _mm_shuffle_epi8(v, _mm_set_epi8(4,5,6,7, 4,5,6,7, 4,5,6,7, 4,5,6,7));
|
||||
}
|
||||
|
||||
template <>
|
||||
inline __m128i UnpackXMM<2>(const __m128i& v)
|
||||
{
|
||||
return _mm_shuffle_epi8(v, _mm_set_epi8(8,9,10,11, 8,9,10,11, 8,9,10,11, 8,9,10,11));
|
||||
}
|
||||
|
||||
template <>
|
||||
inline __m128i UnpackXMM<3>(const __m128i& v)
|
||||
{
|
||||
return _mm_shuffle_epi8(v, _mm_set_epi8(12,13,14,15, 12,13,14,15, 12,13,14,15, 12,13,14,15));
|
||||
}
|
||||
|
||||
template <unsigned int IDX>
|
||||
inline __m128i RepackXMM(const __m128i& a, const __m128i& b, const __m128i& c, const __m128i& d)
|
||||
{
|
||||
return UnpackXMM<IDX>(a, b, c, d);
|
||||
}
|
||||
|
||||
template <unsigned int IDX>
|
||||
inline __m128i RepackXMM(const __m128i& v)
|
||||
{
|
||||
return UnpackXMM<IDX>(v);
|
||||
}
|
||||
|
||||
inline void CHAM128_Enc_Block(__m128i &block0,
|
||||
const word32 *subkeys, unsigned int rounds)
|
||||
{
|
||||
// Rearrange the data for vectorization. UnpackXMM includes a
|
||||
// little-endian swap for SSE. Thanks to Peter Cordes for help
|
||||
// with packing and unpacking.
|
||||
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 B1 C1 D1][A2 B2 C2 D2] ...
|
||||
__m128i a = UnpackXMM<0>(block0);
|
||||
__m128i b = UnpackXMM<1>(block0);
|
||||
__m128i c = UnpackXMM<2>(block0);
|
||||
__m128i d = UnpackXMM<3>(block0);
|
||||
|
||||
__m128i counter = _mm_set_epi32(0,0,0,0);
|
||||
__m128i increment = _mm_set_epi32(1,1,1,1);
|
||||
|
||||
const unsigned int MASK = (rounds == 80 ? 7 : 15);
|
||||
for (int i=0; i<static_cast<int>(rounds); i+=4)
|
||||
{
|
||||
__m128i k, k1, k2, t1, t2;
|
||||
k = _mm_castpd_si128(_mm_load_sd(CONST_DOUBLE_CAST(&subkeys[(i+0) & MASK])));
|
||||
|
||||
// Shuffle out two subkeys
|
||||
k1 = _mm_shuffle_epi8(k, _mm_set_epi8(3,2,1,0, 3,2,1,0, 3,2,1,0, 3,2,1,0));
|
||||
k2 = _mm_shuffle_epi8(k, _mm_set_epi8(7,6,5,4, 7,6,5,4, 7,6,5,4, 7,6,5,4));
|
||||
|
||||
t1 = _mm_xor_si128(a, counter);
|
||||
t2 = _mm_xor_si128(RotateLeft32<1>(b), k1);
|
||||
a = RotateLeft32<8>(_mm_add_epi32(t1, t2));
|
||||
|
||||
counter = _mm_add_epi32(counter, increment);
|
||||
|
||||
t1 = _mm_xor_si128(b, counter);
|
||||
t2 = _mm_xor_si128(RotateLeft32<8>(c), k2);
|
||||
b = RotateLeft32<1>(_mm_add_epi32(t1, t2));
|
||||
|
||||
counter = _mm_add_epi32(counter, increment);
|
||||
k = _mm_castpd_si128(_mm_load_sd(CONST_DOUBLE_CAST(&subkeys[(i+2) & MASK])));
|
||||
|
||||
// Shuffle out two subkeys
|
||||
k1 = _mm_shuffle_epi8(k, _mm_set_epi8(3,2,1,0, 3,2,1,0, 3,2,1,0, 3,2,1,0));
|
||||
k2 = _mm_shuffle_epi8(k, _mm_set_epi8(7,6,5,4, 7,6,5,4, 7,6,5,4, 7,6,5,4));
|
||||
|
||||
t1 = _mm_xor_si128(c, counter);
|
||||
t2 = _mm_xor_si128(RotateLeft32<1>(d), k1);
|
||||
c = RotateLeft32<8>(_mm_add_epi32(t1, t2));
|
||||
|
||||
counter = _mm_add_epi32(counter, increment);
|
||||
|
||||
t1 = _mm_xor_si128(d, counter);
|
||||
t2 = _mm_xor_si128(RotateLeft32<8>(a), k2);
|
||||
d = RotateLeft32<1>(_mm_add_epi32(t1, t2));
|
||||
|
||||
counter = _mm_add_epi32(counter, increment);
|
||||
}
|
||||
|
||||
// [A1 B1 C1 D1][A2 B2 C2 D2] ... => [A1 A2 A3 A4][B1 B2 B3 B4] ...
|
||||
block0 = RepackXMM<0>(a,b,c,d);
|
||||
}
|
||||
|
||||
inline void CHAM128_Dec_Block(__m128i &block0,
|
||||
const word32 *subkeys, unsigned int rounds)
|
||||
{
|
||||
// Rearrange the data for vectorization. UnpackXMM includes a
|
||||
// little-endian swap for SSE. Thanks to Peter Cordes for help
|
||||
// with packing and unpacking.
|
||||
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 B1 C1 D1][A2 B2 C2 D2] ...
|
||||
__m128i a = UnpackXMM<0>(block0);
|
||||
__m128i b = UnpackXMM<1>(block0);
|
||||
__m128i c = UnpackXMM<2>(block0);
|
||||
__m128i d = UnpackXMM<3>(block0);
|
||||
|
||||
__m128i counter = _mm_set_epi32(rounds-1,rounds-1,rounds-1,rounds-1);
|
||||
__m128i decrement = _mm_set_epi32(1,1,1,1);
|
||||
|
||||
const unsigned int MASK = (rounds == 80 ? 7 : 15);
|
||||
for (int i = static_cast<int>(rounds)-1; i >= 0; i-=4)
|
||||
{
|
||||
__m128i k, k1, k2, t1, t2;
|
||||
k = _mm_castpd_si128(_mm_load_sd(CONST_DOUBLE_CAST(&subkeys[(i-1) & MASK])));
|
||||
|
||||
// Shuffle out two subkeys
|
||||
k1 = _mm_shuffle_epi8(k, _mm_set_epi8(7,6,5,4, 7,6,5,4, 7,6,5,4, 7,6,5,4));
|
||||
k2 = _mm_shuffle_epi8(k, _mm_set_epi8(3,2,1,0, 3,2,1,0, 3,2,1,0, 3,2,1,0));
|
||||
|
||||
// Odd round
|
||||
t1 = RotateRight32<1>(d);
|
||||
t2 = _mm_xor_si128(RotateLeft32<8>(a), k1);
|
||||
d = _mm_xor_si128(_mm_sub_epi32(t1, t2), counter);
|
||||
|
||||
counter = _mm_sub_epi32(counter, decrement);
|
||||
|
||||
// Even round
|
||||
t1 = RotateRight32<8>(c);
|
||||
t2 = _mm_xor_si128(RotateLeft32<1>(d), k2);
|
||||
c = _mm_xor_si128(_mm_sub_epi32(t1, t2), counter);
|
||||
|
||||
counter = _mm_sub_epi32(counter, decrement);
|
||||
k = _mm_castpd_si128(_mm_load_sd(CONST_DOUBLE_CAST(&subkeys[(i-3) & MASK])));
|
||||
|
||||
// Shuffle out two subkeys
|
||||
k1 = _mm_shuffle_epi8(k, _mm_set_epi8(7,6,5,4, 7,6,5,4, 7,6,5,4, 7,6,5,4));
|
||||
k2 = _mm_shuffle_epi8(k, _mm_set_epi8(3,2,1,0, 3,2,1,0, 3,2,1,0, 3,2,1,0));
|
||||
|
||||
// Odd round
|
||||
t1 = RotateRight32<1>(b);
|
||||
t2 = _mm_xor_si128(RotateLeft32<8>(c), k1);
|
||||
b = _mm_xor_si128(_mm_sub_epi32(t1, t2), counter);
|
||||
|
||||
counter = _mm_sub_epi32(counter, decrement);
|
||||
|
||||
// Even round
|
||||
t1 = RotateRight32<8>(a);
|
||||
t2 = _mm_xor_si128(RotateLeft32<1>(b), k2);
|
||||
a = _mm_xor_si128(_mm_sub_epi32(t1, t2), counter);
|
||||
|
||||
counter = _mm_sub_epi32(counter, decrement);
|
||||
}
|
||||
|
||||
// [A1 B1 C1 D1][A2 B2 C2 D2] ... => [A1 A2 A3 A4][B1 B2 B3 B4] ...
|
||||
block0 = RepackXMM<0>(a,b,c,d);
|
||||
}
|
||||
|
||||
inline void CHAM128_Enc_4_Blocks(__m128i &block0, __m128i &block1,
|
||||
__m128i &block2, __m128i &block3, const word32 *subkeys, unsigned int rounds)
|
||||
{
|
||||
// Rearrange the data for vectorization. UnpackXMM includes a
|
||||
// little-endian swap for SSE. Thanks to Peter Cordes for help
|
||||
// with packing and unpacking.
|
||||
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 B1 C1 D1][A2 B2 C2 D2] ...
|
||||
__m128i a = UnpackXMM<0>(block0, block1, block2, block3);
|
||||
__m128i b = UnpackXMM<1>(block0, block1, block2, block3);
|
||||
__m128i c = UnpackXMM<2>(block0, block1, block2, block3);
|
||||
__m128i d = UnpackXMM<3>(block0, block1, block2, block3);
|
||||
|
||||
__m128i counter = _mm_set_epi32(0,0,0,0);
|
||||
__m128i increment = _mm_set_epi32(1,1,1,1);
|
||||
|
||||
const unsigned int MASK = (rounds == 80 ? 7 : 15);
|
||||
for (int i=0; i<static_cast<int>(rounds); i+=4)
|
||||
{
|
||||
__m128i k, k1, k2, t1, t2;
|
||||
k = _mm_castpd_si128(_mm_load_sd(CONST_DOUBLE_CAST(&subkeys[(i+0) & MASK])));
|
||||
|
||||
// Shuffle out two subkeys
|
||||
k1 = _mm_shuffle_epi8(k, _mm_set_epi8(3,2,1,0, 3,2,1,0, 3,2,1,0, 3,2,1,0));
|
||||
k2 = _mm_shuffle_epi8(k, _mm_set_epi8(7,6,5,4, 7,6,5,4, 7,6,5,4, 7,6,5,4));
|
||||
|
||||
t1 = _mm_xor_si128(a, counter);
|
||||
t2 = _mm_xor_si128(RotateLeft32<1>(b), k1);
|
||||
a = RotateLeft32<8>(_mm_add_epi32(t1, t2));
|
||||
|
||||
counter = _mm_add_epi32(counter, increment);
|
||||
|
||||
t1 = _mm_xor_si128(b, counter);
|
||||
t2 = _mm_xor_si128(RotateLeft32<8>(c), k2);
|
||||
b = RotateLeft32<1>(_mm_add_epi32(t1, t2));
|
||||
|
||||
counter = _mm_add_epi32(counter, increment);
|
||||
k = _mm_castpd_si128(_mm_load_sd(CONST_DOUBLE_CAST(&subkeys[(i+2) & MASK])));
|
||||
|
||||
// Shuffle out two subkeys
|
||||
k1 = _mm_shuffle_epi8(k, _mm_set_epi8(3,2,1,0, 3,2,1,0, 3,2,1,0, 3,2,1,0));
|
||||
k2 = _mm_shuffle_epi8(k, _mm_set_epi8(7,6,5,4, 7,6,5,4, 7,6,5,4, 7,6,5,4));
|
||||
|
||||
t1 = _mm_xor_si128(c, counter);
|
||||
t2 = _mm_xor_si128(RotateLeft32<1>(d), k1);
|
||||
c = RotateLeft32<8>(_mm_add_epi32(t1, t2));
|
||||
|
||||
counter = _mm_add_epi32(counter, increment);
|
||||
|
||||
t1 = _mm_xor_si128(d, counter);
|
||||
t2 = _mm_xor_si128(RotateLeft32<8>(a), k2);
|
||||
d = RotateLeft32<1>(_mm_add_epi32(t1, t2));
|
||||
|
||||
counter = _mm_add_epi32(counter, increment);
|
||||
}
|
||||
|
||||
// [A1 B1 C1 D1][A2 B2 C2 D2] ... => [A1 A2 A3 A4][B1 B2 B3 B4] ...
|
||||
block0 = RepackXMM<0>(a,b,c,d);
|
||||
block1 = RepackXMM<1>(a,b,c,d);
|
||||
block2 = RepackXMM<2>(a,b,c,d);
|
||||
block3 = RepackXMM<3>(a,b,c,d);
|
||||
}
|
||||
|
||||
inline void CHAM128_Dec_4_Blocks(__m128i &block0, __m128i &block1,
|
||||
__m128i &block2, __m128i &block3, const word32 *subkeys, unsigned int rounds)
|
||||
{
|
||||
// Rearrange the data for vectorization. UnpackXMM includes a
|
||||
// little-endian swap for SSE. Thanks to Peter Cordes for help
|
||||
// with packing and unpacking.
|
||||
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 B1 C1 D1][A2 B2 C2 D2] ...
|
||||
__m128i a = UnpackXMM<0>(block0, block1, block2, block3);
|
||||
__m128i b = UnpackXMM<1>(block0, block1, block2, block3);
|
||||
__m128i c = UnpackXMM<2>(block0, block1, block2, block3);
|
||||
__m128i d = UnpackXMM<3>(block0, block1, block2, block3);
|
||||
|
||||
__m128i counter = _mm_set_epi32(rounds-1,rounds-1,rounds-1,rounds-1);
|
||||
__m128i decrement = _mm_set_epi32(1,1,1,1);
|
||||
|
||||
const unsigned int MASK = (rounds == 80 ? 7 : 15);
|
||||
for (int i = static_cast<int>(rounds)-1; i >= 0; i-=4)
|
||||
{
|
||||
__m128i k, k1, k2, t1, t2;
|
||||
k = _mm_castpd_si128(_mm_load_sd(CONST_DOUBLE_CAST(&subkeys[(i-1) & MASK])));
|
||||
|
||||
// Shuffle out two subkeys
|
||||
k1 = _mm_shuffle_epi8(k, _mm_set_epi8(7,6,5,4, 7,6,5,4, 7,6,5,4, 7,6,5,4));
|
||||
k2 = _mm_shuffle_epi8(k, _mm_set_epi8(3,2,1,0, 3,2,1,0, 3,2,1,0, 3,2,1,0));
|
||||
|
||||
// Odd round
|
||||
t1 = RotateRight32<1>(d);
|
||||
t2 = _mm_xor_si128(RotateLeft32<8>(a), k1);
|
||||
d = _mm_xor_si128(_mm_sub_epi32(t1, t2), counter);
|
||||
|
||||
counter = _mm_sub_epi32(counter, decrement);
|
||||
|
||||
// Even round
|
||||
t1 = RotateRight32<8>(c);
|
||||
t2 = _mm_xor_si128(RotateLeft32<1>(d), k2);
|
||||
c = _mm_xor_si128(_mm_sub_epi32(t1, t2), counter);
|
||||
|
||||
counter = _mm_sub_epi32(counter, decrement);
|
||||
k = _mm_castpd_si128(_mm_load_sd(CONST_DOUBLE_CAST(&subkeys[(i-3) & MASK])));
|
||||
|
||||
// Shuffle out two subkeys
|
||||
k1 = _mm_shuffle_epi8(k, _mm_set_epi8(7,6,5,4, 7,6,5,4, 7,6,5,4, 7,6,5,4));
|
||||
k2 = _mm_shuffle_epi8(k, _mm_set_epi8(3,2,1,0, 3,2,1,0, 3,2,1,0, 3,2,1,0));
|
||||
|
||||
// Odd round
|
||||
t1 = RotateRight32<1>(b);
|
||||
t2 = _mm_xor_si128(RotateLeft32<8>(c), k1);
|
||||
b = _mm_xor_si128(_mm_sub_epi32(t1, t2), counter);
|
||||
|
||||
counter = _mm_sub_epi32(counter, decrement);
|
||||
|
||||
// Even round
|
||||
t1 = RotateRight32<8>(a);
|
||||
t2 = _mm_xor_si128(RotateLeft32<1>(b), k2);
|
||||
a = _mm_xor_si128(_mm_sub_epi32(t1, t2), counter);
|
||||
|
||||
counter = _mm_sub_epi32(counter, decrement);
|
||||
}
|
||||
|
||||
// [A1 B1 C1 D1][A2 B2 C2 D2] ... => [A1 A2 A3 A4][B1 B2 B3 B4] ...
|
||||
block0 = RepackXMM<0>(a,b,c,d);
|
||||
block1 = RepackXMM<1>(a,b,c,d);
|
||||
block2 = RepackXMM<2>(a,b,c,d);
|
||||
block3 = RepackXMM<3>(a,b,c,d);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
NAMESPACE_END // W32
|
||||
|
||||
#endif // CRYPTOPP_SSSE3_AVAILABLE
|
||||
|
||||
ANONYMOUS_NAMESPACE_END
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
#if defined(CRYPTOPP_SSSE3_AVAILABLE)
|
||||
size_t CHAM128_Enc_AdvancedProcessBlocks_SSSE3(const word32* subKeys, size_t rounds,
|
||||
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags)
|
||||
{
|
||||
return AdvancedProcessBlocks128_4x1_SSE(W32::CHAM128_Enc_Block, W32::CHAM128_Enc_4_Blocks,
|
||||
subKeys, rounds, inBlocks, xorBlocks, outBlocks, length, flags);
|
||||
}
|
||||
|
||||
size_t CHAM128_Dec_AdvancedProcessBlocks_SSSE3(const word32* subKeys, size_t rounds,
|
||||
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags)
|
||||
{
|
||||
return AdvancedProcessBlocks128_4x1_SSE(W32::CHAM128_Dec_Block, W32::CHAM128_Dec_4_Blocks,
|
||||
subKeys, rounds, inBlocks, xorBlocks, outBlocks, length, flags);
|
||||
}
|
||||
#endif // CRYPTOPP_SSSE3_AVAILABLE
|
||||
|
||||
NAMESPACE_END
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
// channels.cpp - originally written and placed in the public domain by Wei Dai
|
||||
// CryptoPP::Test namespace added by JW in February 2017
|
||||
|
||||
#include "pch.h"
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "channels.h"
|
||||
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(disable: 4355)
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
#if 0
|
||||
void MessageSwitch::AddDefaultRoute(BufferedTransformation &destination, const std::string &channel)
|
||||
{
|
||||
m_defaultRoutes.push_back(Route(&destination, channel));
|
||||
}
|
||||
|
||||
void MessageSwitch::AddRoute(unsigned int begin, unsigned int end, BufferedTransformation &destination, const std::string &channel)
|
||||
{
|
||||
RangeRoute route(begin, end, Route(&destination, channel));
|
||||
RouteList::iterator it = upper_bound(m_routes.begin(), m_routes.end(), route);
|
||||
m_routes.insert(it, route);
|
||||
}
|
||||
|
||||
/*
|
||||
class MessageRouteIterator
|
||||
{
|
||||
public:
|
||||
typedef MessageSwitch::RouteList::const_iterator RouteIterator;
|
||||
typedef MessageSwitch::DefaultRouteList::const_iterator DefaultIterator;
|
||||
|
||||
bool m_useDefault;
|
||||
RouteIterator m_itRouteCurrent, m_itRouteEnd;
|
||||
DefaultIterator m_itDefaultCurrent, m_itDefaultEnd;
|
||||
|
||||
MessageRouteIterator(MessageSwitch &ms, const std::string &channel)
|
||||
: m_channel(channel)
|
||||
{
|
||||
std::pair<MapIterator, MapIterator> range = cs.m_routeMap.equal_range(channel);
|
||||
if (range.first == range.second)
|
||||
{
|
||||
m_useDefault = true;
|
||||
m_itListCurrent = cs.m_defaultRoutes.begin();
|
||||
m_itListEnd = cs.m_defaultRoutes.end();
|
||||
}
|
||||
else
|
||||
{
|
||||
m_useDefault = false;
|
||||
m_itMapCurrent = range.first;
|
||||
m_itMapEnd = range.second;
|
||||
}
|
||||
}
|
||||
|
||||
bool End() const
|
||||
{
|
||||
return m_useDefault ? m_itListCurrent == m_itListEnd : m_itMapCurrent == m_itMapEnd;
|
||||
}
|
||||
|
||||
void Next()
|
||||
{
|
||||
if (m_useDefault)
|
||||
++m_itListCurrent;
|
||||
else
|
||||
++m_itMapCurrent;
|
||||
}
|
||||
|
||||
BufferedTransformation & Destination()
|
||||
{
|
||||
return m_useDefault ? *m_itListCurrent->first : *m_itMapCurrent->second.first;
|
||||
}
|
||||
|
||||
const std::string & Message()
|
||||
{
|
||||
if (m_useDefault)
|
||||
return m_itListCurrent->second.get() ? *m_itListCurrent->second.get() : m_channel;
|
||||
else
|
||||
return m_itMapCurrent->second.second;
|
||||
}
|
||||
};
|
||||
|
||||
void MessageSwitch::Put(byte inByte);
|
||||
void MessageSwitch::Put(const byte *inString, unsigned int length);
|
||||
|
||||
void MessageSwitch::Flush(bool completeFlush, int propagation=-1);
|
||||
void MessageSwitch::MessageEnd(int propagation=-1);
|
||||
void MessageSwitch::PutMessageEnd(const byte *inString, unsigned int length, int propagation=-1);
|
||||
void MessageSwitch::MessageSeriesEnd(int propagation=-1);
|
||||
*/
|
||||
#endif
|
||||
|
||||
|
||||
//
|
||||
// ChannelRouteIterator
|
||||
//////////////////////////
|
||||
|
||||
void ChannelRouteIterator::Reset(const std::string &channel)
|
||||
{
|
||||
m_channel = channel;
|
||||
std::pair<MapIterator, MapIterator> range = m_cs.m_routeMap.equal_range(channel);
|
||||
if (range.first == range.second)
|
||||
{
|
||||
m_useDefault = true;
|
||||
m_itListCurrent = m_cs.m_defaultRoutes.begin();
|
||||
m_itListEnd = m_cs.m_defaultRoutes.end();
|
||||
}
|
||||
else
|
||||
{
|
||||
m_useDefault = false;
|
||||
m_itMapCurrent = range.first;
|
||||
m_itMapEnd = range.second;
|
||||
}
|
||||
}
|
||||
|
||||
bool ChannelRouteIterator::End() const
|
||||
{
|
||||
return m_useDefault ? m_itListCurrent == m_itListEnd : m_itMapCurrent == m_itMapEnd;
|
||||
}
|
||||
|
||||
void ChannelRouteIterator::Next()
|
||||
{
|
||||
if (m_useDefault)
|
||||
++m_itListCurrent;
|
||||
else
|
||||
++m_itMapCurrent;
|
||||
}
|
||||
|
||||
BufferedTransformation & ChannelRouteIterator::Destination()
|
||||
{
|
||||
return m_useDefault ? *m_itListCurrent->first : *m_itMapCurrent->second.first;
|
||||
}
|
||||
|
||||
const std::string & ChannelRouteIterator::Channel()
|
||||
{
|
||||
if (m_useDefault)
|
||||
return m_itListCurrent->second.get() ? *m_itListCurrent->second.get() : m_channel;
|
||||
else
|
||||
return m_itMapCurrent->second.second;
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// ChannelSwitch
|
||||
///////////////////
|
||||
|
||||
size_t ChannelSwitch::ChannelPut2(const std::string &channel, const byte *begin, size_t length, int messageEnd, bool blocking)
|
||||
{
|
||||
if (m_blocked)
|
||||
{
|
||||
m_blocked = false;
|
||||
goto WasBlocked;
|
||||
}
|
||||
|
||||
m_it.Reset(channel);
|
||||
|
||||
while (!m_it.End())
|
||||
{
|
||||
WasBlocked:
|
||||
if (m_it.Destination().ChannelPut2(m_it.Channel(), begin, length, messageEnd, blocking))
|
||||
{
|
||||
m_blocked = true;
|
||||
return 1;
|
||||
}
|
||||
|
||||
m_it.Next();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ChannelSwitch::IsolatedInitialize(const NameValuePairs& parameters)
|
||||
{
|
||||
CRYPTOPP_UNUSED(parameters);
|
||||
m_routeMap.clear();
|
||||
m_defaultRoutes.clear();
|
||||
m_blocked = false;
|
||||
}
|
||||
|
||||
bool ChannelSwitch::ChannelFlush(const std::string &channel, bool completeFlush, int propagation, bool blocking)
|
||||
{
|
||||
if (m_blocked)
|
||||
{
|
||||
m_blocked = false;
|
||||
goto WasBlocked;
|
||||
}
|
||||
|
||||
m_it.Reset(channel);
|
||||
|
||||
while (!m_it.End())
|
||||
{
|
||||
WasBlocked:
|
||||
if (m_it.Destination().ChannelFlush(m_it.Channel(), completeFlush, propagation, blocking))
|
||||
{
|
||||
m_blocked = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
m_it.Next();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ChannelSwitch::ChannelMessageSeriesEnd(const std::string &channel, int propagation, bool blocking)
|
||||
{
|
||||
CRYPTOPP_UNUSED(blocking);
|
||||
if (m_blocked)
|
||||
{
|
||||
m_blocked = false;
|
||||
goto WasBlocked;
|
||||
}
|
||||
|
||||
m_it.Reset(channel);
|
||||
|
||||
while (!m_it.End())
|
||||
{
|
||||
WasBlocked:
|
||||
if (m_it.Destination().ChannelMessageSeriesEnd(m_it.Channel(), propagation))
|
||||
{
|
||||
m_blocked = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
m_it.Next();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
byte * ChannelSwitch::ChannelCreatePutSpace(const std::string &channel, size_t &size)
|
||||
{
|
||||
m_it.Reset(channel);
|
||||
if (!m_it.End())
|
||||
{
|
||||
BufferedTransformation &target = m_it.Destination();
|
||||
const std::string &ch = m_it.Channel();
|
||||
m_it.Next();
|
||||
if (m_it.End()) // there is only one target channel
|
||||
return target.ChannelCreatePutSpace(ch, size);
|
||||
}
|
||||
size = 0;
|
||||
return NULLPTR;
|
||||
}
|
||||
|
||||
size_t ChannelSwitch::ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking)
|
||||
{
|
||||
ChannelRouteIterator it(*this);
|
||||
it.Reset(channel);
|
||||
|
||||
if (!it.End())
|
||||
{
|
||||
BufferedTransformation &target = it.Destination();
|
||||
const std::string &targetChannel = it.Channel();
|
||||
it.Next();
|
||||
if (it.End()) // there is only one target channel
|
||||
return target.ChannelPutModifiable2(targetChannel, inString, length, messageEnd, blocking);
|
||||
}
|
||||
|
||||
return ChannelPut2(channel, inString, length, messageEnd, blocking);
|
||||
}
|
||||
|
||||
void ChannelSwitch::AddDefaultRoute(BufferedTransformation &destination)
|
||||
{
|
||||
m_defaultRoutes.push_back(DefaultRoute(&destination, value_ptr<std::string>(NULLPTR)));
|
||||
}
|
||||
|
||||
void ChannelSwitch::RemoveDefaultRoute(BufferedTransformation &destination)
|
||||
{
|
||||
for (DefaultRouteList::iterator it = m_defaultRoutes.begin(); it != m_defaultRoutes.end(); ++it)
|
||||
if (it->first == &destination && !it->second.get())
|
||||
{
|
||||
m_defaultRoutes.erase(it);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ChannelSwitch::AddDefaultRoute(BufferedTransformation &destination, const std::string &outChannel)
|
||||
{
|
||||
m_defaultRoutes.push_back(DefaultRoute(&destination, outChannel));
|
||||
}
|
||||
|
||||
void ChannelSwitch::RemoveDefaultRoute(BufferedTransformation &destination, const std::string &outChannel)
|
||||
{
|
||||
for (DefaultRouteList::iterator it = m_defaultRoutes.begin(); it != m_defaultRoutes.end(); ++it)
|
||||
if (it->first == &destination && (it->second.get() && *it->second == outChannel))
|
||||
{
|
||||
m_defaultRoutes.erase(it);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ChannelSwitch::AddRoute(const std::string &inChannel, BufferedTransformation &destination, const std::string &outChannel)
|
||||
{
|
||||
m_routeMap.insert(RouteMap::value_type(inChannel, Route(&destination, outChannel)));
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
for (MapIterator it = range.first; it != range.second; ++it)
|
||||
if (it->second.first == &destination && it->second.second == outChannel)
|
||||
{
|
||||
m_routeMap.erase(it);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
// channels.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file channels.h
|
||||
/// \brief Classes for multiple named channels
|
||||
|
||||
#ifndef CRYPTOPP_CHANNELS_H
|
||||
#define CRYPTOPP_CHANNELS_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "simple.h"
|
||||
#include "smartptr.h"
|
||||
#include "stdcpp.h"
|
||||
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable: 4355)
|
||||
#endif
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
#if 0
|
||||
/// Route input on default channel to different and/or multiple channels based on message sequence number
|
||||
class MessageSwitch : public Sink
|
||||
{
|
||||
public:
|
||||
void AddDefaultRoute(BufferedTransformation &destination, const std::string &channel);
|
||||
void AddRoute(unsigned int begin, unsigned int end, BufferedTransformation &destination, const std::string &channel);
|
||||
|
||||
void Put(byte inByte);
|
||||
void Put(const byte *inString, unsigned int length);
|
||||
|
||||
void Flush(bool completeFlush, int propagation=-1);
|
||||
void MessageEnd(int propagation=-1);
|
||||
void PutMessageEnd(const byte *inString, unsigned int length, int propagation=-1);
|
||||
void MessageSeriesEnd(int propagation=-1);
|
||||
|
||||
private:
|
||||
typedef std::pair<BufferedTransformation *, std::string> Route;
|
||||
struct RangeRoute
|
||||
{
|
||||
RangeRoute(unsigned int begin, unsigned int end, const Route &route)
|
||||
: begin(begin), end(end), route(route) {}
|
||||
bool operator<(const RangeRoute &rhs) const {return begin < rhs.begin;}
|
||||
unsigned int begin, end;
|
||||
Route route;
|
||||
};
|
||||
|
||||
typedef std::list<RangeRoute> RouteList;
|
||||
typedef std::list<Route> DefaultRouteList;
|
||||
|
||||
RouteList m_routes;
|
||||
DefaultRouteList m_defaultRoutes;
|
||||
unsigned int m_nCurrentMessage;
|
||||
};
|
||||
#endif
|
||||
|
||||
class ChannelSwitchTypedefs
|
||||
{
|
||||
public:
|
||||
typedef std::pair<BufferedTransformation *, std::string> Route;
|
||||
typedef std::multimap<std::string, Route> RouteMap;
|
||||
|
||||
typedef std::pair<BufferedTransformation *, value_ptr<std::string> > DefaultRoute;
|
||||
typedef std::list<DefaultRoute> DefaultRouteList;
|
||||
|
||||
// SunCC workaround: can't use const_iterator here
|
||||
typedef RouteMap::iterator MapIterator;
|
||||
typedef DefaultRouteList::iterator ListIterator;
|
||||
};
|
||||
|
||||
class ChannelSwitch;
|
||||
|
||||
class ChannelRouteIterator : public ChannelSwitchTypedefs
|
||||
{
|
||||
public:
|
||||
ChannelRouteIterator(ChannelSwitch &cs) : m_cs(cs), m_useDefault(false) {}
|
||||
|
||||
void Reset(const std::string &channel);
|
||||
bool End() const;
|
||||
void Next();
|
||||
BufferedTransformation & Destination();
|
||||
const std::string & Channel();
|
||||
|
||||
ChannelSwitch& m_cs;
|
||||
std::string m_channel;
|
||||
bool m_useDefault;
|
||||
MapIterator m_itMapCurrent, m_itMapEnd;
|
||||
ListIterator m_itListCurrent, m_itListEnd;
|
||||
|
||||
protected:
|
||||
// Hide this to see if we break something...
|
||||
ChannelRouteIterator();
|
||||
};
|
||||
|
||||
/// Route input to different and/or multiple channels based on channel ID
|
||||
class CRYPTOPP_DLL ChannelSwitch : public Multichannel<Sink>, public ChannelSwitchTypedefs
|
||||
{
|
||||
public:
|
||||
ChannelSwitch() : m_it(*this), m_blocked(false) {}
|
||||
ChannelSwitch(BufferedTransformation &destination) : m_it(*this), m_blocked(false)
|
||||
{
|
||||
AddDefaultRoute(destination);
|
||||
}
|
||||
ChannelSwitch(BufferedTransformation &destination, const std::string &outChannel) : m_it(*this), m_blocked(false)
|
||||
{
|
||||
AddDefaultRoute(destination, outChannel);
|
||||
}
|
||||
|
||||
void IsolatedInitialize(const NameValuePairs ¶meters=g_nullNameValuePairs);
|
||||
|
||||
size_t ChannelPut2(const std::string &channel, const byte *begin, size_t length, int messageEnd, bool blocking);
|
||||
size_t ChannelPutModifiable2(const std::string &channel, byte *begin, size_t length, int messageEnd, bool blocking);
|
||||
|
||||
bool ChannelFlush(const std::string &channel, bool completeFlush, int propagation=-1, bool blocking=true);
|
||||
bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
|
||||
|
||||
byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
|
||||
|
||||
void AddDefaultRoute(BufferedTransformation &destination);
|
||||
void RemoveDefaultRoute(BufferedTransformation &destination);
|
||||
void AddDefaultRoute(BufferedTransformation &destination, const std::string &outChannel);
|
||||
void RemoveDefaultRoute(BufferedTransformation &destination, const std::string &outChannel);
|
||||
void AddRoute(const std::string &inChannel, BufferedTransformation &destination, const std::string &outChannel);
|
||||
void RemoveRoute(const std::string &inChannel, BufferedTransformation &destination, const std::string &outChannel);
|
||||
|
||||
private:
|
||||
RouteMap m_routeMap;
|
||||
DefaultRouteList m_defaultRoutes;
|
||||
|
||||
ChannelRouteIterator m_it;
|
||||
bool m_blocked;
|
||||
|
||||
friend class ChannelRouteIterator;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
|
||||
#endif
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
// cmac.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
#include "cmac.h"
|
||||
#include "misc.h"
|
||||
|
||||
ANONYMOUS_NAMESPACE_BEGIN
|
||||
|
||||
using CryptoPP::byte;
|
||||
using CryptoPP::IsPowerOf2;
|
||||
|
||||
void MulU(byte *k, unsigned int len)
|
||||
{
|
||||
byte carry = 0;
|
||||
for (int i=len-1; i>=1; i-=2)
|
||||
{
|
||||
byte carry2 = k[i] >> 7;
|
||||
k[i] += k[i] + carry;
|
||||
carry = k[i-1] >> 7;
|
||||
k[i-1] += k[i-1] + carry2;
|
||||
}
|
||||
|
||||
#ifndef CRYPTOPP_CMAC_WIDE_BLOCK_CIPHERS
|
||||
CRYPTOPP_ASSERT(len == 16);
|
||||
|
||||
if (carry)
|
||||
{
|
||||
k[15] ^= 0x87;
|
||||
return;
|
||||
}
|
||||
#else
|
||||
CRYPTOPP_ASSERT(IsPowerOf2(len));
|
||||
CRYPTOPP_ASSERT(len >= 8);
|
||||
CRYPTOPP_ASSERT(len <= 128);
|
||||
|
||||
if (carry)
|
||||
{
|
||||
switch (len)
|
||||
{
|
||||
case 8:
|
||||
k[7] ^= 0x1b;
|
||||
break;
|
||||
case 16:
|
||||
k[15] ^= 0x87;
|
||||
break;
|
||||
case 32:
|
||||
// https://crypto.stackexchange.com/q/9815/10496
|
||||
// Polynomial x^256 + x^10 + x^5 + x^2 + 1
|
||||
k[30] ^= 4;
|
||||
k[31] ^= 0x25;
|
||||
break;
|
||||
case 64:
|
||||
// https://crypto.stackexchange.com/q/9815/10496
|
||||
// Polynomial x^512 + x^8 + x^5 + x^2 + 1
|
||||
k[62] ^= 1;
|
||||
k[63] ^= 0x25;
|
||||
break;
|
||||
case 128:
|
||||
// https://crypto.stackexchange.com/q/9815/10496
|
||||
// Polynomial x^1024 + x^19 + x^6 + x + 1
|
||||
k[125] ^= 8;
|
||||
k[126] ^= 0x00;
|
||||
k[127] ^= 0x43;
|
||||
break;
|
||||
default:
|
||||
CRYPTOPP_ASSERT(0);
|
||||
}
|
||||
}
|
||||
#endif // CRYPTOPP_CMAC_WIDE_BLOCK_CIPHERS
|
||||
}
|
||||
|
||||
ANONYMOUS_NAMESPACE_END
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
void CMAC_Base::UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms)
|
||||
{
|
||||
BlockCipher &cipher = AccessCipher();
|
||||
cipher.SetKey(key, length, params);
|
||||
|
||||
unsigned int blockSize = cipher.BlockSize();
|
||||
m_reg.CleanNew(3*blockSize);
|
||||
m_counter = 0;
|
||||
|
||||
cipher.ProcessBlock(m_reg, m_reg+blockSize);
|
||||
MulU(m_reg+blockSize, blockSize);
|
||||
memcpy(m_reg+2*blockSize, m_reg+blockSize, blockSize);
|
||||
MulU(m_reg+2*blockSize, blockSize);
|
||||
}
|
||||
|
||||
void CMAC_Base::Update(const byte *input, size_t length)
|
||||
{
|
||||
CRYPTOPP_ASSERT((input && length) || !(input || length));
|
||||
if (!length)
|
||||
return;
|
||||
|
||||
BlockCipher &cipher = AccessCipher();
|
||||
unsigned int blockSize = cipher.BlockSize();
|
||||
|
||||
if (m_counter > 0)
|
||||
{
|
||||
const unsigned int len = UnsignedMin(blockSize - m_counter, length);
|
||||
if (len)
|
||||
{
|
||||
xorbuf(m_reg+m_counter, input, len);
|
||||
length -= len;
|
||||
input += len;
|
||||
m_counter += len;
|
||||
}
|
||||
|
||||
if (m_counter == blockSize && length > 0)
|
||||
{
|
||||
cipher.ProcessBlock(m_reg);
|
||||
m_counter = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (length > blockSize)
|
||||
{
|
||||
CRYPTOPP_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;
|
||||
}
|
||||
|
||||
if (length > 0)
|
||||
{
|
||||
CRYPTOPP_ASSERT(m_counter + length <= blockSize);
|
||||
xorbuf(m_reg+m_counter, input, length);
|
||||
m_counter += (unsigned int)length;
|
||||
}
|
||||
|
||||
CRYPTOPP_ASSERT(m_counter > 0);
|
||||
}
|
||||
|
||||
void CMAC_Base::TruncatedFinal(byte *mac, size_t size)
|
||||
{
|
||||
ThrowIfInvalidTruncatedSize(size);
|
||||
|
||||
BlockCipher &cipher = AccessCipher();
|
||||
unsigned int blockSize = cipher.BlockSize();
|
||||
|
||||
if (m_counter < blockSize)
|
||||
{
|
||||
m_reg[m_counter] ^= 0x80;
|
||||
cipher.AdvancedProcessBlocks(m_reg, m_reg+2*blockSize, m_reg, blockSize, BlockTransformation::BT_DontIncrementInOutPointers|BlockTransformation::BT_XorInput);
|
||||
}
|
||||
else
|
||||
cipher.AdvancedProcessBlocks(m_reg, m_reg+blockSize, m_reg, blockSize, BlockTransformation::BT_DontIncrementInOutPointers|BlockTransformation::BT_XorInput);
|
||||
|
||||
memcpy(mac, m_reg, size);
|
||||
|
||||
m_counter = 0;
|
||||
memset(m_reg, 0, blockSize);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
// cmac.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file cmac.h
|
||||
/// \brief Classes for CMAC message authentication code
|
||||
/// \since Crypto++ 5.6.0
|
||||
|
||||
#ifndef CRYPTOPP_CMAC_H
|
||||
#define CRYPTOPP_CMAC_H
|
||||
|
||||
#include "seckey.h"
|
||||
#include "secblock.h"
|
||||
|
||||
/// \brief Enable CMAC and wide block ciphers
|
||||
/// \details CMAC is only defined for AES. The library can support wide
|
||||
/// block ciphers like Kaylna and Threefish since we know the polynomials.
|
||||
#ifndef CRYPTOPP_CMAC_WIDE_BLOCK_CIPHERS
|
||||
# define CRYPTOPP_CMAC_WIDE_BLOCK_CIPHERS 1
|
||||
#endif // CRYPTOPP_CMAC_WIDE_BLOCK_CIPHERS
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief CMAC base implementation
|
||||
/// \since Crypto++ 5.6.0
|
||||
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CMAC_Base : public MessageAuthenticationCode
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~CMAC_Base() {}
|
||||
CMAC_Base() : m_counter(0) {}
|
||||
|
||||
void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms);
|
||||
void Update(const byte *input, size_t length);
|
||||
void TruncatedFinal(byte *mac, size_t size);
|
||||
unsigned int DigestSize() const {return GetCipher().BlockSize();}
|
||||
unsigned int OptimalBlockSize() const {return GetCipher().BlockSize();}
|
||||
unsigned int OptimalDataAlignment() const {return GetCipher().OptimalDataAlignment();}
|
||||
std::string AlgorithmProvider() const {return GetCipher().AlgorithmProvider();}
|
||||
|
||||
protected:
|
||||
friend class EAX_Base;
|
||||
|
||||
const BlockCipher & GetCipher() const {return const_cast<CMAC_Base*>(this)->AccessCipher();}
|
||||
virtual BlockCipher & AccessCipher() =0;
|
||||
|
||||
void ProcessBuf();
|
||||
SecByteBlock m_reg;
|
||||
unsigned int m_counter;
|
||||
};
|
||||
|
||||
/// \brief CMAC message authentication code
|
||||
/// \tparam T block cipher
|
||||
/// \details Template parameter T should be a class derived from BlockCipherDocumentation, for example AES, with a block size of 8, 16, or 32.
|
||||
/// \sa <a href="http://www.cryptolounge.org/wiki/CMAC">CMAC</a>
|
||||
/// \since Crypto++ 5.6.0
|
||||
template <class T>
|
||||
class CMAC : public MessageAuthenticationCodeImpl<CMAC_Base, CMAC<T> >, public SameKeyLengthAs<T>
|
||||
{
|
||||
public:
|
||||
/// \brief Construct a CMAC
|
||||
CMAC() {}
|
||||
/// \brief Construct a CMAC
|
||||
/// \param key the MAC key
|
||||
/// \param length the key size, in bytes
|
||||
CMAC(const byte *key, size_t length=SameKeyLengthAs<T>::DEFAULT_KEYLENGTH)
|
||||
{this->SetKey(key, length);}
|
||||
|
||||
static std::string StaticAlgorithmName() {return std::string("CMAC(") + T::StaticAlgorithmName() + ")";}
|
||||
|
||||
private:
|
||||
BlockCipher & AccessCipher() {return m_cipher;}
|
||||
typename T::Encryption m_cipher;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
// config.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file config.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>
|
||||
/// on the Crypto++ wiki
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
/// \file config.h
|
||||
/// \brief Library configuration file
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_H
|
||||
#define CRYPTOPP_CONFIG_H
|
||||
|
||||
#include "config_align.h"
|
||||
#include "config_asm.h"
|
||||
#include "config_cpu.h"
|
||||
#include "config_cxx.h"
|
||||
#include "config_dll.h"
|
||||
#include "config_int.h"
|
||||
#include "config_misc.h"
|
||||
#include "config_ns.h"
|
||||
#include "config_os.h"
|
||||
#include "config_ver.h"
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_H
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
// config_align.h - written and placed in public domain by Jeffrey Walton
|
||||
// the bits that make up this source file are from the
|
||||
// library's monolithic config.h.
|
||||
|
||||
/// \file config_align.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config_align.h</tt> provides defines for aligned memory
|
||||
/// allocations.
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \note You should include <tt>config.h</tt> rather than <tt>config_align.h</tt>
|
||||
/// directly.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>
|
||||
/// on the Crypto++ wiki
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_ALIGN_H
|
||||
#define CRYPTOPP_CONFIG_ALIGN_H
|
||||
|
||||
#include "config_asm.h" // CRYPTOPP_DISABLE_ASM
|
||||
#include "config_cpu.h" // X86, X32, X64, ARM32, ARM64, etc
|
||||
#include "config_cxx.h" // CRYPTOPP_CXX11_ALIGNAS
|
||||
#include "config_ver.h" // Compiler versions
|
||||
|
||||
// Nearly all Intel's and AMD's have SSE. Enable it independent of SSE ASM and intrinsics.
|
||||
// ARM NEON and ARMv8 ASIMD only need natural alignment of an element in the vector.
|
||||
// Altivec through POWER7 need vector alignment. POWER8 and POWER9 relax the requirement.
|
||||
#if defined(CRYPTOPP_DISABLE_ASM)
|
||||
#define CRYPTOPP_BOOL_ALIGN16 0
|
||||
#elif (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64 || \
|
||||
CRYPTOPP_BOOL_PPC32 || CRYPTOPP_BOOL_PPC64)
|
||||
#define CRYPTOPP_BOOL_ALIGN16 1
|
||||
#else
|
||||
#define CRYPTOPP_BOOL_ALIGN16 0
|
||||
#endif
|
||||
|
||||
// How to allocate 16-byte aligned memory (for SSE2)
|
||||
// posix_memalign see https://forum.kde.org/viewtopic.php?p=66274
|
||||
#if defined(_MSC_VER)
|
||||
#define CRYPTOPP_MM_MALLOC_AVAILABLE
|
||||
#elif defined(__linux__) || defined(__sun__) || defined(__CYGWIN__)
|
||||
#define CRYPTOPP_MEMALIGN_AVAILABLE
|
||||
#elif defined(__APPLE__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
|
||||
#define CRYPTOPP_MALLOC_ALIGNMENT_IS_16
|
||||
#elif (defined(_GNU_SOURCE) || ((_XOPEN_SOURCE + 0) >= 600)) && (_POSIX_ADVISORY_INFO > 0)
|
||||
#define CRYPTOPP_POSIX_MEMALIGN_AVAILABLE
|
||||
#else
|
||||
#define CRYPTOPP_NO_ALIGNED_ALLOC
|
||||
#endif
|
||||
|
||||
// Sun Studio Express 3 (December 2006) provides GCC-style attributes.
|
||||
// IBM XL C/C++ alignment modifier per Optimization Guide, pp. 19-20.
|
||||
// __IBM_ATTRIBUTES per XLC 12.1 AIX Compiler Manual, p. 473.
|
||||
// CRYPTOPP_ALIGN_DATA may not be reliable on AIX.
|
||||
#if defined(CRYPTOPP_CXX11_ALIGNAS)
|
||||
#define CRYPTOPP_ALIGN_DATA(x) alignas(x)
|
||||
#elif defined(_MSC_VER)
|
||||
#define CRYPTOPP_ALIGN_DATA(x) __declspec(align(x))
|
||||
#elif defined(__GNUC__) || defined(__clang__) || (__SUNPRO_CC >= 0x5100)
|
||||
#define CRYPTOPP_ALIGN_DATA(x) __attribute__((aligned(x)))
|
||||
#elif defined(__xlc__) || defined(__xlC__)
|
||||
#define CRYPTOPP_ALIGN_DATA(x) __attribute__((aligned(x)))
|
||||
#else
|
||||
#define CRYPTOPP_ALIGN_DATA(x)
|
||||
#endif
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_ALIGN_H
|
||||
+470
@@ -0,0 +1,470 @@
|
||||
// config_asm.h - written and placed in public domain by Jeffrey Walton
|
||||
// the bits that make up this source file are from the
|
||||
// library's monolithic config.h.
|
||||
|
||||
/// \file config_asm.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config_asm.h</tt> provides defines for instruction set
|
||||
/// architectures
|
||||
/// and inline assembly.
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \note You should include <tt>config.h</tt> rather than <tt>config_asm.h</tt>
|
||||
/// directly.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>
|
||||
/// on the Crypto++ wiki
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_ASM_H
|
||||
#define CRYPTOPP_CONFIG_ASM_H
|
||||
|
||||
#include "config_os.h"
|
||||
#include "config_cpu.h"
|
||||
#include "config_ver.h"
|
||||
|
||||
// Define this to disable ASM, intrinsics and built-ins. The library will be
|
||||
// compiled using C++ only. The library code will not include SSE2 (and
|
||||
// above), NEON, Aarch32, Aarch64, or Altivec (and above). Note the compiler
|
||||
// may use higher ISAs depending on compiler options, but the library will not
|
||||
// explictly use the ISAs. When disabling ASM, it is best to do it from
|
||||
// config.h to ensure the library and all programs share the setting.
|
||||
// #define CRYPTOPP_DISABLE_ASM 1
|
||||
|
||||
// https://github.com/weidai11/cryptopp/issues/719
|
||||
#if defined(__native_client__)
|
||||
# undef CRYPTOPP_DISABLE_ASM
|
||||
# define CRYPTOPP_DISABLE_ASM 1
|
||||
#endif
|
||||
|
||||
// Some Clang and SunCC cannot handle mixed asm with positional arguments,
|
||||
// where the body is Intel style with no prefix and the templates are
|
||||
// AT&T style. Define this if the Makefile misdetects the configuration.
|
||||
// Also see https://bugs.llvm.org/show_bug.cgi?id=39895 .
|
||||
// #define CRYPTOPP_DISABLE_MIXED_ASM 1
|
||||
|
||||
#if defined(__clang__) || (defined(__APPLE__) && defined(__GNUC__)) || defined(__SUNPRO_CC)
|
||||
# undef CRYPTOPP_DISABLE_MIXED_ASM
|
||||
# define CRYPTOPP_DISABLE_MIXED_ASM 1
|
||||
#endif
|
||||
|
||||
// CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS is no longer honored. It
|
||||
// was removed at https://github.com/weidai11/cryptopp/issues/682
|
||||
// #define CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS 1
|
||||
|
||||
// ***************** IA32 CPU features ********************
|
||||
|
||||
#if (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64)
|
||||
|
||||
// Apple Clang prior to 5.0 cannot handle SSE2
|
||||
#if defined(CRYPTOPP_APPLE_CLANG_VERSION) && (CRYPTOPP_APPLE_CLANG_VERSION < 50000)
|
||||
# define CRYPTOPP_DISABLE_ASM 1
|
||||
#endif
|
||||
|
||||
// Sun Studio 12.1 provides GCC inline assembly
|
||||
// http://blogs.oracle.com/x86be/entry/gcc_style_asm_inlining_support
|
||||
#if defined(__SUNPRO_CC) && (__SUNPRO_CC < 0x5100)
|
||||
# define CRYPTOPP_DISABLE_ASM 1
|
||||
#endif
|
||||
|
||||
// Guard everything in CRYPTOPP_DISABLE_ASM
|
||||
#if !defined(CRYPTOPP_DISABLE_ASM)
|
||||
|
||||
#if (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 1
|
||||
|
||||
#if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(_MSC_VER) || CRYPTOPP_GCC_VERSION >= 30300 || defined(__SSE2__))
|
||||
#define CRYPTOPP_SSE2_ASM_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
#if !defined(CRYPTOPP_DISABLE_SSSE3) && (_MSC_VER >= 1500 || CRYPTOPP_GCC_VERSION >= 40300 || defined(__SSSE3__))
|
||||
#define CRYPTOPP_SSSE3_ASM_AVAILABLE 1
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(_MSC_VER) && defined(_M_X64)
|
||||
#define CRYPTOPP_X64_MASM_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
#if defined(__GNUC__) && defined(__x86_64__)
|
||||
#define CRYPTOPP_X64_ASM_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// 32-bit SunCC does not enable SSE2 by default.
|
||||
#if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(_MSC_VER) || CRYPTOPP_GCC_VERSION >= 30300 || defined(__SSE2__) || (__SUNPRO_CC >= 0x5100))
|
||||
#define CRYPTOPP_SSE2_INTRIN_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
#if !defined(CRYPTOPP_DISABLE_SSSE3)
|
||||
# if defined(__SSSE3__) || (_MSC_VER >= 1500) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40300) || (__INTEL_COMPILER >= 1000) || (__SUNPRO_CC >= 0x5110) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 20300) || (CRYPTOPP_APPLE_CLANG_VERSION >= 40000)
|
||||
#define CRYPTOPP_SSSE3_AVAILABLE 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// Intrinsics availible in GCC 4.3 (http://gcc.gnu.org/gcc-4.3/changes.html) and
|
||||
// MSVC 2008 (http://msdn.microsoft.com/en-us/library/bb892950%28v=vs.90%29.aspx)
|
||||
// SunCC could generate SSE4 at 12.1, but the intrinsics are missing until 12.4.
|
||||
#if !defined(CRYPTOPP_DISABLE_SSE4) && defined(CRYPTOPP_SSSE3_AVAILABLE) && \
|
||||
(defined(__SSE4_1__) || (CRYPTOPP_MSC_VERSION >= 1500) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40300) || (__INTEL_COMPILER >= 1000) || (__SUNPRO_CC >= 0x5110) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 20300) || (CRYPTOPP_APPLE_CLANG_VERSION >= 40000))
|
||||
#define CRYPTOPP_SSE41_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
#if !defined(CRYPTOPP_DISABLE_SSE4) && defined(CRYPTOPP_SSSE3_AVAILABLE) && \
|
||||
(defined(__SSE4_2__) || (CRYPTOPP_MSC_VERSION >= 1500) || (__SUNPRO_CC >= 0x5110) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40300) || (__INTEL_COMPILER >= 1000) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 20300) || (CRYPTOPP_APPLE_CLANG_VERSION >= 40000))
|
||||
#define CRYPTOPP_SSE42_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// Couple to CRYPTOPP_DISABLE_AESNI, but use CRYPTOPP_CLMUL_AVAILABLE so we can selectively
|
||||
// disable for misbehaving platofrms and compilers, like Solaris or some Clang.
|
||||
#if defined(CRYPTOPP_DISABLE_AESNI)
|
||||
#define CRYPTOPP_DISABLE_CLMUL 1
|
||||
#endif
|
||||
|
||||
// Requires Sun Studio 12.3 (SunCC 0x5120) in theory.
|
||||
#if !defined(CRYPTOPP_DISABLE_CLMUL) && defined(CRYPTOPP_SSE42_AVAILABLE) && \
|
||||
(defined(__PCLMUL__) || (_MSC_FULL_VER >= 150030729) || (__SUNPRO_CC >= 0x5120) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40300) || (__INTEL_COMPILER >= 1110) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 30200) || (CRYPTOPP_APPLE_CLANG_VERSION >= 40300))
|
||||
#define CRYPTOPP_CLMUL_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// Requires Sun Studio 12.3 (SunCC 0x5120)
|
||||
#if !defined(CRYPTOPP_DISABLE_AESNI) && defined(CRYPTOPP_SSE42_AVAILABLE) && \
|
||||
(defined(__AES__) || (_MSC_FULL_VER >= 150030729) || (__SUNPRO_CC >= 0x5120) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40300) || (__INTEL_COMPILER >= 1110) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 30200) || (CRYPTOPP_APPLE_CLANG_VERSION >= 40300))
|
||||
#define CRYPTOPP_AESNI_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// Requires Binutils 2.24
|
||||
#if !defined(CRYPTOPP_DISABLE_AVX) && defined(CRYPTOPP_SSE42_AVAILABLE) && \
|
||||
(defined(__AVX2__) || (CRYPTOPP_MSC_VERSION >= 1800) || (__SUNPRO_CC >= 0x5130) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40700) || (__INTEL_COMPILER >= 1400) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 30100) || (CRYPTOPP_APPLE_CLANG_VERSION >= 40600))
|
||||
#define CRYPTOPP_AVX_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// Requires Binutils 2.24
|
||||
#if !defined(CRYPTOPP_DISABLE_AVX2) && defined(CRYPTOPP_AVX_AVAILABLE) && \
|
||||
(defined(__AVX2__) || (CRYPTOPP_MSC_VERSION >= 1800) || (__SUNPRO_CC >= 0x5130) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40900) || (__INTEL_COMPILER >= 1400) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 30100) || (CRYPTOPP_APPLE_CLANG_VERSION >= 40600))
|
||||
#define CRYPTOPP_AVX2_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// Guessing at SHA for SunCC. Its not in Sun Studio 12.6. Also see
|
||||
// http://stackoverflow.com/questions/45872180/which-xarch-for-sha-extensions-on-solaris
|
||||
#if !defined(CRYPTOPP_DISABLE_SHANI) && defined(CRYPTOPP_SSE42_AVAILABLE) && \
|
||||
(defined(__SHA__) || (CRYPTOPP_MSC_VERSION >= 1900) || (__SUNPRO_CC >= 0x5160) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40900) || (__INTEL_COMPILER >= 1300) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 30400) || (CRYPTOPP_APPLE_CLANG_VERSION >= 50100))
|
||||
#define CRYPTOPP_SHANI_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// RDRAND uses byte codes. All we need is x86 ASM for it.
|
||||
// However tie it to AES-NI since SecureKey was available with it.
|
||||
#if !defined(CRYPTOPP_DISABLE_RDRAND) && defined(CRYPTOPP_AESNI_AVAILABLE)
|
||||
#define CRYPTOPP_RDRAND_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// RDSEED uses byte codes. All we need is x86 ASM for it.
|
||||
// However tie it to AES-NI since SecureKey was available with it.
|
||||
#if !defined(CRYPTOPP_DISABLE_RDSEED) && defined(CRYPTOPP_AESNI_AVAILABLE)
|
||||
#define CRYPTOPP_RDSEED_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// PadlockRNG uses byte codes. All we need is x86 ASM for it.
|
||||
#if !defined(CRYPTOPP_DISABLE_PADLOCK) && \
|
||||
!(defined(__ANDROID__) || defined(ANDROID) || defined(__APPLE__)) && \
|
||||
defined(CRYPTOPP_X86_ASM_AVAILABLE)
|
||||
#define CRYPTOPP_PADLOCK_AVAILABLE 1
|
||||
#define CRYPTOPP_PADLOCK_RNG_AVAILABLE 1
|
||||
#define CRYPTOPP_PADLOCK_ACE_AVAILABLE 1
|
||||
#define CRYPTOPP_PADLOCK_ACE2_AVAILABLE 1
|
||||
#define CRYPTOPP_PADLOCK_PHE_AVAILABLE 1
|
||||
#define CRYPTOPP_PADLOCK_PMM_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// Fixup Android and SSE, Crypto. It may be enabled based on compiler version.
|
||||
// Also see https://developer.android.com/ndk/guides/abis
|
||||
#if defined(__ANDROID__) || defined(ANDROID)
|
||||
# if (CRYPTOPP_BOOL_X86)
|
||||
# undef CRYPTOPP_SSE41_AVAILABLE
|
||||
# undef CRYPTOPP_SSE42_AVAILABLE
|
||||
# undef CRYPTOPP_CLMUL_AVAILABLE
|
||||
# undef CRYPTOPP_AESNI_AVAILABLE
|
||||
# undef CRYPTOPP_SHANI_AVAILABLE
|
||||
# undef CRYPTOPP_RDRAND_AVAILABLE
|
||||
# undef CRYPTOPP_RDSEED_AVAILABLE
|
||||
# undef CRYPTOPP_AVX_AVAILABLE
|
||||
# undef CRYPTOPP_AVX2_AVAILABLE
|
||||
# endif
|
||||
# if (CRYPTOPP_BOOL_X64)
|
||||
# undef CRYPTOPP_CLMUL_AVAILABLE
|
||||
# undef CRYPTOPP_AESNI_AVAILABLE
|
||||
# undef CRYPTOPP_SHANI_AVAILABLE
|
||||
# undef CRYPTOPP_RDRAND_AVAILABLE
|
||||
# undef CRYPTOPP_RDSEED_AVAILABLE
|
||||
# undef CRYPTOPP_AVX_AVAILABLE
|
||||
# undef CRYPTOPP_AVX2_AVAILABLE
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// Fixup for SunCC 12.1-12.4. Bad code generation in AES_Encrypt and friends.
|
||||
#if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x5130)
|
||||
# undef CRYPTOPP_AESNI_AVAILABLE
|
||||
#endif
|
||||
|
||||
// Fixup for SunCC 12.1-12.6. Compiler crash on GCM_Reduce_CLMUL.
|
||||
// http://github.com/weidai11/cryptopp/issues/226
|
||||
#if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x5150)
|
||||
# undef CRYPTOPP_CLMUL_AVAILABLE
|
||||
#endif
|
||||
|
||||
#endif // CRYPTOPP_DISABLE_ASM
|
||||
|
||||
#endif // X86, X32, X64
|
||||
|
||||
// ***************** ARM CPU features ********************
|
||||
|
||||
#if (CRYPTOPP_BOOL_ARM32 || CRYPTOPP_BOOL_ARMV8)
|
||||
|
||||
// We don't have an ARM big endian test rig. Disable
|
||||
// ARM-BE ASM and instrinsics until we can test it.
|
||||
#if (CRYPTOPP_BIG_ENDIAN)
|
||||
# define CRYPTOPP_DISABLE_ASM 1
|
||||
#endif
|
||||
|
||||
// Guard everything in CRYPTOPP_DISABLE_ASM
|
||||
#if !defined(CRYPTOPP_DISABLE_ASM)
|
||||
|
||||
// Requires ACLE 1.0. -mfpu=neon or above must be present
|
||||
// Requires GCC 4.3, Clang 2.8 or Visual Studio 2012
|
||||
// Do not use APPLE_CLANG_VERSION; use __ARM_FEATURE_XXX instead.
|
||||
#if !defined(CRYPTOPP_ARM_NEON_AVAILABLE) && !defined(CRYPTOPP_DISABLE_ARM_NEON)
|
||||
# if defined(__arm__) || defined(__ARM_NEON) || defined(__ARM_FEATURE_NEON) || defined(_M_ARM)
|
||||
# if (CRYPTOPP_GCC_VERSION >= 40300) || (CRYPTOPP_LLVM_CLANG_VERSION >= 20800) || \
|
||||
(CRYPTOPP_MSC_VERSION >= 1700)
|
||||
# define CRYPTOPP_ARM_NEON_AVAILABLE 1
|
||||
# endif // Compilers
|
||||
# endif // Platforms
|
||||
#endif
|
||||
|
||||
// ARMv8 and ASIMD. -march=armv8-a or above must be present
|
||||
// Requires GCC 4.8, Clang 3.3 or Visual Studio 2017
|
||||
// Do not use APPLE_CLANG_VERSION; use __ARM_FEATURE_XXX instead.
|
||||
#if !defined(CRYPTOPP_ARM_ASIMD_AVAILABLE) && !defined(CRYPTOPP_DISABLE_ARM_ASIMD)
|
||||
# if defined(__aarch32__) || defined(__aarch64__) || defined(_M_ARM64)
|
||||
# if defined(__ARM_NEON) || defined(__ARM_FEATURE_NEON) || defined(__ARM_FEATURE_ASIMD) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40800) || (CRYPTOPP_LLVM_CLANG_VERSION >= 30300) || \
|
||||
(CRYPTOPP_MSC_VERSION >= 1916)
|
||||
# define CRYPTOPP_ARM_NEON_AVAILABLE 1
|
||||
# define CRYPTOPP_ARM_ASIMD_AVAILABLE 1
|
||||
# endif // Compilers
|
||||
# endif // Platforms
|
||||
#endif
|
||||
|
||||
// ARMv8 and ASIMD. -march=armv8-a+crc or above must be present
|
||||
// Requires GCC 4.8, Clang 3.3 or Visual Studio 2017
|
||||
// Do not use APPLE_CLANG_VERSION; use __ARM_FEATURE_XXX instead.
|
||||
#if !defined(CRYPTOPP_ARM_CRC32_AVAILABLE) && !defined(CRYPTOPP_DISABLE_ARM_CRC32)
|
||||
# if defined(__aarch32__) || defined(__aarch64__) || defined(_M_ARM64)
|
||||
# if defined(__ARM_FEATURE_CRC32) || (CRYPTOPP_GCC_VERSION >= 40800) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 30300) || (CRYPTOPP_MSC_VERSION >= 1916)
|
||||
# define CRYPTOPP_ARM_CRC32_AVAILABLE 1
|
||||
# endif // Compilers
|
||||
# endif // Platforms
|
||||
#endif
|
||||
|
||||
// ARMv8 and ASIMD. -march=armv8-a+crypto or above must be present
|
||||
// Requires GCC 4.8, Clang 3.3 or Visual Studio 2017
|
||||
// Do not use APPLE_CLANG_VERSION; use __ARM_FEATURE_XXX instead.
|
||||
#if !defined(CRYPTOPP_ARM_PMULL_AVAILABLE) && !defined(CRYPTOPP_DISABLE_ARM_PMULL)
|
||||
# if defined(__aarch32__) || defined(__aarch64__) || defined(_M_ARM64)
|
||||
# if defined(__ARM_FEATURE_CRYPTO) || (CRYPTOPP_GCC_VERSION >= 40800) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 30300) || (CRYPTOPP_MSC_VERSION >= 1916)
|
||||
# define CRYPTOPP_ARM_PMULL_AVAILABLE 1
|
||||
# endif // Compilers
|
||||
# endif // Platforms
|
||||
#endif
|
||||
|
||||
// ARMv8 and AES. -march=armv8-a+crypto or above must be present
|
||||
// Requires GCC 4.8, Clang 3.3 or Visual Studio 2017
|
||||
// Do not use APPLE_CLANG_VERSION; use __ARM_FEATURE_XXX instead.
|
||||
#if !defined(CRYPTOPP_ARM_AES_AVAILABLE) && !defined(CRYPTOPP_DISABLE_ARM_AES)
|
||||
# if defined(__aarch32__) || defined(__aarch64__) || defined(_M_ARM64)
|
||||
# if defined(__ARM_FEATURE_CRYPTO) || (CRYPTOPP_GCC_VERSION >= 40800) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 30300) || (CRYPTOPP_MSC_VERSION >= 1916)
|
||||
# define CRYPTOPP_ARM_AES_AVAILABLE 1
|
||||
# endif // Compilers
|
||||
# endif // Platforms
|
||||
#endif
|
||||
|
||||
// ARMv8 and SHA-1, SHA-256. -march=armv8-a+crypto or above must be present
|
||||
// Requires GCC 4.8, Clang 3.3 or Visual Studio 2017
|
||||
// Do not use APPLE_CLANG_VERSION; use __ARM_FEATURE_XXX instead.
|
||||
#if !defined(CRYPTOPP_ARM_SHA_AVAILABLE) && !defined(CRYPTOPP_DISABLE_ARM_SHA)
|
||||
# if defined(__aarch32__) || defined(__aarch64__) || defined(_M_ARM64)
|
||||
# if defined(__ARM_FEATURE_CRYPTO) || (CRYPTOPP_GCC_VERSION >= 40800) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 30300) || (CRYPTOPP_MSC_VERSION >= 1916)
|
||||
# define CRYPTOPP_ARM_SHA1_AVAILABLE 1
|
||||
# define CRYPTOPP_ARM_SHA2_AVAILABLE 1
|
||||
# endif // Compilers
|
||||
# endif // Platforms
|
||||
#endif
|
||||
|
||||
// ARMv8 and SHA-512, SHA-3. -march=armv8.4-a+crypto or above must be present
|
||||
// Requires GCC 8.0, Clang ??? or Visual Studio 20??
|
||||
// Do not use APPLE_CLANG_VERSION; use __ARM_FEATURE_XXX instead.
|
||||
#if !defined(CRYPTOPP_ARM_SHA3_AVAILABLE) && !defined(CRYPTOPP_DISABLE_ARM_SHA)
|
||||
# if defined(__aarch32__) || defined(__aarch64__) || defined(_M_ARM64)
|
||||
# if defined(__ARM_FEATURE_SHA3) || (CRYPTOPP_GCC_VERSION >= 80000)
|
||||
# define CRYPTOPP_ARM_SHA512_AVAILABLE 1
|
||||
# define CRYPTOPP_ARM_SHA3_AVAILABLE 1
|
||||
# endif // Compilers
|
||||
# endif // Platforms
|
||||
#endif
|
||||
|
||||
// ARMv8 and SM3, SM4. -march=armv8.4-a+crypto or above must be present
|
||||
// Requires GCC 8.0, Clang ??? or Visual Studio 20??
|
||||
// Do not use APPLE_CLANG_VERSION; use __ARM_FEATURE_XXX instead.
|
||||
#if !defined(CRYPTOPP_ARM_SM3_AVAILABLE) && !defined(CRYPTOPP_DISABLE_ARM_SM3)
|
||||
# if defined(__aarch32__) || defined(__aarch64__) || defined(_M_ARM64)
|
||||
# if defined(__ARM_FEATURE_SM3) || (CRYPTOPP_GCC_VERSION >= 80000)
|
||||
# define CRYPTOPP_ARM_SM3_AVAILABLE 1
|
||||
# define CRYPTOPP_ARM_SM4_AVAILABLE 1
|
||||
# endif // Compilers
|
||||
# endif // Platforms
|
||||
#endif
|
||||
|
||||
// Limit the <arm_neon.h> include.
|
||||
#if !defined(CRYPTOPP_ARM_NEON_HEADER)
|
||||
# if defined(CRYPTOPP_ARM_NEON_AVAILABLE) || defined (CRYPTOPP_ARM_ASIMD_AVAILABLE)
|
||||
# if !defined(_M_ARM64)
|
||||
# define CRYPTOPP_ARM_NEON_HEADER 1
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// Limit the <arm_acle.h> include.
|
||||
#if !defined(CRYPTOPP_ARM_ACLE_HEADER)
|
||||
# if defined(__aarch32__) || defined(__aarch64__) || (__ARM_ARCH >= 8) || defined(__ARM_ACLE)
|
||||
# if !defined(__ANDROID__) && !defined(ANDROID) && !defined(__APPLE__)
|
||||
# define CRYPTOPP_ARM_ACLE_HEADER 1
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// Fixup Apple Clang and PMULL. Apple defines __ARM_FEATURE_CRYPTO for Xcode 6
|
||||
// but does not provide PMULL. TODO: determine when PMULL is available.
|
||||
#if defined(CRYPTOPP_APPLE_CLANG_VERSION) && (CRYPTOPP_APPLE_CLANG_VERSION < 70000)
|
||||
# undef CRYPTOPP_ARM_PMULL_AVAILABLE
|
||||
#endif
|
||||
|
||||
// Disable for Android. Android only offers the base Aarch64 architecture.
|
||||
// Also see https://developer.android.com/ndk/guides/abis
|
||||
#if defined(__ANDROID__) || defined(ANDROID)
|
||||
# undef CRYPTOPP_ARM_CRC32_AVAILABLE
|
||||
# undef CRYPTOPP_ARM_PMULL_AVAILABLE
|
||||
# undef CRYPTOPP_ARM_AES_AVAILABLE
|
||||
# undef CRYPTOPP_ARM_SHA1_AVAILABLE
|
||||
# undef CRYPTOPP_ARM_SHA2_AVAILABLE
|
||||
# undef CRYPTOPP_ARM_SHA3_AVAILABLE
|
||||
# undef CRYPTOPP_ARM_SHA512_AVAILABLE
|
||||
# undef CRYPTOPP_ARM_SM3_AVAILABLE
|
||||
# undef CRYPTOPP_ARM_SM4_AVAILABLE
|
||||
#endif
|
||||
|
||||
// Cryptogams offers an ARM asm implementations for AES and SHA. Crypto++ does
|
||||
// not provide an asm implementation. The Cryptogams AES implementation is
|
||||
// about 50% faster than C/C++, and SHA implementation is about 30% faster
|
||||
// than C/C++. Define this to use the Cryptogams AES and SHA implementations
|
||||
// on GNU Linux systems. When defined, Crypto++ will use aes_armv4.S,
|
||||
// sha1_armv4.S and sha256_armv4.S. https://www.cryptopp.com/wiki/Cryptogams.
|
||||
#if defined(__arm__) && defined(__linux__)
|
||||
# if defined(__GNUC__) || defined(__clang__)
|
||||
# define CRYPTOGAMS_ARM_AES 1
|
||||
# define CRYPTOGAMS_ARM_SHA1 1
|
||||
# define CRYPTOGAMS_ARM_SHA256 1
|
||||
# define CRYPTOGAMS_ARM_SHA512 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#endif // CRYPTOPP_DISABLE_ASM
|
||||
|
||||
#endif // ARM32, ARM64
|
||||
|
||||
// ***************** AltiVec and Power8 ********************
|
||||
|
||||
#if (CRYPTOPP_BOOL_PPC32 || CRYPTOPP_BOOL_PPC64)
|
||||
|
||||
// Guard everything in CRYPTOPP_DISABLE_ASM
|
||||
#if !defined(CRYPTOPP_DISABLE_ASM) && !defined(CRYPTOPP_DISABLE_ALTIVEC)
|
||||
|
||||
// An old Apple G5 with GCC 4.01 has AltiVec, but its only Power4 or so.
|
||||
#if !defined(CRYPTOPP_ALTIVEC_AVAILABLE)
|
||||
# if defined(_ARCH_PWR4) || defined(__ALTIVEC__) || \
|
||||
(CRYPTOPP_XLC_VERSION >= 100000) || (CRYPTOPP_GCC_VERSION >= 40001) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 20900)
|
||||
# define CRYPTOPP_ALTIVEC_AVAILABLE 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_ALTIVEC_AVAILABLE)
|
||||
|
||||
// We need Power7 for unaligned loads and stores
|
||||
#if !defined(CRYPTOPP_POWER7_AVAILABLE) && !defined(CRYPTOPP_DISABLE_POWER7)
|
||||
# if defined(_ARCH_PWR7) || (CRYPTOPP_XLC_VERSION >= 100000) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40100) || (CRYPTOPP_LLVM_CLANG_VERSION >= 30100)
|
||||
# define CRYPTOPP_POWER7_AVAILABLE 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_POWER7_AVAILABLE)
|
||||
|
||||
// We need Power8 for in-core crypto and 64-bit vector types
|
||||
#if !defined(CRYPTOPP_POWER8_AVAILABLE) && !defined(CRYPTOPP_DISABLE_POWER8)
|
||||
# if defined(_ARCH_PWR8) || (CRYPTOPP_XLC_VERSION >= 130000) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40800) || (CRYPTOPP_LLVM_CLANG_VERSION >= 70000)
|
||||
# define CRYPTOPP_POWER8_AVAILABLE 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if !defined(CRYPTOPP_POWER8_AES_AVAILABLE) && !defined(CRYPTOPP_DISABLE_POWER8_AES) && defined(CRYPTOPP_POWER8_AVAILABLE)
|
||||
# if defined(__CRYPTO__) || defined(_ARCH_PWR8) || (CRYPTOPP_XLC_VERSION >= 130000) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40800) || (CRYPTOPP_LLVM_CLANG_VERSION >= 70000)
|
||||
//# define CRYPTOPP_POWER8_CRC_AVAILABLE 1
|
||||
# define CRYPTOPP_POWER8_AES_AVAILABLE 1
|
||||
# define CRYPTOPP_POWER8_VMULL_AVAILABLE 1
|
||||
# define CRYPTOPP_POWER8_SHA_AVAILABLE 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_POWER8_AVAILABLE)
|
||||
|
||||
// Power9 for random numbers
|
||||
#if !defined(CRYPTOPP_POWER9_AVAILABLE) && !defined(CRYPTOPP_DISABLE_POWER9)
|
||||
# if defined(_ARCH_PWR9) || (CRYPTOPP_XLC_VERSION >= 130200) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 70000) || (CRYPTOPP_LLVM_CLANG_VERSION >= 80000)
|
||||
# define CRYPTOPP_POWER9_AVAILABLE 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#endif // CRYPTOPP_POWER8_AVAILABLE
|
||||
#endif // CRYPTOPP_POWER7_AVAILABLE
|
||||
#endif // CRYPTOPP_ALTIVEC_AVAILABLE
|
||||
#endif // CRYPTOPP_DISABLE_ASM
|
||||
#endif // PPC32, PPC64
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_ASM_H
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
// config_cpu.h - written and placed in public domain by Jeffrey Walton
|
||||
// the bits that make up this source file are from the
|
||||
// library's monolithic config.h.
|
||||
|
||||
/// \file config_cpu.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config_cpu.h</tt> provides defines for the cpu and machine
|
||||
/// architecture.
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \note You should include <tt>config.h</tt> rather than <tt>config_cpu.h</tt>
|
||||
/// directly.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>
|
||||
/// on the Crypto++ wiki,
|
||||
/// <A HREF="https://sourceforge.net/p/predef/wiki/Architectures/">Sourceforge
|
||||
/// Pre-defined Compiler Macros</A>
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_CPU_H
|
||||
#define CRYPTOPP_CONFIG_CPU_H
|
||||
|
||||
#include "config_ver.h"
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
/// \brief 32-bit x32 platform
|
||||
/// \details CRYPTOPP_BOOL_X32 is defined to 1 when building the library
|
||||
/// for a 32-bit x32 platform. Otherwise, the macro is not defined.
|
||||
/// \details x32 is sometimes referred to as x86_32. x32 is the ILP32 data
|
||||
/// model on a 64-bit cpu. Integers, longs and pointers are 32-bit but the
|
||||
/// program runs on a 64-bit cpu.
|
||||
/// \details The significance of x32 is, inline assembly must operate on
|
||||
/// 64-bit registers, not 32-bit registers. That means, for example,
|
||||
/// function prologues and epilogues must push and pop RSP, not ESP.
|
||||
/// \note: Clang defines __ILP32__ on any 32-bit platform. Therefore,
|
||||
/// CRYPTOPP_BOOL_X32 depends upon both __ILP32__ and __x86_64__.
|
||||
/// \sa <A HREF="https://wiki.debian.org/X32Port">Debian X32 Port</A>,
|
||||
/// <A HREF="https://wiki.gentoo.org/wiki/Project:Multilib/Concepts">Gentoo
|
||||
/// Multilib Concepts</A>
|
||||
#define CRYPTOPP_BOOL_X32 ...
|
||||
/// \brief 32-bit x86 platform
|
||||
/// \details CRYPTOPP_BOOL_X64 is defined to 1 when building the library
|
||||
/// for a 64-bit x64 platform. Otherwise, the macro is not defined.
|
||||
#define CRYPTOPP_BOOL_X64 ...
|
||||
/// \brief 32-bit x86 platform
|
||||
/// \details CRYPTOPP_BOOL_X86 is defined to 1 when building the library
|
||||
/// for a 32-bit x86 platform. Otherwise, the macro is not defined.
|
||||
#define CRYPTOPP_BOOL_X86 ...
|
||||
#elif (defined(__ILP32__) || defined(_ILP32)) && defined(__x86_64__)
|
||||
#define CRYPTOPP_BOOL_X32 1
|
||||
#elif (defined(_M_X64) || defined(__x86_64__))
|
||||
#define CRYPTOPP_BOOL_X64 1
|
||||
#elif (defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_X86_) || defined(__I86__) || defined(__INTEL__))
|
||||
#define CRYPTOPP_BOOL_X86 1
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
/// \brief ARMv8 platform
|
||||
/// \details CRYPTOPP_BOOL_ARMV8 is defined to 1 when building the library
|
||||
/// for an ARMv8 platform. Otherwise, the macro is not defined.
|
||||
/// \details ARMv8 includes both Aarch32 and Aarch64. Aarch32 is a 32-bit
|
||||
/// execution environment on Aarch64.
|
||||
#define CRYPTOPP_BOOL_ARMV8 ...
|
||||
/// \brief 64-bit ARM platform
|
||||
/// \details CRYPTOPP_BOOL_ARM64 is defined to 1 when building the library
|
||||
/// for a 64-bit x64 platform. Otherwise, the macro is not defined.
|
||||
/// \details Currently the macro indicates an ARM 64-bit architecture.
|
||||
#define CRYPTOPP_BOOL_ARM64 ...
|
||||
/// \brief 32-bit ARM platform
|
||||
/// \details CRYPTOPP_BOOL_ARM32 is defined to 1 when building the library
|
||||
/// for a 32-bit ARM platform. Otherwise, the macro is not defined.
|
||||
/// \details Currently the macro indicates an ARM A-32 architecture.
|
||||
#define CRYPTOPP_BOOL_ARM32 ...
|
||||
#elif defined(__arm64__) || defined(__aarch32__) || defined(__aarch64__) || defined(_M_ARM64)
|
||||
// Microsoft added ARM64 define December 2017.
|
||||
#define CRYPTOPP_BOOL_ARMV8 1
|
||||
#endif
|
||||
#if defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
|
||||
#define CRYPTOPP_BOOL_ARM64 1
|
||||
#elif defined(__arm__) || defined(_M_ARM)
|
||||
#define CRYPTOPP_BOOL_ARM32 1
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
/// \brief 64-bit PowerPC platform
|
||||
/// \details CRYPTOPP_BOOL_PPC64 is defined to 1 when building the library
|
||||
/// for a 64-bit PowerPC platform. Otherwise, the macro is not defined.
|
||||
#define CRYPTOPP_BOOL_PPC64 ...
|
||||
/// \brief 32-bit PowerPC platform
|
||||
/// \details CRYPTOPP_BOOL_PPC32 is defined to 1 when building the library
|
||||
/// for a 32-bit PowerPC platform. Otherwise, the macro is not defined.
|
||||
#define CRYPTOPP_BOOL_PPC32 ...
|
||||
#elif defined(__ppc64__) || defined(__powerpc64__) || defined(__PPC64__) || defined(_ARCH_PPC64)
|
||||
#define CRYPTOPP_BOOL_PPC64 1
|
||||
#elif defined(__powerpc__) || defined(__ppc__) || defined(__PPC__) || defined(_ARCH_PPC)
|
||||
#define CRYPTOPP_BOOL_PPC32 1
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
/// \brief 64-bit MIPS platform
|
||||
/// \details CRYPTOPP_BOOL_MIPS64 is defined to 1 when building the library
|
||||
/// for a 64-bit MIPS platform. Otherwise, the macro is not defined.
|
||||
#define CRYPTOPP_BOOL_MIPS64 ...
|
||||
/// \brief 64-bit MIPS platform
|
||||
/// \details CRYPTOPP_BOOL_MIPS32 is defined to 1 when building the library
|
||||
/// for a 32-bit MIPS platform. Otherwise, the macro is not defined.
|
||||
#define CRYPTOPP_BOOL_MIPS32 ...
|
||||
#elif defined(__mips64__)
|
||||
#define CRYPTOPP_BOOL_MIPS64 1
|
||||
#elif defined(__mips__)
|
||||
#define CRYPTOPP_BOOL_MIPS32 1
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
/// \brief 64-bit SPARC platform
|
||||
/// \details CRYPTOPP_BOOL_SPARC64 is defined to 1 when building the library
|
||||
/// for a 64-bit SPARC platform. Otherwise, the macro is not defined.
|
||||
#define CRYPTOPP_BOOL_SPARC64 ...
|
||||
/// \brief 32-bit SPARC platform
|
||||
/// \details CRYPTOPP_BOOL_SPARC32 is defined to 1 when building the library
|
||||
/// for a 32-bit SPARC platform. Otherwise, the macro is not defined.
|
||||
#define CRYPTOPP_BOOL_SPARC32 ...
|
||||
#elif defined(__sparc64__) || defined(__sparc64) || defined(__sparcv9) || defined(__sparc_v9__)
|
||||
#define CRYPTOPP_BOOL_SPARC64 1
|
||||
#elif defined(__sparc__) || defined(__sparc) || defined(__sparcv8) || defined(__sparc_v8__)
|
||||
#define CRYPTOPP_BOOL_SPARC32 1
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
/// \brief L1 data cache line size
|
||||
/// \details CRYPTOPP_L1_CACHE_LINE_SIZE should be a lower bound on the L1
|
||||
/// data cache line size. It is used for defense against some timing attacks.
|
||||
/// \details CRYPTOPP_L1_CACHE_LINE_SIZE default value on 32-bit platforms
|
||||
/// is 32, and the default value on 64-bit platforms is 64. On PowerPC the
|
||||
/// default value is 128 since all PowerPC cpu's starting at PPC 970 provide
|
||||
/// it.
|
||||
/// \note The runtime library on some PowerPC platforms misreport the size
|
||||
/// of the cache line size. The runtime library reports 64, while the cpu
|
||||
/// has a cache line size of 128.
|
||||
/// \sa <A HREF="https://bugs.centos.org/view.php?id=14599">CentOS Issue
|
||||
/// 14599: sysconf(_SC_LEVEL1_DCACHE_LINESIZE) returns 0 instead of 128</A>
|
||||
/// \since Crypto++ 5.3
|
||||
#define CRYPTOPP_L1_CACHE_LINE_SIZE ...
|
||||
#else
|
||||
#ifndef CRYPTOPP_L1_CACHE_LINE_SIZE
|
||||
#if defined(CRYPTOPP_BOOL_X32) || defined(CRYPTOPP_BOOL_X64) || defined(CRYPTOPP_BOOL_ARMV8) || \
|
||||
defined(CRYPTOPP_BOOL_MIPS64) || defined(CRYPTOPP_BOOL_SPARC64)
|
||||
#define CRYPTOPP_L1_CACHE_LINE_SIZE 64
|
||||
#elif defined(CRYPTOPP_BOOL_PPC32) || defined(CRYPTOPP_BOOL_PPC64)
|
||||
// http://lists.llvm.org/pipermail/llvm-dev/2017-March/110982.html
|
||||
#define CRYPTOPP_L1_CACHE_LINE_SIZE 128
|
||||
#else
|
||||
// L1 cache line size is 32 on Pentium III and earlier
|
||||
#define CRYPTOPP_L1_CACHE_LINE_SIZE 32
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
/// \brief Initialized data section
|
||||
/// \details CRYPTOPP_SECTION_INIT is added to variables to place them in the
|
||||
/// initialized data section (sometimes denoted <tt>.data</tt>). The placement
|
||||
/// helps avoid "uninitialized variable" warnings from Valgrind and other tools.
|
||||
#define CRYPTOPP_SECTION_INIT ...
|
||||
#else
|
||||
// The section attribute attempts to initialize CPU flags to avoid Valgrind findings above -O1
|
||||
#if ((defined(__MACH__) && defined(__APPLE__)) && ((CRYPTOPP_LLVM_CLANG_VERSION >= 30600) || \
|
||||
(CRYPTOPP_APPLE_CLANG_VERSION >= 70100) || (CRYPTOPP_GCC_VERSION >= 40300)))
|
||||
#define CRYPTOPP_SECTION_INIT __attribute__((section ("__DATA,__data")))
|
||||
#elif (defined(__ELF__) && (CRYPTOPP_GCC_VERSION >= 40300))
|
||||
#define CRYPTOPP_SECTION_INIT __attribute__((section ("nocommon")))
|
||||
#elif defined(__ELF__) && (defined(__xlC__) || defined(__ibmxl__))
|
||||
#define CRYPTOPP_SECTION_INIT __attribute__((section ("nocommon")))
|
||||
#else
|
||||
#define CRYPTOPP_SECTION_INIT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// How to disable CPU feature probing. We determine machine
|
||||
// capabilities by performing an os/platform *query* first,
|
||||
// like getauxv(). If the *query* fails, we move onto a
|
||||
// cpu *probe*. The cpu *probe* tries to exeute an instruction
|
||||
// and then catches a SIGILL on Linux or the exception
|
||||
// EXCEPTION_ILLEGAL_INSTRUCTION on Windows. Some OSes
|
||||
// fail to hangle a SIGILL gracefully, like Apple OSes. Apple
|
||||
// machines corrupt memory and variables around the probe.
|
||||
#if defined(__APPLE__)
|
||||
#define CRYPTOPP_NO_CPU_FEATURE_PROBES 1
|
||||
#endif
|
||||
|
||||
// Flavor of inline assembly language
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
/// \brief Microsoft style inline assembly
|
||||
/// \details CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY is defined when either
|
||||
/// <tt>_MSC_VER</tt> or <tt>__BORLANDC__</tt> are defined.
|
||||
#define CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY ...
|
||||
/// \brief GNU style inline assembly
|
||||
/// \details CRYPTOPP_GNU_STYLE_INLINE_ASSEMBLY is defined when neither
|
||||
/// <tt>_MSC_VER</tt> nor <tt>__BORLANDC__</tt> are defined.
|
||||
#define CRYPTOPP_GNU_STYLE_INLINE_ASSEMBLY ...
|
||||
#elif defined(_MSC_VER) || defined(__BORLANDC__)
|
||||
#define CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY 1
|
||||
#else
|
||||
#define CRYPTOPP_GNU_STYLE_INLINE_ASSEMBLY 1
|
||||
#endif
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_CPU_H
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
// config_cxx.h - written and placed in public domain by Jeffrey Walton
|
||||
// the bits that make up this source file are from the
|
||||
// library's monolithic config.h.
|
||||
|
||||
/// \file config_cxx.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config_cxx.h</tt> provides defines for C++ language and
|
||||
/// runtime library
|
||||
/// features.
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \note You should include <tt>config.h</tt> rather than <tt>config_cxx.h</tt>
|
||||
/// directly.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>
|
||||
/// on the Crypto++ wiki
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
// Visual Studio began at VS2010, http://msdn.microsoft.com/en-us/library/hh567368%28v=vs.110%29.aspx
|
||||
// and https://docs.microsoft.com/en-us/cpp/visual-cpp-language-conformance
|
||||
// Intel, http://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler
|
||||
// GCC, http://gcc.gnu.org/projects/cxx0x.html
|
||||
// Clang, http://clang.llvm.org/cxx_status.html
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_CXX_H
|
||||
#define CRYPTOPP_CONFIG_CXX_H
|
||||
|
||||
#include "config_os.h"
|
||||
#include "config_cpu.h"
|
||||
#include "config_ver.h"
|
||||
|
||||
// https://github.com/weidai11/cryptopp/issues/960
|
||||
#include <string>
|
||||
#include <exception>
|
||||
|
||||
// You may need to force include a C++ header on Android when using STLPort
|
||||
// to ensure _STLPORT_VERSION is defined
|
||||
#if (defined(_MSC_VER) && _MSC_VER <= 1300) || defined(__MWERKS__) || (defined(_STLPORT_VERSION) && ((_STLPORT_VERSION < 0x450) || defined(_STLP_NO_UNCAUGHT_EXCEPT_SUPPORT)))
|
||||
#define CRYPTOPP_DISABLE_UNCAUGHT_EXCEPTION
|
||||
#endif
|
||||
|
||||
// Ancient Crypto++ define, dating back to C++98.
|
||||
#ifndef CRYPTOPP_DISABLE_UNCAUGHT_EXCEPTION
|
||||
# define CRYPTOPP_UNCAUGHT_EXCEPTION_AVAILABLE 1
|
||||
# define CRYPTOPP_CXX98_UNCAUGHT_EXCEPTION 1
|
||||
#endif
|
||||
|
||||
// Compatibility with non-clang compilers.
|
||||
#ifndef __has_feature
|
||||
# define __has_feature(x) 0
|
||||
#endif
|
||||
|
||||
// Define CRYPTOPP_NO_CXX11 to avoid C++11 related features shown at the
|
||||
// end of this file. Some compilers and standard C++ headers advertise C++11
|
||||
// but they are really just C++03 with some additional C++11 headers and
|
||||
// non-conforming classes. Also see Issues 529.
|
||||
// #define CRYPTOPP_NO_CXX11 1
|
||||
|
||||
// Define CRYPTOPP_NO_CXX17 to avoid C++17 related features shown at the end of
|
||||
// this file. At the moment it should only affect std::uncaught_exceptions.
|
||||
// #define CRYPTOPP_NO_CXX17 1
|
||||
|
||||
// C++11 macro version, https://stackoverflow.com/q/7223991/608639
|
||||
#if !defined(CRYPTOPP_NO_CXX11)
|
||||
# if ((_MSC_VER >= 1600) || (__cplusplus >= 201103L)) && !defined(_STLPORT_VERSION)
|
||||
# define CRYPTOPP_CXX11 1
|
||||
# endif
|
||||
#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(__APPLE__) && defined(__clang__)
|
||||
# if !(defined(__has_include) && __has_include(<forward_list>))
|
||||
# undef CRYPTOPP_CXX11
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// C++14 macro version, https://stackoverflow.com/q/26089319/608639
|
||||
#if defined(CRYPTOPP_CXX11) && !defined(CRYPTOPP_NO_CXX14)
|
||||
# if ((_MSC_VER >= 1900) || (__cplusplus >= 201402L)) && !defined(_STLPORT_VERSION)
|
||||
# define CRYPTOPP_CXX14 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// C++17 macro version, https://stackoverflow.com/q/38456127/608639
|
||||
#if defined(CRYPTOPP_CXX14) && !defined(CRYPTOPP_NO_CXX17)
|
||||
# if ((_MSC_VER >= 1900) || (__cplusplus >= 201703L)) && !defined(_STLPORT_VERSION)
|
||||
# define CRYPTOPP_CXX17 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// ***************** C++11 and above ********************
|
||||
|
||||
#if defined(CRYPTOPP_CXX11)
|
||||
|
||||
// atomics: MS at VS2012 (17.00); GCC at 4.4; Clang at 3.1/3.2; Intel 13.0; SunCC 5.14.
|
||||
#if (CRYPTOPP_MSC_VERSION >= 1700) || __has_feature(cxx_atomic) || \
|
||||
(__INTEL_COMPILER >= 1300) || (CRYPTOPP_GCC_VERSION >= 40400) || (__SUNPRO_CC >= 0x5140)
|
||||
# define CRYPTOPP_CXX11_ATOMIC 1
|
||||
#endif // atomics
|
||||
|
||||
// synchronization: MS at VS2012 (17.00); GCC at 4.4; Clang at 3.3; Xcode 5.0; Intel 12.0; SunCC 5.13.
|
||||
// TODO: verify Clang and Intel versions; find __has_feature(x) extension for Clang
|
||||
#if (CRYPTOPP_MSC_VERSION >= 1700) || (CRYPTOPP_LLVM_CLANG_VERSION >= 30300) || \
|
||||
(CRYPTOPP_APPLE_CLANG_VERSION >= 50000) || (__INTEL_COMPILER >= 1200) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40400) || (__SUNPRO_CC >= 0x5130)
|
||||
// Hack ahead. New GCC compilers like GCC 6 on AIX 7.0 or earlier as well as original MinGW
|
||||
// don't have the synchronization gear. However, Wakely's test used for Apple does not work
|
||||
// on the GCC/AIX combination. Another twist is we need other stuff from C++11,
|
||||
// like no-except destructors. Dumping preprocessors shows the following may
|
||||
// apply: http://stackoverflow.com/q/14191566/608639.
|
||||
# include <cstddef>
|
||||
# if !defined(__GLIBCXX__) || defined(_GLIBCXX_HAS_GTHREADS)
|
||||
# define CRYPTOPP_CXX11_SYNCHRONIZATION 1
|
||||
# endif
|
||||
#endif // synchronization
|
||||
|
||||
// Dynamic Initialization and Destruction with Concurrency ("Magic Statics")
|
||||
// MS at VS2015 with Vista (19.00); GCC at 4.3; LLVM Clang at 2.9; Apple Clang at 4.0; Intel 11.1; SunCC 5.13.
|
||||
// Microsoft's implementation only works for Vista and above, so its further
|
||||
// limited. http://connect.microsoft.com/VisualStudio/feedback/details/1789709
|
||||
// Clang may not support this as early as we indicate. Also see https://bugs.llvm.org/show_bug.cgi?id=47012.
|
||||
#if (__cpp_threadsafe_static_init >= 200806) || \
|
||||
(CRYPTOPP_MSC_VERSION >= 1900) && ((WINVER >= 0x0600) || (_WIN32_WINNT >= 0x0600)) || \
|
||||
(CRYPTOPP_LLVM_CLANG_VERSION >= 20900) || (CRYPTOPP_APPLE_CLANG_VERSION >= 40000) || \
|
||||
(__INTEL_COMPILER >= 1110) || (CRYPTOPP_GCC_VERSION >= 40300) || (__SUNPRO_CC >= 0x5130)
|
||||
# define CRYPTOPP_CXX11_STATIC_INIT 1
|
||||
#endif // Dynamic Initialization compilers
|
||||
|
||||
// deleted functions: MS at VS2013 (18.00); GCC at 4.3; Clang at 2.9; Intel 12.1; SunCC 5.13.
|
||||
#if (CRYPTOPP_MSC_VERSION >= 1800) || (CRYPTOPP_LLVM_CLANG_VERSION >= 20900) || \
|
||||
(CRYPTOPP_APPLE_CLANG_VERSION >= 40000) || (__INTEL_COMPILER >= 1210) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40300) || (__SUNPRO_CC >= 0x5130)
|
||||
# define CRYPTOPP_CXX11_DELETED_FUNCTIONS 1
|
||||
#endif // deleted functions
|
||||
|
||||
// alignof/alignas: MS at VS2015 (19.00); GCC at 4.8; Clang at 3.0; Intel 15.0; SunCC 5.13.
|
||||
#if (CRYPTOPP_MSC_VERSION >= 1900) || __has_feature(cxx_alignas) || \
|
||||
(__INTEL_COMPILER >= 1500) || (CRYPTOPP_GCC_VERSION >= 40800) || (__SUNPRO_CC >= 0x5130)
|
||||
# define CRYPTOPP_CXX11_ALIGNAS 1
|
||||
#endif // alignas
|
||||
|
||||
// alignof: MS at VS2015 (19.00); GCC at 4.5; Clang at 2.9; Intel 15.0; SunCC 5.13.
|
||||
#if (CRYPTOPP_MSC_VERSION >= 1900) || __has_feature(cxx_alignof) || \
|
||||
(__INTEL_COMPILER >= 1500) || (CRYPTOPP_GCC_VERSION >= 40500) || (__SUNPRO_CC >= 0x5130)
|
||||
# define CRYPTOPP_CXX11_ALIGNOF 1
|
||||
#endif // alignof
|
||||
|
||||
// initializer lists: MS at VS2013 (18.00); GCC at 4.4; Clang at 3.1; Intel 14.0; SunCC 5.13.
|
||||
#if (CRYPTOPP_MSC_VERSION >= 1800) || (CRYPTOPP_LLVM_CLANG_VERSION >= 30100) || \
|
||||
(CRYPTOPP_APPLE_CLANG_VERSION >= 40000) || (__INTEL_COMPILER >= 1400) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40400) || (__SUNPRO_CC >= 0x5130)
|
||||
# define CRYPTOPP_CXX11_INITIALIZER_LIST 1
|
||||
#endif // alignas
|
||||
|
||||
// lambdas: MS at VS2012 (17.00); GCC at 4.9; Clang at 3.3; Intel 12.0; SunCC 5.14.
|
||||
#if (CRYPTOPP_MSC_VERSION >= 1700) || __has_feature(cxx_lambdas) || \
|
||||
(__INTEL_COMPILER >= 1200) || (CRYPTOPP_GCC_VERSION >= 40900) || (__SUNPRO_CC >= 0x5140)
|
||||
# define CRYPTOPP_CXX11_LAMBDA 1
|
||||
#endif // lambdas
|
||||
|
||||
// noexcept: MS at VS2015 (19.00); GCC at 4.6; Clang at 3.0; Intel 14.0; SunCC 5.13.
|
||||
#if (CRYPTOPP_MSC_VERSION >= 1900) || __has_feature(cxx_noexcept) || \
|
||||
(__INTEL_COMPILER >= 1400) || (CRYPTOPP_GCC_VERSION >= 40600) || (__SUNPRO_CC >= 0x5130)
|
||||
# define CRYPTOPP_CXX11_NOEXCEPT 1
|
||||
#endif // noexcept compilers
|
||||
|
||||
// variadic templates: MS at VS2013 (18.00); GCC at 4.3; Clang at 2.9; Intel 12.1; SunCC 5.13.
|
||||
#if (__cpp_variadic_templates >= 200704) || __has_feature(cxx_variadic_templates) || \
|
||||
(CRYPTOPP_MSC_VERSION >= 1800) || (__INTEL_COMPILER >= 1210) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40300) || (__SUNPRO_CC >= 0x5130)
|
||||
# define CRYPTOPP_CXX11_VARIADIC_TEMPLATES 1
|
||||
#endif // variadic templates
|
||||
|
||||
// constexpr: MS at VS2015 (19.00); GCC at 4.6; Clang at 3.1; Intel 16.0; SunCC 5.13.
|
||||
// Intel has mis-supported the feature since at least ICPC 13.00
|
||||
#if (__cpp_constexpr >= 200704) || __has_feature(cxx_constexpr) || \
|
||||
(CRYPTOPP_MSC_VERSION >= 1900) || (__INTEL_COMPILER >= 1600) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 40600) || (__SUNPRO_CC >= 0x5130)
|
||||
# define CRYPTOPP_CXX11_CONSTEXPR 1
|
||||
#endif // constexpr compilers
|
||||
|
||||
// strong typed enums: MS at VS2012 (17.00); GCC at 4.4; Clang at 3.3; Intel 14.0; SunCC 5.12.
|
||||
// Mircorosft and Intel had partial support earlier, but we require full support.
|
||||
#if (CRYPTOPP_MSC_VERSION >= 1700) || __has_feature(cxx_strong_enums) || \
|
||||
(__INTEL_COMPILER >= 1400) || (CRYPTOPP_GCC_VERSION >= 40400) || (__SUNPRO_CC >= 0x5120)
|
||||
# define CRYPTOPP_CXX11_STRONG_ENUM 1
|
||||
#endif // constexpr compilers
|
||||
|
||||
// nullptr_t: MS at VS2010 (16.00); GCC at 4.6; Clang at 3.3; Intel 10.0; SunCC 5.13.
|
||||
#if (CRYPTOPP_MSC_VERSION >= 1600) || __has_feature(cxx_nullptr) || \
|
||||
(__INTEL_COMPILER >= 1000) || (CRYPTOPP_GCC_VERSION >= 40600) || \
|
||||
(__SUNPRO_CC >= 0x5130) || defined(__IBMCPP_NULLPTR)
|
||||
# define CRYPTOPP_CXX11_NULLPTR 1
|
||||
#endif // nullptr_t compilers
|
||||
|
||||
#endif // CRYPTOPP_CXX11
|
||||
|
||||
// ***************** C++14 and above ********************
|
||||
|
||||
#if defined(CRYPTOPP_CXX14)
|
||||
|
||||
// Extended static_assert with one argument
|
||||
// Microsoft cannot handle the single argument static_assert as of VS2019 (cl.exe 19.00)
|
||||
#if (__cpp_static_assert >= 201411)
|
||||
# define CRYPTOPP_CXX17_STATIC_ASSERT 1
|
||||
#endif // static_assert
|
||||
|
||||
#endif
|
||||
|
||||
// ***************** C++17 and above ********************
|
||||
|
||||
// C++17 is available
|
||||
#if defined(CRYPTOPP_CXX17)
|
||||
|
||||
// C++17 uncaught_exceptions: MS at VS2015 (19.00); GCC at 6.0; Clang at 3.5; Intel 18.0.
|
||||
// Clang and __EXCEPTIONS see http://releases.llvm.org/3.6.0/tools/clang/docs/ReleaseNotes.html
|
||||
// Also see https://github.com/weidai11/cryptopp/issues/980. I'm not sure what
|
||||
// to do when the compiler defines __cpp_lib_uncaught_exceptions but the platform
|
||||
// does not support std::uncaught_exceptions. What was Apple thinking???
|
||||
#if defined(__clang__)
|
||||
# if __EXCEPTIONS && __has_feature(cxx_exceptions)
|
||||
# if __cpp_lib_uncaught_exceptions >= 201411L
|
||||
# define CRYPTOPP_CXX17_UNCAUGHT_EXCEPTIONS 1
|
||||
# endif
|
||||
# endif
|
||||
#elif (CRYPTOPP_MSC_VERSION >= 1900) || (__INTEL_COMPILER >= 1800) || \
|
||||
(CRYPTOPP_GCC_VERSION >= 60000) || (__cpp_lib_uncaught_exceptions >= 201411L)
|
||||
# define CRYPTOPP_CXX17_UNCAUGHT_EXCEPTIONS 1
|
||||
#endif // uncaught_exceptions compilers
|
||||
|
||||
#endif // CRYPTOPP_CXX17
|
||||
|
||||
// ***************** C++ fixups ********************
|
||||
|
||||
#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
|
||||
|
||||
// Hack... C++11 nullptr_t type safety and analysis
|
||||
#if defined(CRYPTOPP_CXX11_NULLPTR) && !defined(NULLPTR)
|
||||
# define NULLPTR nullptr
|
||||
#elif !defined(NULLPTR)
|
||||
# define NULLPTR NULL
|
||||
#endif // CRYPTOPP_CXX11_NULLPTR
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_CXX_H
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
// config_dll.h - written and placed in public domain by Jeffrey Walton
|
||||
// the bits that make up this source file are from the
|
||||
// library's monolithic config.h.
|
||||
|
||||
/// \file config_dll.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config_dll.h</tt> provides defines for shared objects and
|
||||
/// dynamic libraries. Generally speaking the macros are used to export
|
||||
/// classes and template classes from the Win32 dynamic link library.
|
||||
/// When not building the Win32 dynamic link library they are mostly an extern
|
||||
/// template declaration.
|
||||
/// \detail In practice they are a furball coughed up by a cat and then peed
|
||||
/// on by a dog. They are awful to get just right because of inconsistent
|
||||
/// compiler supprt for extern templates, manual instantiation and the FIPS DLL.
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \note You should include <tt>config.h</tt> rather than <tt>config_dll.h</tt>
|
||||
/// directly.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Visual_Studio">Visual Studio</A>,
|
||||
/// and <A HREF="https://www.cryptopp.com/wiki/FIPS_DLL">FIPS DLL</A>
|
||||
/// on the Crypto++ wiki
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_DLL_H
|
||||
#define CRYPTOPP_CONFIG_DLL_H
|
||||
|
||||
#include "config_os.h"
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
|
||||
/// \brief Win32 define for dynamic link libraries
|
||||
/// \details CRYPTOPP_IMPORTS is set in the Visual Studio project files.
|
||||
/// When the macro is set, <tt>CRYPTOPP_DLL</tt> is defined to
|
||||
/// <tt>__declspec(dllimport)</tt>.
|
||||
/// \details This macro has no effect on Unix & Linux.
|
||||
/// \sa <A HREF="https://www.cryptopp.com/wiki/Visual_Studio">Visual Studio</A>,
|
||||
/// and <A HREF="https://www.cryptopp.com/wiki/FIPS_DLL">FIPS DLL</A>
|
||||
/// on the Crypto++ wiki
|
||||
#define CRYPTOPP_IMPORTS ...
|
||||
|
||||
/// \brief Win32 define for dynamic link libraries
|
||||
/// \details CRYPTOPP_EXPORTS is set in the Visual Studio project files.
|
||||
/// When the macro is set, <tt>CRYPTOPP_DLL</tt> is defined to
|
||||
/// <tt>__declspec(dllexport)</tt>.
|
||||
/// \details This macro has no effect on Unix & Linux.
|
||||
/// \sa <A HREF="https://www.cryptopp.com/wiki/Visual_Studio">Visual Studio</A>,
|
||||
/// and <A HREF="https://www.cryptopp.com/wiki/FIPS_DLL">FIPS DLL</A>
|
||||
/// on the Crypto++ wiki
|
||||
#define CRYPTOPP_EXPORTS ...
|
||||
|
||||
/// \brief Win32 define for dynamic link libraries
|
||||
/// \details CRYPTOPP_IS_DLL is set in the Visual Studio project files.
|
||||
/// \sa <A HREF="https://www.cryptopp.com/wiki/Visual_Studio">Visual Studio</A>,
|
||||
/// and <A HREF="https://www.cryptopp.com/wiki/FIPS_DLL">FIPS DLL</A>
|
||||
/// on the Crypto++ wiki
|
||||
#define CRYPTOPP_IS_DLL
|
||||
|
||||
/// \brief Instantiate templates in a dynamic library
|
||||
/// \details CRYPTOPP_DLL_TEMPLATE_CLASS decoration should be used
|
||||
/// for classes intended to be exported from dynamic link libraries.
|
||||
/// \details This macro is primarily used on Win32, but sees some
|
||||
/// action on Unix & Linux due to the source file <tt>dll.cpp</tt>.
|
||||
/// \sa <A HREF="https://www.cryptopp.com/wiki/Visual_Studio">Visual Studio</A>,
|
||||
/// and <A HREF="https://www.cryptopp.com/wiki/FIPS_DLL">FIPS DLL</A>
|
||||
/// on the Crypto++ wiki
|
||||
#define CRYPTOPP_DLL_TEMPLATE_CLASS ...
|
||||
|
||||
/// \brief Instantiate templates in a dynamic library
|
||||
/// \details CRYPTOPP_EXTERN_DLL_TEMPLATE_CLASS decoration should be used
|
||||
/// for template classes intended to be exported from dynamic link libraries.
|
||||
/// \details This macro is primarily used on Win32, but sees some
|
||||
/// action on Unix & Linux due to the source file <tt>dll.cpp</tt>.
|
||||
/// \sa <A HREF="https://www.cryptopp.com/wiki/Visual_Studio">Visual Studio</A>,
|
||||
/// and <A HREF="https://www.cryptopp.com/wiki/FIPS_DLL">FIPS DLL</A>
|
||||
/// on the Crypto++ wiki
|
||||
#define CRYPTOPP_EXTERN_DLL_TEMPLATE_CLASS ...
|
||||
|
||||
/// \brief Instantiate templates in a dynamic library
|
||||
/// \details CRYPTOPP_STATIC_TEMPLATE_CLASS decoration should be used
|
||||
/// for template classes intended to be exported from dynamic link libraries.
|
||||
/// \details This macro is primarily used on Win32, but sees some
|
||||
/// action on Unix & Linux due to the source file <tt>dll.cpp</tt>.
|
||||
/// \sa <A HREF="https://www.cryptopp.com/wiki/Visual_Studio">Visual Studio</A>,
|
||||
/// and <A HREF="https://www.cryptopp.com/wiki/FIPS_DLL">FIPS DLL</A>
|
||||
/// on the Crypto++ wiki
|
||||
#define CRYPTOPP_STATIC_TEMPLATE_CLASS ...
|
||||
|
||||
/// \brief Instantiate templates in a dynamic library
|
||||
/// \details CRYPTOPP_EXTERN_STATIC_TEMPLATE_CLASS decoration should be used
|
||||
/// for template classes intended to be exported from dynamic link libraries.
|
||||
/// \details This macro is primarily used on Win32, but sees some
|
||||
/// action on Unix & Linux due to the source file <tt>dll.cpp</tt>.
|
||||
/// \sa <A HREF="https://www.cryptopp.com/wiki/Visual_Studio">Visual Studio</A>,
|
||||
/// and <A HREF="https://www.cryptopp.com/wiki/FIPS_DLL">FIPS DLL</A>
|
||||
/// on the Crypto++ wiki
|
||||
#define CRYPTOPP_EXTERN_STATIC_TEMPLATE_CLASS ...
|
||||
|
||||
/// \brief Override for internal linkage
|
||||
/// \details CRYPTOPP_TABLE can be used to override internal linkage
|
||||
/// on tables with the <tt>const</tt> qualifier. According to C++ rules
|
||||
/// a decalration with <tt>const</tt> qualifier is internal linkage.
|
||||
/// \note The name CRYPTOPP_TABLE was chosen because it is often used to
|
||||
/// export a table, like AES or SHA constants. The name avoids collisions
|
||||
/// with the DLL gear macros, like CRYPTOPP_EXPORTS and CRYPTOPP_EXTERN.
|
||||
#define CRYPTOPP_TABLE extern
|
||||
|
||||
/// \brief Win32 calling convention
|
||||
/// \details CRYPTOPP_API sets the calling convention on Win32.
|
||||
/// On Win32 CRYPTOPP_API is <tt>__cedcl</tt>. On Unix & Linux
|
||||
/// CRYPTOPP_API is defined to nothing.
|
||||
/// \sa <A HREF="https://www.cryptopp.com/wiki/Visual_Studio">Visual Studio</A>
|
||||
/// on the Crypto++ wiki
|
||||
#define CRYPTOPP_API ...
|
||||
|
||||
#else // CRYPTOPP_DOXYGEN_PROCESSING
|
||||
|
||||
#if defined(CRYPTOPP_WIN32_AVAILABLE)
|
||||
|
||||
#if defined(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
|
||||
|
||||
// C++ makes const internal linkage
|
||||
#define CRYPTOPP_TABLE extern
|
||||
#define CRYPTOPP_API __cdecl
|
||||
|
||||
#else // not CRYPTOPP_WIN32_AVAILABLE
|
||||
|
||||
// C++ makes const internal linkage
|
||||
#define CRYPTOPP_TABLE extern
|
||||
#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
|
||||
|
||||
#endif // CRYPTOPP_DOXYGEN_PROCESSING
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_DLL_H
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
// config_int.h - written and placed in public domain by Jeffrey Walton
|
||||
// the bits that make up this source file are from the
|
||||
// library's monolithic config.h.
|
||||
|
||||
/// \file config_int.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config_int.h</tt> provides defines and typedefs for fixed
|
||||
/// size integers. The library's choices for fixed size integers predates other
|
||||
/// standard-based integers by about 5 years. After fixed sizes were
|
||||
/// made standard, the library continued to use its own definitions for
|
||||
/// compatibility with previous versions of the library.
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \note You should include <tt>config.h</tt> rather than <tt>config_int.h</tt>
|
||||
/// directly.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>
|
||||
/// on the Crypto++ wiki
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_INT_H
|
||||
#define CRYPTOPP_CONFIG_INT_H
|
||||
|
||||
#include "config_ns.h"
|
||||
#include "config_ver.h"
|
||||
|
||||
/// \brief Library byte guard
|
||||
/// \details CRYPTOPP_NO_GLOBAL_BYTE indicates <tt>byte</tt> is in the Crypto++
|
||||
/// namespace.
|
||||
/// \details The Crypto++ <tt>byte</tt> was originally in global namespace to avoid
|
||||
/// ambiguity with other byte typedefs. <tt>byte</tt> was moved to CryptoPP namespace
|
||||
/// at Crypto++ 6.0 due to C++17, <tt>std::byte</tt> and potential compile problems.
|
||||
/// \sa <A HREF="http://github.com/weidai11/cryptopp/issues/442">Issue 442</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">std::byte</A> on the
|
||||
/// Crypto++ wiki
|
||||
/// \since Crypto++ 6.0
|
||||
#define CRYPTOPP_NO_GLOBAL_BYTE 1
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
// Signed words added at Issue 609 for early versions of and Visual Studio and
|
||||
// the NaCl gear. Also see https://github.com/weidai11/cryptopp/issues/609.
|
||||
|
||||
/// \brief 8-bit unsigned datatype
|
||||
/// \details The Crypto++ <tt>byte</tt> was originally in global namespace to avoid
|
||||
/// ambiguity with other byte typedefs. <tt>byte</tt> was moved to CryptoPP namespace
|
||||
/// at Crypto++ 6.0 due to C++17, <tt>std::byte</tt> and potential compile problems.
|
||||
/// \sa CRYPTOPP_NO_GLOBAL_BYTE, <A HREF="http://github.com/weidai11/cryptopp/issues/442">Issue 442</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">std::byte</A> on the
|
||||
/// Crypto++ wiki
|
||||
/// \since Crypto++ 1.0, CryptoPP namespace since Crypto++ 6.0
|
||||
typedef unsigned char byte;
|
||||
/// \brief 16-bit unsigned datatype
|
||||
/// \since Crypto++ 1.0
|
||||
typedef unsigned short word16;
|
||||
/// \brief 32-bit unsigned datatype
|
||||
/// \since Crypto++ 1.0
|
||||
typedef unsigned int word32;
|
||||
|
||||
/// \brief 8-bit signed datatype
|
||||
/// \details The 8-bit signed datatype was added to support constant time
|
||||
/// implementations for curve25519, X25519 key agreement and ed25519
|
||||
/// signatures.
|
||||
/// \since Crypto++ 8.0
|
||||
typedef signed char sbyte;
|
||||
/// \brief 16-bit signed datatype
|
||||
/// \details The 32-bit signed datatype was added to support constant time
|
||||
/// implementations for curve25519, X25519 key agreement and ed25519
|
||||
/// signatures.
|
||||
/// \since Crypto++ 8.0
|
||||
typedef signed short sword16;
|
||||
/// \brief 32-bit signed datatype
|
||||
/// \details The 32-bit signed datatype was added to support constant time
|
||||
/// implementations for curve25519, X25519 key agreement and ed25519
|
||||
/// signatures.
|
||||
/// \since Crypto++ 8.0
|
||||
typedef signed int sword32;
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
|
||||
/// \brief 64-bit unsigned datatype
|
||||
/// \details The typedef for <tt>word64</tt> varies depending on the platform.
|
||||
/// On Microsoft platforms it is <tt>unsigned __int64</tt>. On Unix & Linux
|
||||
/// with LP64 data model it is <tt>unsigned long</tt>. On Unix & Linux with ILP32
|
||||
/// data model it is <tt>unsigned long long</tt>.
|
||||
/// \since Crypto++ 1.0
|
||||
typedef unsigned long long word64;
|
||||
|
||||
/// \brief 64-bit signed datatype
|
||||
/// \details The typedef for <tt>sword64</tt> varies depending on the platform.
|
||||
/// On Microsoft platforms it is <tt>signed __int64</tt>. On Unix & Linux
|
||||
/// with LP64 data model it is <tt>signed long</tt>. On Unix & Linux with ILP32
|
||||
/// data model it is <tt>signed long long</tt>.
|
||||
/// \since Crypto++ 8.0
|
||||
typedef signed long long sword64;
|
||||
|
||||
/// \brief 128-bit unsigned datatype
|
||||
/// \details The typedef for <tt>word128</tt> varies depending on the platform.
|
||||
/// <tt>word128</tt> is only available on 64-bit machines when
|
||||
/// <tt>CRYPTOPP_WORD128_AVAILABLE</tt> is defined.
|
||||
/// On Unix & Linux with LP64 data model it is <tt>__uint128_t</tt>.
|
||||
/// Microsoft platforms do not provide a 128-bit integer type. 32-bit platforms
|
||||
/// do not provide a 128-bit integer type.
|
||||
/// \since Crypto++ 5.6
|
||||
typedef __uint128_t word128;
|
||||
|
||||
/// \brief Declare an unsigned word64
|
||||
/// \details W64LIT is used to portability declare or assign 64-bit literal values.
|
||||
/// W64LIT will append the proper suffix to ensure the compiler accepts the literal.
|
||||
/// \details Use the macro like shown below.
|
||||
/// <pre>
|
||||
/// word64 x = W64LIT(0xffffffffffffffff);
|
||||
/// </pre>
|
||||
/// \since Crypto++ 1.0
|
||||
#define W64LIT(x) ...
|
||||
|
||||
/// \brief Declare a signed word64
|
||||
/// \details SW64LIT is used to portability declare or assign 64-bit literal values.
|
||||
/// SW64LIT will append the proper suffix to ensure the compiler accepts the literal.
|
||||
/// \details Use the macro like shown below.
|
||||
/// <pre>
|
||||
/// sword64 x = SW64LIT(0xffffffffffffffff);
|
||||
/// </pre>
|
||||
/// \since Crypto++ 8.0
|
||||
#define SW64LIT(x) ...
|
||||
|
||||
/// \brief Declare ops on word64 are slow
|
||||
/// \details CRYPTOPP_BOOL_SLOW_WORD64 is typically defined to 1 on platforms
|
||||
/// that have a machine word smaller than 64-bits. That is, the define
|
||||
/// is present on 32-bit platforms. The define is also present on platforms
|
||||
/// where the cpu is slow even with a 64-bit cpu.
|
||||
#define CRYPTOPP_BOOL_SLOW_WORD64 ...
|
||||
|
||||
#elif defined(_MSC_VER) || defined(__BORLANDC__)
|
||||
typedef signed __int64 sword64;
|
||||
typedef unsigned __int64 word64;
|
||||
#define SW64LIT(x) x##i64
|
||||
#define W64LIT(x) x##ui64
|
||||
#elif (_LP64 || __LP64__)
|
||||
typedef signed long sword64;
|
||||
typedef unsigned long word64;
|
||||
#define SW64LIT(x) x##L
|
||||
#define W64LIT(x) x##UL
|
||||
#else
|
||||
typedef signed long long sword64;
|
||||
typedef unsigned long long word64;
|
||||
#define SW64LIT(x) x##LL
|
||||
#define W64LIT(x) x##ULL
|
||||
#endif
|
||||
|
||||
/// \brief Large word type
|
||||
/// \details lword is a typedef for large word types. It is used for file
|
||||
/// offsets and such.
|
||||
typedef word64 lword;
|
||||
|
||||
/// \brief Large word type max value
|
||||
/// \details LWORD_MAX is the maximum value for large word types.
|
||||
/// Since an <tt>lword</tt> is an unsigned type, the value is
|
||||
/// <tt>0xffffffffffffffff</tt>. W64LIT will append the proper suffix.
|
||||
const lword LWORD_MAX = W64LIT(0xffffffffffffffff);
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
/// \brief Half word used for multiprecision integer arithmetic
|
||||
/// \details hword is used for multiprecision integer arithmetic.
|
||||
/// The typedef for <tt>hword</tt> varies depending on the platform.
|
||||
/// On 32-bit platforms it is usually <tt>word16</tt>. On 64-bit platforms
|
||||
/// it is usually <tt>word32</tt>.
|
||||
/// \details Library users typically use byte, word16, word32 and word64.
|
||||
/// \since Crypto++ 2.0
|
||||
typedef word32 hword;
|
||||
/// \brief Full word used for multiprecision integer arithmetic
|
||||
/// \details word is used for multiprecision integer arithmetic.
|
||||
/// The typedef for <tt>word</tt> varies depending on the platform.
|
||||
/// On 32-bit platforms it is usually <tt>word32</tt>. On 64-bit platforms
|
||||
/// it is usually <tt>word64</tt>.
|
||||
/// \details Library users typically use byte, word16, word32 and word64.
|
||||
/// \since Crypto++ 2.0
|
||||
typedef word64 word;
|
||||
/// \brief Double word used for multiprecision integer arithmetic
|
||||
/// \details dword is used for multiprecision integer arithmetic.
|
||||
/// The typedef for <tt>dword</tt> varies depending on the platform.
|
||||
/// On 32-bit platforms it is usually <tt>word64</tt>. On 64-bit Unix &
|
||||
/// Linux platforms it is usually <tt>word128</tt>. <tt>word128</tt> is
|
||||
/// not available on Microsoft platforms. <tt>word128</tt> is only available
|
||||
/// when <tt>CRYPTOPP_WORD128_AVAILABLE</tt> is defined.
|
||||
/// \details Library users typically use byte, word16, word32 and word64.
|
||||
/// \sa CRYPTOPP_WORD128_AVAILABLE
|
||||
/// \since Crypto++ 2.0
|
||||
typedef word128 dword;
|
||||
|
||||
/// \brief 128-bit word availability
|
||||
/// \details CRYPTOPP_WORD128_AVAILABLE indicates a 128-bit word is
|
||||
/// available from the platform. 128-bit words are usually available on
|
||||
/// 64-bit platforms, but not available 32-bit platforms.
|
||||
/// \details If CRYPTOPP_WORD128_AVAILABLE is not defined, then 128-bit
|
||||
/// words are not available.
|
||||
/// \details GCC and compatible compilers signal 128-bit word availability
|
||||
/// with the preporcessor macro <tt>__SIZEOF_INT128__ >= 16</tt>.
|
||||
/// \since Crypto++ 2.0
|
||||
#define CRYPTOPP_WORD128_AVAILABLE ...
|
||||
#else
|
||||
// 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__))
|
||||
typedef word32 hword;
|
||||
typedef word64 word;
|
||||
#else
|
||||
#define CRYPTOPP_NATIVE_DWORD_AVAILABLE 1
|
||||
#if defined(__alpha__) || defined(__ia64__) || defined(_ARCH_PPC64) || defined(__x86_64__) || defined(__mips64) || defined(__sparc64__) || defined(__aarch64__)
|
||||
#if ((CRYPTOPP_GCC_VERSION >= 30400) || (CRYPTOPP_LLVM_CLANG_VERSION >= 30000) || (CRYPTOPP_APPLE_CLANG_VERSION >= 40300)) && (__SIZEOF_INT128__ >= 16)
|
||||
// GCC 4.0.1 on MacOS X is missing __umodti3 and __udivti3
|
||||
// GCC 4.8.3 and bad uint128_t ops on PPC64/POWER7 (Issue 421)
|
||||
// mode(TI) division broken on amd64 with GCC earlier than GCC 3.4
|
||||
typedef word32 hword;
|
||||
typedef word64 word;
|
||||
typedef __uint128_t dword;
|
||||
typedef __uint128_t word128;
|
||||
#define CRYPTOPP_WORD128_AVAILABLE 1
|
||||
#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
|
||||
#endif
|
||||
|
||||
#ifndef CRYPTOPP_BOOL_SLOW_WORD64
|
||||
# define CRYPTOPP_BOOL_SLOW_WORD64 0
|
||||
#endif
|
||||
|
||||
/// \brief Size of a platform word in bytes
|
||||
/// \details The size of a platform word, in bytes
|
||||
const unsigned int WORD_SIZE = sizeof(word);
|
||||
|
||||
/// \brief Size of a platform word in bits
|
||||
/// \details The size of a platform word, in bits
|
||||
const unsigned int WORD_BITS = WORD_SIZE * 8;
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_INT_H
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
// config_misc.h - written and placed in public domain by Jeffrey Walton
|
||||
// the bits that make up this source file are from the
|
||||
// library's monolithic config.h.
|
||||
|
||||
/// \file config_misc.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config_misc.h</tt> provides miscellaneous defines.
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \note You should include <tt>config.h</tt> rather than <tt>config_misc.h</tt>
|
||||
/// directly.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>
|
||||
/// on the Crypto++ wiki
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_MISC_H
|
||||
#define CRYPTOPP_CONFIG_MISC_H
|
||||
|
||||
#include "config_asm.h"
|
||||
#include "config_cxx.h"
|
||||
#include "config_os.h"
|
||||
#include "config_ver.h"
|
||||
|
||||
// Define this if running on a big-endian CPU
|
||||
// big endian will be assumed if CRYPTOPP_LITTLE_ENDIAN is not non-0
|
||||
#if !defined(CRYPTOPP_LITTLE_ENDIAN) && !defined(CRYPTOPP_BIG_ENDIAN) && (defined(__BIG_ENDIAN__) || (defined(__s390__) || defined(__s390x__) || defined(__zarch__)) || (defined(__m68k__) || defined(__MC68K__)) || defined(__sparc) || defined(__sparc__) || defined(__hppa__) || defined(__MIPSEB__) || defined(__ARMEB__) || (defined(__MWERKS__) && !defined(__INTEL__)))
|
||||
# define CRYPTOPP_BIG_ENDIAN 1
|
||||
#endif
|
||||
|
||||
// Define this if running on a little-endian CPU
|
||||
// big endian will be assumed if CRYPTOPP_LITTLE_ENDIAN is not non-0
|
||||
#if !defined(CRYPTOPP_BIG_ENDIAN) && !defined(CRYPTOPP_LITTLE_ENDIAN)
|
||||
# define CRYPTOPP_LITTLE_ENDIAN 1
|
||||
#endif
|
||||
|
||||
// Define this if you want to set a prefix for TestData/ and TestVectors/
|
||||
// Be sure to add the trailing slash since its simple concatenation.
|
||||
// After https://github.com/weidai11/cryptopp/issues/760 the library
|
||||
// should find the test vectors and data without much effort. It
|
||||
// will search in "./" and "$ORIGIN/../share/cryptopp" automatically.
|
||||
#ifndef CRYPTOPP_DATA_DIR
|
||||
# define CRYPTOPP_DATA_DIR ""
|
||||
#endif
|
||||
|
||||
// Define this to disable the test suite from searching for test
|
||||
// vectors and data in "./" and "$ORIGIN/../share/cryptopp". The
|
||||
// library will still search in CRYPTOPP_DATA_DIR, regardless.
|
||||
// Some distros may want to disable this feature. Also see
|
||||
// https://github.com/weidai11/cryptopp/issues/760
|
||||
// #ifndef CRYPTOPP_DISABLE_DATA_DIR_SEARCH
|
||||
// # define CRYPTOPP_DISABLE_DATA_DIR_SEARCH
|
||||
// #endif
|
||||
|
||||
// Define this if you want or need the library's memcpy_s and memmove_s.
|
||||
// See http://github.com/weidai11/cryptopp/issues/28.
|
||||
// #if !defined(CRYPTOPP_WANT_SECURE_LIB)
|
||||
// # define CRYPTOPP_WANT_SECURE_LIB
|
||||
// #endif
|
||||
|
||||
// Define this if ARMv8 shifts are slow. ARM Cortex-A53 and Cortex-A57 shift
|
||||
// operation perform poorly, so NEON and ASIMD code that relies on shifts
|
||||
// or rotates often performs worse than C/C++ code. Also see
|
||||
// http://github.com/weidai11/cryptopp/issues/367.
|
||||
#define CRYPTOPP_SLOW_ARMV8_SHIFT 1
|
||||
|
||||
// CRYPTOPP_DEBUG enables the library's CRYPTOPP_ASSERT. CRYPTOPP_ASSERT
|
||||
// raises a SIGTRAP (Unix) or calls DebugBreak() (Windows). CRYPTOPP_ASSERT
|
||||
// is only in effect when CRYPTOPP_DEBUG, DEBUG or _DEBUG is defined. Unlike
|
||||
// Posix assert, CRYPTOPP_ASSERT is not affected by NDEBUG (or failure to
|
||||
// define it).
|
||||
// Also see http://github.com/weidai11/cryptopp/issues/277, CVE-2016-7420
|
||||
#if (defined(DEBUG) || defined(_DEBUG)) && !defined(CRYPTOPP_DEBUG)
|
||||
# define CRYPTOPP_DEBUG 1
|
||||
#endif
|
||||
|
||||
// File system code to use when creating GZIP archive.
|
||||
// http://www.gzip.org/format.txt
|
||||
#if !defined(GZIP_OS_CODE)
|
||||
# if defined(__macintosh__)
|
||||
# define GZIP_OS_CODE 7
|
||||
# elif defined(__unix__) || defined(__linux__)
|
||||
# define GZIP_OS_CODE 3
|
||||
# else
|
||||
# define GZIP_OS_CODE 0
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// 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
|
||||
|
||||
// Define this if you want Integer's operator<< to honor std::showbase (and
|
||||
// std::noshowbase). If defined, Integer will use a suffix of 'b', 'o', 'h'
|
||||
// or '.' (the last for decimal) when std::showbase is in effect. If
|
||||
// std::noshowbase is set, then the suffix is not added to the Integer. If
|
||||
// not defined, existing behavior is preserved and Integer will use a suffix
|
||||
// of 'b', 'o', 'h' or '.' (the last for decimal).
|
||||
// #define CRYPTOPP_USE_STD_SHOWBASE
|
||||
|
||||
// Define this if you want to decouple AlgorithmParameters and Integer
|
||||
// The decoupling should make it easier for the linker to remove Integer
|
||||
// related code for those who do not need Integer, and avoid a potential
|
||||
// race during AssignIntToInteger pointer initialization. Also
|
||||
// see http://github.com/weidai11/cryptopp/issues/389.
|
||||
// #define CRYPTOPP_NO_ASSIGN_TO_INTEGER
|
||||
|
||||
// Need GCC 4.6/Clang 1.7/Apple Clang 2.0 or above due to "GCC diagnostic {push|pop}"
|
||||
#if (CRYPTOPP_GCC_VERSION >= 40600) || (CRYPTOPP_LLVM_CLANG_VERSION >= 10700) || \
|
||||
(CRYPTOPP_APPLE_CLANG_VERSION >= 20000)
|
||||
#define CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// Portable way to suppress warnings.
|
||||
// Moved from misc.h due to circular depenedencies.
|
||||
#ifndef CRYPTOPP_UNUSED
|
||||
#define CRYPTOPP_UNUSED(x) ((void)(x))
|
||||
#endif
|
||||
|
||||
// how to disable inlining
|
||||
#if defined(_MSC_VER)
|
||||
# define CRYPTOPP_NOINLINE_DOTDOTDOT
|
||||
# define CRYPTOPP_NOINLINE __declspec(noinline)
|
||||
#elif defined(__xlc__) || defined(__xlC__) || defined(__ibmxl__)
|
||||
# define CRYPTOPP_NOINLINE_DOTDOTDOT ...
|
||||
# define CRYPTOPP_NOINLINE __attribute__((noinline))
|
||||
#elif defined(__GNUC__)
|
||||
# define CRYPTOPP_NOINLINE_DOTDOTDOT
|
||||
# define CRYPTOPP_NOINLINE __attribute__((noinline))
|
||||
#else
|
||||
# define CRYPTOPP_NOINLINE_DOTDOTDOT ...
|
||||
# define CRYPTOPP_NOINLINE
|
||||
#endif
|
||||
|
||||
// http://stackoverflow.com/a/13867690/608639
|
||||
#if defined(CRYPTOPP_CXX11_CONSTEXPR)
|
||||
# define CRYPTOPP_STATIC_CONSTEXPR static constexpr
|
||||
# define CRYPTOPP_CONSTEXPR constexpr
|
||||
#else
|
||||
# define CRYPTOPP_STATIC_CONSTEXPR static
|
||||
# define CRYPTOPP_CONSTEXPR
|
||||
#endif // CRYPTOPP_CXX11_CONSTEXPR
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
# define CRYPTOPP_CONSTANT(x) static const int x
|
||||
#elif defined(CRYPTOPP_CXX11_STRONG_ENUM)
|
||||
# define CRYPTOPP_CONSTANT(x) enum : int { x }
|
||||
#elif defined(CRYPTOPP_CXX11_CONSTEXPR)
|
||||
# define CRYPTOPP_CONSTANT(x) constexpr static int x
|
||||
#else
|
||||
# define CRYPTOPP_CONSTANT(x) static const int x
|
||||
#endif
|
||||
|
||||
// Warnings
|
||||
#ifdef _MSC_VER
|
||||
// 4127: conditional expression is constant
|
||||
// 4512: assignment operator not generated
|
||||
// 4661: no suitable definition provided for explicit template instantiation request
|
||||
// 4910: '__declspec(dllexport)' and 'extern' are incompatible on an explicit instantiation
|
||||
# pragma warning(disable: 4127 4512 4661 4910)
|
||||
// _MSC_VER 1920 is VS2019
|
||||
# if _MSC_VER >= 1920
|
||||
// 5054: operator '|': deprecated between enumerations of different types
|
||||
# pragma warning(disable: 5054)
|
||||
# endif
|
||||
// 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
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_MISC_H
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
// config_ns.h - written and placed in public domain by Jeffrey Walton
|
||||
// the bits that make up this source file are from the
|
||||
// library's monolithic config.h.
|
||||
|
||||
/// \file config_ns.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config_ns.h</tt> provides defines for C++ and library
|
||||
/// namespaces.
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \note You should include <tt>config.h</tt> rather than <tt>config_ns.h</tt>
|
||||
/// directly.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>
|
||||
/// on the Crypto++ wiki
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_NAMESPACE_H
|
||||
#define CRYPTOPP_CONFIG_NAMESPACE_H
|
||||
|
||||
// namespace support is now required
|
||||
#ifdef NO_NAMESPACE
|
||||
# error namespace support is now required
|
||||
#endif
|
||||
|
||||
#ifdef CRYPTOPP_DOXYGEN_PROCESSING
|
||||
|
||||
/// \namespace CryptoPP
|
||||
/// \brief Crypto++ library namespace
|
||||
/// \details Nearly all classes are located in the CryptoPP namespace. Within
|
||||
/// the namespace, there are four additional namespaces.
|
||||
/// <ul>
|
||||
/// <li>Name - namespace for names used with NameValuePairs and documented
|
||||
/// in argnames.h
|
||||
/// <li>NaCl - namespace for NaCl test functions like crypto_box,
|
||||
/// crypto_box_open, crypto_sign, and crypto_sign_open
|
||||
/// <li>Donna - namespace for curve25519 library operations. The name was
|
||||
/// selected due to use of Langley and Moon's curve25519-donna.
|
||||
/// <li>Test - namespace for testing and benchmarks classes
|
||||
/// <li>Weak - namespace for weak and wounded algorithms, like ARC4, MD5
|
||||
/// and Pananma
|
||||
/// </ul>
|
||||
/// \since Crypto++ 3.0
|
||||
namespace CryptoPP { }
|
||||
|
||||
// Bring in the symbols found 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)
|
||||
#define NAMESPACE_END
|
||||
// Get Doxygen to generate better documentation for these typedefs
|
||||
#define DOCUMENTED_TYPEDEF(x, y) class y : public x {}
|
||||
// Make "protected" "private" so the functions and members are not documented
|
||||
#define protected private
|
||||
|
||||
#else
|
||||
// Not Doxygen
|
||||
#define NAMESPACE_BEGIN(x) namespace x {
|
||||
#define NAMESPACE_END }
|
||||
#define DOCUMENTED_TYPEDEF(x, y) typedef x y
|
||||
|
||||
#endif // CRYPTOPP_DOXYGEN_PROCESSING
|
||||
|
||||
#define ANONYMOUS_NAMESPACE_BEGIN namespace {
|
||||
#define ANONYMOUS_NAMESPACE_END }
|
||||
#define USING_NAMESPACE(x) using namespace x;
|
||||
#define DOCUMENTED_NAMESPACE_BEGIN(x) namespace x {
|
||||
#define DOCUMENTED_NAMESPACE_END }
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_NAMESPACE_H
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
// config_os.h - written and placed in public domain by Jeffrey Walton
|
||||
// the bits that make up this source file are from the
|
||||
// library's monolithic config.h.
|
||||
|
||||
/// \file config_os.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config_os.h</tt> provides defines for platforms and operating
|
||||
/// systems.
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \note You should include <tt>config.h</tt> rather than <tt>config_os.h</tt>
|
||||
/// directly.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>
|
||||
/// on the Crypto++ wiki
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_OS_H
|
||||
#define CRYPTOPP_CONFIG_OS_H
|
||||
|
||||
#include "config_ver.h"
|
||||
|
||||
// It is OK to remove the hard stop below, but you are on your own.
|
||||
// After building the library be sure to run self tests described
|
||||
// https://www.cryptopp.com/wiki/Release_Process#Self_Tests
|
||||
// Some relevant bug reports can be found at:
|
||||
// * Clang: http://github.com/weidai11/cryptopp/issues/147
|
||||
#if (defined(_MSC_VER) && defined(__clang__) && !(defined( __clang_analyzer__)))
|
||||
# error: "Unsupported configuration"
|
||||
#endif
|
||||
|
||||
// Windows platform
|
||||
#if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
|
||||
#define CRYPTOPP_WIN32_AVAILABLE
|
||||
#endif
|
||||
|
||||
// Unix and Linux platforms
|
||||
#if defined(__unix__) || defined(__MACH__) || defined(__NetBSD__) || defined(__sun)
|
||||
#define CRYPTOPP_UNIX_AVAILABLE
|
||||
#endif
|
||||
|
||||
// BSD platforms
|
||||
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
|
||||
#define CRYPTOPP_BSD_AVAILABLE
|
||||
#endif
|
||||
|
||||
// Microsoft compilers
|
||||
#if defined(_MSC_VER) || defined(__fastcall)
|
||||
#define CRYPTOPP_FASTCALL __fastcall
|
||||
#else
|
||||
#define CRYPTOPP_FASTCALL
|
||||
#endif
|
||||
|
||||
// Microsoft compilers
|
||||
#if defined(_MSC_VER)
|
||||
#define CRYPTOPP_NO_VTABLE __declspec(novtable)
|
||||
#else
|
||||
#define CRYPTOPP_NO_VTABLE
|
||||
#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 Windows random number generation.
|
||||
// This macro will be ignored if NO_OS_DEPENDENCE is defined.
|
||||
// #define USE_MS_CRYPTOAPI
|
||||
|
||||
// Define this to use features provided by Microsoft's CryptoNG API.
|
||||
// CryptoNG API is available in Vista and above and its cross platform,
|
||||
// including desktop apps and store apps. Currently the only feature
|
||||
// used is Windows random number generation.
|
||||
// This macro will be ignored if NO_OS_DEPENDENCE is defined.
|
||||
// #define USE_MS_CNGAPI
|
||||
|
||||
// If the user did not make a choice, then select CryptoNG if
|
||||
// targeting Windows 8 or above.
|
||||
#if !defined(USE_MS_CRYPTOAPI) && !defined(USE_MS_CNGAPI)
|
||||
# if !defined(_USING_V110_SDK71_) && ((WINVER >= 0x0602 /*_WIN32_WINNT_WIN8*/) || \
|
||||
(_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/))
|
||||
# define USE_MS_CNGAPI
|
||||
# else
|
||||
# define USE_MS_CRYPTOAPI
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// Begin OS features, like init priorities and random numbers
|
||||
#ifndef NO_OS_DEPENDENCE
|
||||
|
||||
// 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)". The platforms
|
||||
// with gaps are Apple and Sun because they require linker scripts. Apple and
|
||||
// Sun will use the library's Singletons to initialize and acquire resources.
|
||||
// Also see http://cryptopp.com/wiki/Static_Initialization_Order_Fiasco
|
||||
#ifndef CRYPTOPP_INIT_PRIORITY
|
||||
# define CRYPTOPP_INIT_PRIORITY 250
|
||||
#endif
|
||||
|
||||
// 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.
|
||||
#ifndef CRYPTOPP_USER_PRIORITY
|
||||
# define CRYPTOPP_USER_PRIORITY (CRYPTOPP_INIT_PRIORITY+101)
|
||||
#endif
|
||||
|
||||
// Most platforms allow us to specify when to create C++ objects. Apple and Sun do not.
|
||||
#if (CRYPTOPP_INIT_PRIORITY > 0) && !(defined(NO_OS_DEPENDENCE) || defined(__APPLE__) || defined(__sun__))
|
||||
# if (CRYPTOPP_GCC_VERSION >= 30000) || (CRYPTOPP_LLVM_CLANG_VERSION >= 20900) || (_INTEL_COMPILER >= 800)
|
||||
# define HAVE_GCC_INIT_PRIORITY 1
|
||||
# elif (CRYPTOPP_MSC_VERSION >= 1310)
|
||||
# define HAVE_MSC_INIT_PRIORITY 1
|
||||
# elif defined(__xlc__) || defined(__xlC__) || defined(__ibmxl__)
|
||||
# define HAVE_XLC_INIT_PRIORITY 1
|
||||
# endif
|
||||
#endif // CRYPTOPP_INIT_PRIORITY, NO_OS_DEPENDENCE, Apple, Sun
|
||||
|
||||
#if defined(CRYPTOPP_WIN32_AVAILABLE) || defined(CRYPTOPP_UNIX_AVAILABLE)
|
||||
# define HIGHRES_TIMER_AVAILABLE
|
||||
#endif
|
||||
|
||||
#ifdef CRYPTOPP_WIN32_AVAILABLE
|
||||
# if !defined(WINAPI_FAMILY)
|
||||
# define THREAD_TIMER_AVAILABLE
|
||||
# elif defined(WINAPI_FAMILY)
|
||||
# if (WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP))
|
||||
# define THREAD_TIMER_AVAILABLE
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_UNIX_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
# define NONBLOCKING_RNG_AVAILABLE
|
||||
# define BLOCKING_RNG_AVAILABLE
|
||||
# define OS_RNG_AVAILABLE
|
||||
#endif
|
||||
|
||||
// Cygwin/Newlib requires _XOPEN_SOURCE=600
|
||||
#if defined(CRYPTOPP_UNIX_AVAILABLE)
|
||||
# define UNIX_SIGNALS_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
#ifdef CRYPTOPP_WIN32_AVAILABLE
|
||||
# if !defined(WINAPI_FAMILY)
|
||||
# define NONBLOCKING_RNG_AVAILABLE
|
||||
# define OS_RNG_AVAILABLE
|
||||
# elif defined(WINAPI_FAMILY)
|
||||
# if (WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP))
|
||||
# define NONBLOCKING_RNG_AVAILABLE
|
||||
# define OS_RNG_AVAILABLE
|
||||
# elif !(WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP))
|
||||
# if ((WINVER >= 0x0A00 /*_WIN32_WINNT_WIN10*/) || (_WIN32_WINNT >= 0x0A00 /*_WIN32_WINNT_WIN10*/))
|
||||
# define NONBLOCKING_RNG_AVAILABLE
|
||||
# define OS_RNG_AVAILABLE
|
||||
# endif
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#endif // NO_OS_DEPENDENCE
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_OS_H
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
// config_ver.h - written and placed in public domain by Jeffrey Walton
|
||||
// the bits that make up this source file are from the
|
||||
// library's monolithic config.h.
|
||||
|
||||
/// \file config_ver.h
|
||||
/// \brief Library configuration file
|
||||
/// \details <tt>config_ver.h</tt> provides defines for library and compiler
|
||||
/// versions.
|
||||
/// \details <tt>config.h</tt> was split into components in May 2019 to better
|
||||
/// integrate with Autoconf and its feature tests. The splitting occurred so
|
||||
/// users could continue to include <tt>config.h</tt> while allowing Autoconf
|
||||
/// to write new <tt>config_asm.h</tt> and new <tt>config_cxx.h</tt> using
|
||||
/// its feature tests.
|
||||
/// \note You should include <tt>config.h</tt> rather than <tt>config_ver.h</tt>
|
||||
/// directly.
|
||||
/// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/835">Issue 835,
|
||||
/// Make config.h more autoconf friendly</A>,
|
||||
/// <A HREF="https://www.cryptopp.com/wiki/Configure.sh">Configure.sh script</A>
|
||||
/// on the Crypto++ wiki
|
||||
/// \since Crypto++ 8.3
|
||||
|
||||
#ifndef CRYPTOPP_CONFIG_VERSION_H
|
||||
#define CRYPTOPP_CONFIG_VERSION_H
|
||||
|
||||
/// \brief Library major version
|
||||
/// \details CRYPTOPP_MAJOR reflects the major version of the library the
|
||||
/// headers came from. It is not necessarily the version of the library built
|
||||
/// as a shared object if versions are inadvertently mixed and matched.
|
||||
/// \sa CRYPTOPP_VERSION, LibraryVersion(), HeaderVersion()
|
||||
/// \since Crypto++ 8.2
|
||||
#define CRYPTOPP_MAJOR 8
|
||||
/// \brief Library minor version
|
||||
/// \details CRYPTOPP_MINOR reflects the minor version of the library the
|
||||
/// headers came from. It is not necessarily the version of the library built
|
||||
/// as a shared object if versions are inadvertently mixed and matched.
|
||||
/// \sa CRYPTOPP_VERSION, LibraryVersion(), HeaderVersion()
|
||||
/// \since Crypto++ 8.2
|
||||
#define CRYPTOPP_MINOR 4
|
||||
/// \brief Library revision number
|
||||
/// \details CRYPTOPP_REVISION reflects the revision number of the library the
|
||||
/// headers came from. It is not necessarily the revision of the library built
|
||||
/// as a shared object if versions are inadvertently mixed and matched.
|
||||
/// \sa CRYPTOPP_VERSION, LibraryVersion(), HeaderVersion()
|
||||
/// \since Crypto++ 8.2
|
||||
#define CRYPTOPP_REVISION 0
|
||||
|
||||
/// \brief Full library version
|
||||
/// \details CRYPTOPP_VERSION reflects the version of the library the headers
|
||||
/// came from. It is not necessarily the version of the library built as a
|
||||
/// shared object if versions are inadvertently mixed and matched.
|
||||
/// \sa CRYPTOPP_MAJOR, CRYPTOPP_MINOR, CRYPTOPP_REVISION, LibraryVersion(), HeaderVersion()
|
||||
/// \since Crypto++ 5.6
|
||||
#define CRYPTOPP_VERSION 840
|
||||
|
||||
// Compiler version macros
|
||||
|
||||
#if defined(__GNUC__)
|
||||
# define CRYPTOPP_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
|
||||
#endif
|
||||
|
||||
#if defined(__xlc__) || defined(__xlC__)
|
||||
# define CRYPTOPP_XLC_VERSION ((__xlC__ / 256) * 10000 + (__xlC__ % 256) * 100)
|
||||
#endif
|
||||
|
||||
// Apple and LLVM's Clang. Apple Clang version 7.0 roughly equals LLVM Clang version 3.7
|
||||
// Also see https://gist.github.com/yamaya/2924292
|
||||
#if defined(__clang__) && defined(__apple_build_version__)
|
||||
# undef CRYPTOPP_GCC_VERSION
|
||||
# define CRYPTOPP_APPLE_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
|
||||
#elif defined(__clang__)
|
||||
# undef CRYPTOPP_GCC_VERSION
|
||||
# define CRYPTOPP_LLVM_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# define CRYPTOPP_MSC_VERSION (_MSC_VER)
|
||||
#endif
|
||||
|
||||
#endif // CRYPTOPP_CONFIG_VERSION_H
|
||||
+1292
File diff suppressed because it is too large
Load Diff
Vendored
+1083
File diff suppressed because it is too large
Load Diff
+367
@@ -0,0 +1,367 @@
|
||||
// crc.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
#include "crc.h"
|
||||
#include "misc.h"
|
||||
#include "cpu.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
// crc_simd.cpp
|
||||
#if (CRYPTOPP_ARM_CRC32_AVAILABLE)
|
||||
extern void CRC32_Update_ARMV8(const byte *s, size_t n, word32& c);
|
||||
extern void CRC32C_Update_ARMV8(const byte *s, size_t n, word32& c);
|
||||
#endif
|
||||
|
||||
// crc_simd.cpp
|
||||
#if (CRYPTOPP_SSE42_AVAILABLE)
|
||||
extern void CRC32C_Update_SSE42(const byte *s, size_t n, word32& c);
|
||||
#endif
|
||||
|
||||
/* Table of CRC-32's of all single byte values (made by makecrc.c) */
|
||||
const word32 CRC32::m_tab[] = {
|
||||
#if (CRYPTOPP_LITTLE_ENDIAN)
|
||||
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
|
||||
0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
|
||||
0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
|
||||
0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
|
||||
0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
|
||||
0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
|
||||
0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
|
||||
0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
|
||||
0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
|
||||
0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
|
||||
0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
|
||||
0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
|
||||
0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
|
||||
0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
|
||||
0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
|
||||
0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
|
||||
0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
|
||||
0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
|
||||
0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
|
||||
0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
|
||||
0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
|
||||
0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
|
||||
0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
|
||||
0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
|
||||
0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
|
||||
0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
|
||||
0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
|
||||
0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
|
||||
0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
|
||||
0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
|
||||
0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
|
||||
0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
|
||||
0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
|
||||
0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
|
||||
0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
|
||||
0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
|
||||
0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
|
||||
0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
|
||||
0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
|
||||
0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
|
||||
0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
|
||||
0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
|
||||
0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
|
||||
0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
|
||||
0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
|
||||
0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
|
||||
0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
|
||||
0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
|
||||
0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
|
||||
0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
|
||||
0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
|
||||
0x2d02ef8dL
|
||||
#else
|
||||
0x00000000L, 0x96300777L, 0x2c610eeeL, 0xba510999L, 0x19c46d07L,
|
||||
0x8ff46a70L, 0x35a563e9L, 0xa395649eL, 0x3288db0eL, 0xa4b8dc79L,
|
||||
0x1ee9d5e0L, 0x88d9d297L, 0x2b4cb609L, 0xbd7cb17eL, 0x072db8e7L,
|
||||
0x911dbf90L, 0x6410b71dL, 0xf220b06aL, 0x4871b9f3L, 0xde41be84L,
|
||||
0x7dd4da1aL, 0xebe4dd6dL, 0x51b5d4f4L, 0xc785d383L, 0x56986c13L,
|
||||
0xc0a86b64L, 0x7af962fdL, 0xecc9658aL, 0x4f5c0114L, 0xd96c0663L,
|
||||
0x633d0ffaL, 0xf50d088dL, 0xc8206e3bL, 0x5e10694cL, 0xe44160d5L,
|
||||
0x727167a2L, 0xd1e4033cL, 0x47d4044bL, 0xfd850dd2L, 0x6bb50aa5L,
|
||||
0xfaa8b535L, 0x6c98b242L, 0xd6c9bbdbL, 0x40f9bcacL, 0xe36cd832L,
|
||||
0x755cdf45L, 0xcf0dd6dcL, 0x593dd1abL, 0xac30d926L, 0x3a00de51L,
|
||||
0x8051d7c8L, 0x1661d0bfL, 0xb5f4b421L, 0x23c4b356L, 0x9995bacfL,
|
||||
0x0fa5bdb8L, 0x9eb80228L, 0x0888055fL, 0xb2d90cc6L, 0x24e90bb1L,
|
||||
0x877c6f2fL, 0x114c6858L, 0xab1d61c1L, 0x3d2d66b6L, 0x9041dc76L,
|
||||
0x0671db01L, 0xbc20d298L, 0x2a10d5efL, 0x8985b171L, 0x1fb5b606L,
|
||||
0xa5e4bf9fL, 0x33d4b8e8L, 0xa2c90778L, 0x34f9000fL, 0x8ea80996L,
|
||||
0x18980ee1L, 0xbb0d6a7fL, 0x2d3d6d08L, 0x976c6491L, 0x015c63e6L,
|
||||
0xf4516b6bL, 0x62616c1cL, 0xd8306585L, 0x4e0062f2L, 0xed95066cL,
|
||||
0x7ba5011bL, 0xc1f40882L, 0x57c40ff5L, 0xc6d9b065L, 0x50e9b712L,
|
||||
0xeab8be8bL, 0x7c88b9fcL, 0xdf1ddd62L, 0x492dda15L, 0xf37cd38cL,
|
||||
0x654cd4fbL, 0x5861b24dL, 0xce51b53aL, 0x7400bca3L, 0xe230bbd4L,
|
||||
0x41a5df4aL, 0xd795d83dL, 0x6dc4d1a4L, 0xfbf4d6d3L, 0x6ae96943L,
|
||||
0xfcd96e34L, 0x468867adL, 0xd0b860daL, 0x732d0444L, 0xe51d0333L,
|
||||
0x5f4c0aaaL, 0xc97c0dddL, 0x3c710550L, 0xaa410227L, 0x10100bbeL,
|
||||
0x86200cc9L, 0x25b56857L, 0xb3856f20L, 0x09d466b9L, 0x9fe461ceL,
|
||||
0x0ef9de5eL, 0x98c9d929L, 0x2298d0b0L, 0xb4a8d7c7L, 0x173db359L,
|
||||
0x810db42eL, 0x3b5cbdb7L, 0xad6cbac0L, 0x2083b8edL, 0xb6b3bf9aL,
|
||||
0x0ce2b603L, 0x9ad2b174L, 0x3947d5eaL, 0xaf77d29dL, 0x1526db04L,
|
||||
0x8316dc73L, 0x120b63e3L, 0x843b6494L, 0x3e6a6d0dL, 0xa85a6a7aL,
|
||||
0x0bcf0ee4L, 0x9dff0993L, 0x27ae000aL, 0xb19e077dL, 0x44930ff0L,
|
||||
0xd2a30887L, 0x68f2011eL, 0xfec20669L, 0x5d5762f7L, 0xcb676580L,
|
||||
0x71366c19L, 0xe7066b6eL, 0x761bd4feL, 0xe02bd389L, 0x5a7ada10L,
|
||||
0xcc4add67L, 0x6fdfb9f9L, 0xf9efbe8eL, 0x43beb717L, 0xd58eb060L,
|
||||
0xe8a3d6d6L, 0x7e93d1a1L, 0xc4c2d838L, 0x52f2df4fL, 0xf167bbd1L,
|
||||
0x6757bca6L, 0xdd06b53fL, 0x4b36b248L, 0xda2b0dd8L, 0x4c1b0aafL,
|
||||
0xf64a0336L, 0x607a0441L, 0xc3ef60dfL, 0x55df67a8L, 0xef8e6e31L,
|
||||
0x79be6946L, 0x8cb361cbL, 0x1a8366bcL, 0xa0d26f25L, 0x36e26852L,
|
||||
0x95770cccL, 0x03470bbbL, 0xb9160222L, 0x2f260555L, 0xbe3bbac5L,
|
||||
0x280bbdb2L, 0x925ab42bL, 0x046ab35cL, 0xa7ffd7c2L, 0x31cfd0b5L,
|
||||
0x8b9ed92cL, 0x1daede5bL, 0xb0c2649bL, 0x26f263ecL, 0x9ca36a75L,
|
||||
0x0a936d02L, 0xa906099cL, 0x3f360eebL, 0x85670772L, 0x13570005L,
|
||||
0x824abf95L, 0x147ab8e2L, 0xae2bb17bL, 0x381bb60cL, 0x9b8ed292L,
|
||||
0x0dbed5e5L, 0xb7efdc7cL, 0x21dfdb0bL, 0xd4d2d386L, 0x42e2d4f1L,
|
||||
0xf8b3dd68L, 0x6e83da1fL, 0xcd16be81L, 0x5b26b9f6L, 0xe177b06fL,
|
||||
0x7747b718L, 0xe65a0888L, 0x706a0fffL, 0xca3b0666L, 0x5c0b0111L,
|
||||
0xff9e658fL, 0x69ae62f8L, 0xd3ff6b61L, 0x45cf6c16L, 0x78e20aa0L,
|
||||
0xeed20dd7L, 0x5483044eL, 0xc2b30339L, 0x612667a7L, 0xf71660d0L,
|
||||
0x4d476949L, 0xdb776e3eL, 0x4a6ad1aeL, 0xdc5ad6d9L, 0x660bdf40L,
|
||||
0xf03bd837L, 0x53aebca9L, 0xc59ebbdeL, 0x7fcfb247L, 0xe9ffb530L,
|
||||
0x1cf2bdbdL, 0x8ac2bacaL, 0x3093b353L, 0xa6a3b424L, 0x0536d0baL,
|
||||
0x9306d7cdL, 0x2957de54L, 0xbf67d923L, 0x2e7a66b3L, 0xb84a61c4L,
|
||||
0x021b685dL, 0x942b6f2aL, 0x37be0bb4L, 0xa18e0cc3L, 0x1bdf055aL,
|
||||
0x8def022dL
|
||||
#endif
|
||||
};
|
||||
|
||||
std::string CRC32::AlgorithmProvider() const
|
||||
{
|
||||
#if (CRYPTOPP_ARM_CRC32_AVAILABLE)
|
||||
if (HasCRC32())
|
||||
return "ARMv8";
|
||||
#endif
|
||||
return "C++";
|
||||
}
|
||||
|
||||
CRC32::CRC32()
|
||||
{
|
||||
Reset();
|
||||
}
|
||||
|
||||
void CRC32::Update(const byte *s, size_t n)
|
||||
{
|
||||
#if (CRYPTOPP_ARM_CRC32_AVAILABLE)
|
||||
if (HasCRC32())
|
||||
{
|
||||
CRC32_Update_ARMV8(s, n, m_crc);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
word32 crc = m_crc;
|
||||
|
||||
for(; !IsAligned<word32>(s) && n > 0; n--)
|
||||
crc = m_tab[CRC32_INDEX(crc) ^ *s++] ^ CRC32_SHIFTED(crc);
|
||||
|
||||
while (n >= 4)
|
||||
{
|
||||
crc ^= *(const word32 *)(void*)s;
|
||||
crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
|
||||
crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
|
||||
crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
|
||||
crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
|
||||
n -= 4; s += 4;
|
||||
}
|
||||
|
||||
while (n--)
|
||||
crc = m_tab[CRC32_INDEX(crc) ^ *s++] ^ CRC32_SHIFTED(crc);
|
||||
|
||||
m_crc = crc;
|
||||
}
|
||||
|
||||
void CRC32::TruncatedFinal(byte *hash, size_t size)
|
||||
{
|
||||
ThrowIfInvalidTruncatedSize(size);
|
||||
|
||||
m_crc ^= CRC32_NEGL;
|
||||
for (size_t i=0; i<size; i++)
|
||||
hash[i] = GetCrcByte(i);
|
||||
|
||||
Reset();
|
||||
}
|
||||
|
||||
// Castagnoli CRC32C (iSCSI)
|
||||
|
||||
const word32 CRC32C::m_tab[] = {
|
||||
#if (CRYPTOPP_LITTLE_ENDIAN)
|
||||
0x00000000L, 0xf26b8303L, 0xe13b70f7L, 0x1350f3f4L, 0xc79a971fL,
|
||||
0x35f1141cL, 0x26a1e7e8L, 0xd4ca64ebL, 0x8ad958cfL, 0x78b2dbccL,
|
||||
0x6be22838L, 0x9989ab3bL, 0x4d43cfd0L, 0xbf284cd3L, 0xac78bf27L,
|
||||
0x5e133c24L, 0x105ec76fL, 0xe235446cL, 0xf165b798L, 0x030e349bL,
|
||||
0xd7c45070L, 0x25afd373L, 0x36ff2087L, 0xc494a384L, 0x9a879fa0L,
|
||||
0x68ec1ca3L, 0x7bbcef57L, 0x89d76c54L, 0x5d1d08bfL, 0xaf768bbcL,
|
||||
0xbc267848L, 0x4e4dfb4bL, 0x20bd8edeL, 0xd2d60dddL, 0xc186fe29L,
|
||||
0x33ed7d2aL, 0xe72719c1L, 0x154c9ac2L, 0x061c6936L, 0xf477ea35L,
|
||||
0xaa64d611L, 0x580f5512L, 0x4b5fa6e6L, 0xb93425e5L, 0x6dfe410eL,
|
||||
0x9f95c20dL, 0x8cc531f9L, 0x7eaeb2faL, 0x30e349b1L, 0xc288cab2L,
|
||||
0xd1d83946L, 0x23b3ba45L, 0xf779deaeL, 0x05125dadL, 0x1642ae59L,
|
||||
0xe4292d5aL, 0xba3a117eL, 0x4851927dL, 0x5b016189L, 0xa96ae28aL,
|
||||
0x7da08661L, 0x8fcb0562L, 0x9c9bf696L, 0x6ef07595L, 0x417b1dbcL,
|
||||
0xb3109ebfL, 0xa0406d4bL, 0x522bee48L, 0x86e18aa3L, 0x748a09a0L,
|
||||
0x67dafa54L, 0x95b17957L, 0xcba24573L, 0x39c9c670L, 0x2a993584L,
|
||||
0xd8f2b687L, 0x0c38d26cL, 0xfe53516fL, 0xed03a29bL, 0x1f682198L,
|
||||
0x5125dad3L, 0xa34e59d0L, 0xb01eaa24L, 0x42752927L, 0x96bf4dccL,
|
||||
0x64d4cecfL, 0x77843d3bL, 0x85efbe38L, 0xdbfc821cL, 0x2997011fL,
|
||||
0x3ac7f2ebL, 0xc8ac71e8L, 0x1c661503L, 0xee0d9600L, 0xfd5d65f4L,
|
||||
0x0f36e6f7L, 0x61c69362L, 0x93ad1061L, 0x80fde395L, 0x72966096L,
|
||||
0xa65c047dL, 0x5437877eL, 0x4767748aL, 0xb50cf789L, 0xeb1fcbadL,
|
||||
0x197448aeL, 0x0a24bb5aL, 0xf84f3859L, 0x2c855cb2L, 0xdeeedfb1L,
|
||||
0xcdbe2c45L, 0x3fd5af46L, 0x7198540dL, 0x83f3d70eL, 0x90a324faL,
|
||||
0x62c8a7f9L, 0xb602c312L, 0x44694011L, 0x5739b3e5L, 0xa55230e6L,
|
||||
0xfb410cc2L, 0x092a8fc1L, 0x1a7a7c35L, 0xe811ff36L, 0x3cdb9bddL,
|
||||
0xceb018deL, 0xdde0eb2aL, 0x2f8b6829L, 0x82f63b78L, 0x709db87bL,
|
||||
0x63cd4b8fL, 0x91a6c88cL, 0x456cac67L, 0xb7072f64L, 0xa457dc90L,
|
||||
0x563c5f93L, 0x082f63b7L, 0xfa44e0b4L, 0xe9141340L, 0x1b7f9043L,
|
||||
0xcfb5f4a8L, 0x3dde77abL, 0x2e8e845fL, 0xdce5075cL, 0x92a8fc17L,
|
||||
0x60c37f14L, 0x73938ce0L, 0x81f80fe3L, 0x55326b08L, 0xa759e80bL,
|
||||
0xb4091bffL, 0x466298fcL, 0x1871a4d8L, 0xea1a27dbL, 0xf94ad42fL,
|
||||
0x0b21572cL, 0xdfeb33c7L, 0x2d80b0c4L, 0x3ed04330L, 0xccbbc033L,
|
||||
0xa24bb5a6L, 0x502036a5L, 0x4370c551L, 0xb11b4652L, 0x65d122b9L,
|
||||
0x97baa1baL, 0x84ea524eL, 0x7681d14dL, 0x2892ed69L, 0xdaf96e6aL,
|
||||
0xc9a99d9eL, 0x3bc21e9dL, 0xef087a76L, 0x1d63f975L, 0x0e330a81L,
|
||||
0xfc588982L, 0xb21572c9L, 0x407ef1caL, 0x532e023eL, 0xa145813dL,
|
||||
0x758fe5d6L, 0x87e466d5L, 0x94b49521L, 0x66df1622L, 0x38cc2a06L,
|
||||
0xcaa7a905L, 0xd9f75af1L, 0x2b9cd9f2L, 0xff56bd19L, 0x0d3d3e1aL,
|
||||
0x1e6dcdeeL, 0xec064eedL, 0xc38d26c4L, 0x31e6a5c7L, 0x22b65633L,
|
||||
0xd0ddd530L, 0x0417b1dbL, 0xf67c32d8L, 0xe52cc12cL, 0x1747422fL,
|
||||
0x49547e0bL, 0xbb3ffd08L, 0xa86f0efcL, 0x5a048dffL, 0x8ecee914L,
|
||||
0x7ca56a17L, 0x6ff599e3L, 0x9d9e1ae0L, 0xd3d3e1abL, 0x21b862a8L,
|
||||
0x32e8915cL, 0xc083125fL, 0x144976b4L, 0xe622f5b7L, 0xf5720643L,
|
||||
0x07198540L, 0x590ab964L, 0xab613a67L, 0xb831c993L, 0x4a5a4a90L,
|
||||
0x9e902e7bL, 0x6cfbad78L, 0x7fab5e8cL, 0x8dc0dd8fL, 0xe330a81aL,
|
||||
0x115b2b19L, 0x020bd8edL, 0xf0605beeL, 0x24aa3f05L, 0xd6c1bc06L,
|
||||
0xc5914ff2L, 0x37faccf1L, 0x69e9f0d5L, 0x9b8273d6L, 0x88d28022L,
|
||||
0x7ab90321L, 0xae7367caL, 0x5c18e4c9L, 0x4f48173dL, 0xbd23943eL,
|
||||
0xf36e6f75L, 0x0105ec76L, 0x12551f82L, 0xe03e9c81L, 0x34f4f86aL,
|
||||
0xc69f7b69L, 0xd5cf889dL, 0x27a40b9eL, 0x79b737baL, 0x8bdcb4b9L,
|
||||
0x988c474dL, 0x6ae7c44eL, 0xbe2da0a5L, 0x4c4623a6L, 0x5f16d052L,
|
||||
0xad7d5351L
|
||||
#else
|
||||
0x00000000L, 0x03836bf2L, 0xf7703be1L, 0xf4f35013L, 0x1f979ac7L,
|
||||
0x1c14f135L, 0xe8e7a126L, 0xeb64cad4L, 0xcf58d98aL, 0xccdbb278L,
|
||||
0x3828e26bL, 0x3bab8999L, 0xd0cf434dL, 0xd34c28bfL, 0x27bf78acL,
|
||||
0x243c135eL, 0x6fc75e10L, 0x6c4435e2L, 0x98b765f1L, 0x9b340e03L,
|
||||
0x7050c4d7L, 0x73d3af25L, 0x8720ff36L, 0x84a394c4L, 0xa09f879aL,
|
||||
0xa31cec68L, 0x57efbc7bL, 0x546cd789L, 0xbf081d5dL, 0xbc8b76afL,
|
||||
0x487826bcL, 0x4bfb4d4eL, 0xde8ebd20L, 0xdd0dd6d2L, 0x29fe86c1L,
|
||||
0x2a7ded33L, 0xc11927e7L, 0xc29a4c15L, 0x36691c06L, 0x35ea77f4L,
|
||||
0x11d664aaL, 0x12550f58L, 0xe6a65f4bL, 0xe52534b9L, 0x0e41fe6dL,
|
||||
0x0dc2959fL, 0xf931c58cL, 0xfab2ae7eL, 0xb149e330L, 0xb2ca88c2L,
|
||||
0x4639d8d1L, 0x45bab323L, 0xaede79f7L, 0xad5d1205L, 0x59ae4216L,
|
||||
0x5a2d29e4L, 0x7e113abaL, 0x7d925148L, 0x8961015bL, 0x8ae26aa9L,
|
||||
0x6186a07dL, 0x6205cb8fL, 0x96f69b9cL, 0x9575f06eL, 0xbc1d7b41L,
|
||||
0xbf9e10b3L, 0x4b6d40a0L, 0x48ee2b52L, 0xa38ae186L, 0xa0098a74L,
|
||||
0x54fada67L, 0x5779b195L, 0x7345a2cbL, 0x70c6c939L, 0x8435992aL,
|
||||
0x87b6f2d8L, 0x6cd2380cL, 0x6f5153feL, 0x9ba203edL, 0x9821681fL,
|
||||
0xd3da2551L, 0xd0594ea3L, 0x24aa1eb0L, 0x27297542L, 0xcc4dbf96L,
|
||||
0xcfced464L, 0x3b3d8477L, 0x38beef85L, 0x1c82fcdbL, 0x1f019729L,
|
||||
0xebf2c73aL, 0xe871acc8L, 0x0315661cL, 0x00960deeL, 0xf4655dfdL,
|
||||
0xf7e6360fL, 0x6293c661L, 0x6110ad93L, 0x95e3fd80L, 0x96609672L,
|
||||
0x7d045ca6L, 0x7e873754L, 0x8a746747L, 0x89f70cb5L, 0xadcb1febL,
|
||||
0xae487419L, 0x5abb240aL, 0x59384ff8L, 0xb25c852cL, 0xb1dfeedeL,
|
||||
0x452cbecdL, 0x46afd53fL, 0x0d549871L, 0x0ed7f383L, 0xfa24a390L,
|
||||
0xf9a7c862L, 0x12c302b6L, 0x11406944L, 0xe5b33957L, 0xe63052a5L,
|
||||
0xc20c41fbL, 0xc18f2a09L, 0x357c7a1aL, 0x36ff11e8L, 0xdd9bdb3cL,
|
||||
0xde18b0ceL, 0x2aebe0ddL, 0x29688b2fL, 0x783bf682L, 0x7bb89d70L,
|
||||
0x8f4bcd63L, 0x8cc8a691L, 0x67ac6c45L, 0x642f07b7L, 0x90dc57a4L,
|
||||
0x935f3c56L, 0xb7632f08L, 0xb4e044faL, 0x401314e9L, 0x43907f1bL,
|
||||
0xa8f4b5cfL, 0xab77de3dL, 0x5f848e2eL, 0x5c07e5dcL, 0x17fca892L,
|
||||
0x147fc360L, 0xe08c9373L, 0xe30ff881L, 0x086b3255L, 0x0be859a7L,
|
||||
0xff1b09b4L, 0xfc986246L, 0xd8a47118L, 0xdb271aeaL, 0x2fd44af9L,
|
||||
0x2c57210bL, 0xc733ebdfL, 0xc4b0802dL, 0x3043d03eL, 0x33c0bbccL,
|
||||
0xa6b54ba2L, 0xa5362050L, 0x51c57043L, 0x52461bb1L, 0xb922d165L,
|
||||
0xbaa1ba97L, 0x4e52ea84L, 0x4dd18176L, 0x69ed9228L, 0x6a6ef9daL,
|
||||
0x9e9da9c9L, 0x9d1ec23bL, 0x767a08efL, 0x75f9631dL, 0x810a330eL,
|
||||
0x828958fcL, 0xc97215b2L, 0xcaf17e40L, 0x3e022e53L, 0x3d8145a1L,
|
||||
0xd6e58f75L, 0xd566e487L, 0x2195b494L, 0x2216df66L, 0x062acc38L,
|
||||
0x05a9a7caL, 0xf15af7d9L, 0xf2d99c2bL, 0x19bd56ffL, 0x1a3e3d0dL,
|
||||
0xeecd6d1eL, 0xed4e06ecL, 0xc4268dc3L, 0xc7a5e631L, 0x3356b622L,
|
||||
0x30d5ddd0L, 0xdbb11704L, 0xd8327cf6L, 0x2cc12ce5L, 0x2f424717L,
|
||||
0x0b7e5449L, 0x08fd3fbbL, 0xfc0e6fa8L, 0xff8d045aL, 0x14e9ce8eL,
|
||||
0x176aa57cL, 0xe399f56fL, 0xe01a9e9dL, 0xabe1d3d3L, 0xa862b821L,
|
||||
0x5c91e832L, 0x5f1283c0L, 0xb4764914L, 0xb7f522e6L, 0x430672f5L,
|
||||
0x40851907L, 0x64b90a59L, 0x673a61abL, 0x93c931b8L, 0x904a5a4aL,
|
||||
0x7b2e909eL, 0x78adfb6cL, 0x8c5eab7fL, 0x8fddc08dL, 0x1aa830e3L,
|
||||
0x192b5b11L, 0xedd80b02L, 0xee5b60f0L, 0x053faa24L, 0x06bcc1d6L,
|
||||
0xf24f91c5L, 0xf1ccfa37L, 0xd5f0e969L, 0xd673829bL, 0x2280d288L,
|
||||
0x2103b97aL, 0xca6773aeL, 0xc9e4185cL, 0x3d17484fL, 0x3e9423bdL,
|
||||
0x756f6ef3L, 0x76ec0501L, 0x821f5512L, 0x819c3ee0L, 0x6af8f434L,
|
||||
0x697b9fc6L, 0x9d88cfd5L, 0x9e0ba427L, 0xba37b779L, 0xb9b4dc8bL,
|
||||
0x4d478c98L, 0x4ec4e76aL, 0xa5a02dbeL, 0xa623464cL, 0x52d0165fL,
|
||||
0x51537dadL
|
||||
#endif
|
||||
};
|
||||
|
||||
std::string CRC32C::AlgorithmProvider() const
|
||||
{
|
||||
#if (CRYPTOPP_ARM_CRC32_AVAILABLE)
|
||||
if (HasCRC32())
|
||||
return "ARMv8";
|
||||
#endif
|
||||
#if (CRYPTOPP_SSE42_AVAILABLE)
|
||||
if (HasSSE42())
|
||||
return "SSE4.2";
|
||||
#endif
|
||||
return "C++";
|
||||
}
|
||||
|
||||
CRC32C::CRC32C()
|
||||
{
|
||||
Reset();
|
||||
}
|
||||
|
||||
void CRC32C::Update(const byte *s, size_t n)
|
||||
{
|
||||
#if (CRYPTOPP_SSE42_AVAILABLE)
|
||||
if (HasSSE42())
|
||||
{
|
||||
CRC32C_Update_SSE42(s, n, m_crc);
|
||||
return;
|
||||
}
|
||||
#elif (CRYPTOPP_ARM_CRC32_AVAILABLE)
|
||||
if (HasCRC32())
|
||||
{
|
||||
CRC32C_Update_ARMV8(s, n, m_crc);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
word32 crc = m_crc;
|
||||
|
||||
for(; !IsAligned<word32>(s) && n > 0; n--)
|
||||
crc = m_tab[CRC32_INDEX(crc) ^ *s++] ^ CRC32_SHIFTED(crc);
|
||||
|
||||
while (n >= 4)
|
||||
{
|
||||
crc ^= *(const word32 *)(void*)s;
|
||||
crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
|
||||
crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
|
||||
crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
|
||||
crc = m_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
|
||||
n -= 4; s += 4;
|
||||
}
|
||||
|
||||
while (n--)
|
||||
crc = m_tab[CRC32_INDEX(crc) ^ *s++] ^ CRC32_SHIFTED(crc);
|
||||
|
||||
m_crc = crc;
|
||||
}
|
||||
|
||||
void CRC32C::TruncatedFinal(byte *hash, size_t size)
|
||||
{
|
||||
ThrowIfInvalidTruncatedSize(size);
|
||||
|
||||
m_crc ^= CRC32_NEGL;
|
||||
for (size_t i=0; i<size; i++)
|
||||
hash[i] = GetCrcByte(i);
|
||||
|
||||
Reset();
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
Vendored
+78
@@ -0,0 +1,78 @@
|
||||
// crc.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file crc.h
|
||||
/// \brief Classes for CRC-32 and CRC-32C checksum algorithm
|
||||
|
||||
#ifndef CRYPTOPP_CRC32_H
|
||||
#define CRYPTOPP_CRC32_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
const word32 CRC32_NEGL = 0xffffffffL;
|
||||
|
||||
#if (CRYPTOPP_LITTLE_ENDIAN)
|
||||
#define CRC32_INDEX(c) (c & 0xff)
|
||||
#define CRC32_SHIFTED(c) (c >> 8)
|
||||
#else
|
||||
#define CRC32_INDEX(c) (c >> 24)
|
||||
#define CRC32_SHIFTED(c) (c << 8)
|
||||
#endif
|
||||
|
||||
/// \brief CRC-32 Checksum Calculation
|
||||
/// \details Uses CRC polynomial 0xEDB88320
|
||||
class CRC32 : public HashTransformation
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = 4);
|
||||
CRC32();
|
||||
void Update(const byte *input, size_t length);
|
||||
void TruncatedFinal(byte *hash, size_t size);
|
||||
unsigned int DigestSize() const {return DIGESTSIZE;}
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "CRC32";}
|
||||
std::string AlgorithmName() const {return StaticAlgorithmName();}
|
||||
|
||||
void UpdateByte(byte b) {m_crc = m_tab[CRC32_INDEX(m_crc) ^ b] ^ CRC32_SHIFTED(m_crc);}
|
||||
byte GetCrcByte(size_t i) const {return reinterpret_cast<const byte *>(&m_crc)[i];}
|
||||
|
||||
std::string AlgorithmProvider() const;
|
||||
|
||||
protected:
|
||||
void Reset() {m_crc = CRC32_NEGL;}
|
||||
|
||||
private:
|
||||
static const word32 m_tab[256];
|
||||
word32 m_crc;
|
||||
};
|
||||
|
||||
/// \brief CRC-32C Checksum Calculation
|
||||
/// \details Uses CRC polynomial 0x82F63B78
|
||||
/// \since Crypto++ 5.6.4
|
||||
class CRC32C : public HashTransformation
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = 4);
|
||||
CRC32C();
|
||||
void Update(const byte *input, size_t length);
|
||||
void TruncatedFinal(byte *hash, size_t size);
|
||||
unsigned int DigestSize() const {return DIGESTSIZE;}
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "CRC32C";}
|
||||
std::string AlgorithmName() const {return StaticAlgorithmName();}
|
||||
|
||||
void UpdateByte(byte b) {m_crc = m_tab[CRC32_INDEX(m_crc) ^ b] ^ CRC32_SHIFTED(m_crc);}
|
||||
byte GetCrcByte(size_t i) const {return reinterpret_cast<const byte *>(&m_crc)[i];}
|
||||
|
||||
std::string AlgorithmProvider() const;
|
||||
|
||||
protected:
|
||||
void Reset() {m_crc = CRC32_NEGL;}
|
||||
|
||||
private:
|
||||
static const word32 m_tab[256];
|
||||
word32 m_crc;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
// crc_simd.cpp - written and placed in the public domain by
|
||||
// Jeffrey Walton, Uri Blumenthal and Marcel Raad.
|
||||
//
|
||||
// This source file uses intrinsics to gain access to SSE4.2 and
|
||||
// ARMv8a CRC-32 and CRC-32C instructions. A separate source file
|
||||
// is needed because additional CXXFLAGS are required to enable
|
||||
// the appropriate instructions sets in some build configurations.
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
#include "misc.h"
|
||||
|
||||
#if (CRYPTOPP_SSE42_AVAILABLE)
|
||||
# include <nmmintrin.h>
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_ARM_NEON_HEADER)
|
||||
# include <arm_neon.h>
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_ARM_ACLE_HEADER)
|
||||
# include <stdint.h>
|
||||
# include <arm_acle.h>
|
||||
#endif
|
||||
|
||||
#ifdef CRYPTOPP_GNU_STYLE_INLINE_ASSEMBLY
|
||||
# include <signal.h>
|
||||
# include <setjmp.h>
|
||||
#endif
|
||||
|
||||
#ifndef EXCEPTION_EXECUTE_HANDLER
|
||||
# define EXCEPTION_EXECUTE_HANDLER 1
|
||||
#endif
|
||||
|
||||
// Squash MS LNK4221 and libtool warnings
|
||||
extern const char CRC_SIMD_FNAME[] = __FILE__;
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
#ifdef CRYPTOPP_GNU_STYLE_INLINE_ASSEMBLY
|
||||
extern "C" {
|
||||
typedef void (*SigHandler)(int);
|
||||
|
||||
static jmp_buf s_jmpSIGILL;
|
||||
static void SigIllHandler(int)
|
||||
{
|
||||
longjmp(s_jmpSIGILL, 1);
|
||||
}
|
||||
}
|
||||
#endif // Not CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY
|
||||
|
||||
#if (CRYPTOPP_BOOL_ARM32 || CRYPTOPP_BOOL_ARMV8)
|
||||
|
||||
bool CPU_ProbeCRC32()
|
||||
{
|
||||
#if defined(CRYPTOPP_NO_CPU_FEATURE_PROBES)
|
||||
return false;
|
||||
#elif (CRYPTOPP_ARM_CRC32_AVAILABLE)
|
||||
# if defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY)
|
||||
volatile bool result = true;
|
||||
__try
|
||||
{
|
||||
word32 w=0, x=1; word16 y=2; byte z=3;
|
||||
w = __crc32w(w,x);
|
||||
w = __crc32h(w,y);
|
||||
w = __crc32b(w,z);
|
||||
w = __crc32cw(w,x);
|
||||
w = __crc32ch(w,y);
|
||||
w = __crc32cb(w,z);
|
||||
|
||||
result = !!w;
|
||||
}
|
||||
__except (EXCEPTION_EXECUTE_HANDLER)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return result;
|
||||
#else
|
||||
|
||||
// longjmp and clobber warnings. Volatile is required.
|
||||
// http://github.com/weidai11/cryptopp/issues/24 and http://stackoverflow.com/q/7721854
|
||||
volatile bool result = true;
|
||||
|
||||
volatile SigHandler oldHandler = signal(SIGILL, SigIllHandler);
|
||||
if (oldHandler == SIG_ERR)
|
||||
return false;
|
||||
|
||||
volatile sigset_t oldMask;
|
||||
if (sigprocmask(0, NULLPTR, (sigset_t*)&oldMask))
|
||||
{
|
||||
signal(SIGILL, oldHandler);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (setjmp(s_jmpSIGILL))
|
||||
result = false;
|
||||
else
|
||||
{
|
||||
word32 w=0, x=1; word16 y=2; byte z=3;
|
||||
w = __crc32w(w,x);
|
||||
w = __crc32h(w,y);
|
||||
w = __crc32b(w,z);
|
||||
w = __crc32cw(w,x);
|
||||
w = __crc32ch(w,y);
|
||||
w = __crc32cb(w,z);
|
||||
|
||||
// Hack... GCC optimizes away the code and returns true
|
||||
result = !!w;
|
||||
}
|
||||
|
||||
sigprocmask(SIG_SETMASK, (sigset_t*)&oldMask, NULLPTR);
|
||||
signal(SIGILL, oldHandler);
|
||||
return result;
|
||||
# endif
|
||||
#else
|
||||
return false;
|
||||
#endif // CRYPTOPP_ARM_CRC32_AVAILABLE
|
||||
}
|
||||
#endif // ARM32 or ARM64
|
||||
|
||||
#if (CRYPTOPP_ARM_CRC32_AVAILABLE)
|
||||
void CRC32_Update_ARMV8(const byte *s, size_t n, word32& c)
|
||||
{
|
||||
for(; !IsAligned<word32>(s) && n > 0; s++, n--)
|
||||
c = __crc32b(c, *s);
|
||||
|
||||
for(; n > 4; s+=4, n-=4)
|
||||
c = __crc32w(c, *(const word32 *)(void*)s);
|
||||
|
||||
for(; n > 0; s++, n--)
|
||||
c = __crc32b(c, *s);
|
||||
}
|
||||
|
||||
void CRC32C_Update_ARMV8(const byte *s, size_t n, word32& c)
|
||||
{
|
||||
for(; !IsAligned<word32>(s) && n > 0; s++, n--)
|
||||
c = __crc32cb(c, *s);
|
||||
|
||||
for(; n > 4; s+=4, n-=4)
|
||||
c = __crc32cw(c, *(const word32 *)(void*)s);
|
||||
|
||||
for(; n > 0; s++, n--)
|
||||
c = __crc32cb(c, *s);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if (CRYPTOPP_SSE42_AVAILABLE)
|
||||
void CRC32C_Update_SSE42(const byte *s, size_t n, word32& c)
|
||||
{
|
||||
for(; !IsAligned<word32>(s) && n > 0; s++, n--)
|
||||
c = _mm_crc32_u8(c, *s);
|
||||
|
||||
for(; n > 4; s+=4, n-=4)
|
||||
c = _mm_crc32_u32(c, *(const word32 *)(void*)s);
|
||||
|
||||
for(; n > 0; s++, n--)
|
||||
c = _mm_crc32_u8(c, *s);
|
||||
}
|
||||
#endif
|
||||
|
||||
NAMESPACE_END
|
||||
+1054
File diff suppressed because it is too large
Load Diff
+3362
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
#ifndef _CRYPTOPPLIBLINK_H_
|
||||
#define _CRYPTOPPLIBLINK_H_
|
||||
|
||||
#ifdef _DLL
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
#define CRYPTOPP_IMPORTS
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(CRYPTOPP_IMPORTS)
|
||||
#include "dll.h"
|
||||
#else
|
||||
#ifdef _WIN32
|
||||
#ifdef _DEBUG
|
||||
#pragma comment( lib, "Cryptopp_lib_debug.lib" )
|
||||
#else
|
||||
#pragma comment( lib, "Cryptopp_lib_release.lib" )
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#endif /* !_CRYPTOPPLIBLINK_H_ */
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
// darn.cpp - written and placed in public domain by Jeffrey Walton
|
||||
|
||||
#include "pch.h"
|
||||
#include "config.h"
|
||||
#include "cryptlib.h"
|
||||
#include "secblock.h"
|
||||
#include "darn.h"
|
||||
#include "cpu.h"
|
||||
|
||||
// At the moment only GCC 7.0 (and above) seems to support __builtin_darn()
|
||||
// and __builtin_darn_32(). Clang 7.0 does not provide them, but it does
|
||||
// support assembly instructions. XLC is unknown, but there are no hits when
|
||||
// searching IBM's site. To cover more platforms we provide GCC inline
|
||||
// assembly like we do with RDRAND and RDSEED. Platforms that don't support
|
||||
// GCC inline assembly or the builtin will fail the compile.
|
||||
|
||||
// Inline assembler available in GCC 3.2 or above. For practical
|
||||
// purposes we check for GCC 4.0 or above. GCC imposters claim
|
||||
// to be GCC 4.2.1 so it will capture them, too. We exclude the
|
||||
// Apple machines because they are not Power9 and use a slightly
|
||||
// different syntax in their assembler.
|
||||
#if ((__GNUC__ >= 4) || defined(__IBM_GCC_ASM)) && !defined(__APPLE__)
|
||||
# define GCC_DARN_ASM_AVAILABLE 1
|
||||
#endif
|
||||
|
||||
// warning C4702: unreachable code
|
||||
#if CRYPTOPP_MSC_VERSION
|
||||
# pragma warning(disable: 4702)
|
||||
#endif
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
#if (CRYPTOPP_BOOL_PPC32 || CRYPTOPP_BOOL_PPC64)
|
||||
|
||||
// *************************** 32-bit *************************** //
|
||||
|
||||
#if (CRYPTOPP_BOOL_PPC32)
|
||||
|
||||
// Fills 4 bytes, buffer must be aligned
|
||||
inline void DARN32(void* output)
|
||||
{
|
||||
CRYPTOPP_ASSERT(IsAlignedOn(output, GetAlignmentOf<word32>()));
|
||||
word32* ptr = reinterpret_cast<word32*>(output);
|
||||
|
||||
#if defined(GCC_DARN_ASM_AVAILABLE)
|
||||
// This is "darn r3, 0". When L=0 a 32-bit conditioned word
|
||||
// is returned. On failure 0xffffffffffffffff is returned.
|
||||
// The Power manual recommends only checking the low 32-bit
|
||||
// word for this case. See Power ISA 3.0 specification, p. 78.
|
||||
do
|
||||
{
|
||||
__asm__ __volatile__ (
|
||||
#if (CRYPTOPP_BIG_ENDIAN)
|
||||
".byte 0x7c, 0x60, 0x05, 0xe6 \n\t" // r3 = darn 3, 0
|
||||
"mr %0, 3 \n\t" // val = r3
|
||||
#else
|
||||
".byte 0xe6, 0x05, 0x60, 0x7c \n\t" // r3 = darn 3, 0
|
||||
"mr %0, 3 \n\t" // val = r3
|
||||
#endif
|
||||
: "=r" (*ptr) : : "r3"
|
||||
);
|
||||
} while (*ptr == 0xFFFFFFFFu);
|
||||
#elif defined(_ARCH_PWR9)
|
||||
// This is probably going to break some platforms.
|
||||
// We will deal with them as we encounter them.
|
||||
*ptr = __builtin_darn_32();
|
||||
#elif defined(__APPLE__)
|
||||
// Nop. Apple G4 and G5 machines are too old. They will
|
||||
// avoid this code path because HasPower9() returns false.
|
||||
CRYPTOPP_ASSERT(0);
|
||||
#else
|
||||
// Catch other compile breaks
|
||||
int XXX[-1];
|
||||
#endif
|
||||
}
|
||||
#endif // PPC32
|
||||
|
||||
// *************************** 64-bit *************************** //
|
||||
|
||||
#if (CRYPTOPP_BOOL_PPC64)
|
||||
|
||||
// Fills 8 bytes, buffer must be aligned
|
||||
inline void DARN64(void* output)
|
||||
{
|
||||
CRYPTOPP_ASSERT(IsAlignedOn(output, GetAlignmentOf<word64>()));
|
||||
word64* ptr = reinterpret_cast<word64*>(output);
|
||||
|
||||
#if defined(GCC_DARN_ASM_AVAILABLE)
|
||||
// This is "darn r3, 1". When L=1 a 64-bit conditioned word
|
||||
// is returned. On failure 0xffffffffffffffff is returned.
|
||||
// See Power ISA 3.0 specification, p. 78.
|
||||
do
|
||||
{
|
||||
__asm__ __volatile__ (
|
||||
#if (CRYPTOPP_BIG_ENDIAN)
|
||||
".byte 0x7c, 0x61, 0x05, 0xe6 \n\t" // r3 = darn 3, 1
|
||||
"mr %0, 3 \n\t" // val = r3
|
||||
#else
|
||||
".byte 0xe6, 0x05, 0x61, 0x7c \n\t" // r3 = darn 3, 1
|
||||
"mr %0, 3 \n\t" // val = r3
|
||||
#endif
|
||||
: "=r" (*ptr) : : "r3"
|
||||
);
|
||||
} while (*ptr == 0xFFFFFFFFFFFFFFFFull);
|
||||
#elif defined(_ARCH_PWR9)
|
||||
// This is probably going to break some platforms.
|
||||
// We will deal with them as we encounter them.
|
||||
*ptr = __builtin_darn();
|
||||
#elif defined(__APPLE__)
|
||||
// Nop. Apple G4 and G5 machines are too old. They will
|
||||
// avoid this code path because HasPower9() returns false.
|
||||
CRYPTOPP_ASSERT(0);
|
||||
#else
|
||||
// Catch other compile breaks
|
||||
int XXX[-1];
|
||||
#endif
|
||||
}
|
||||
#endif // PPC64
|
||||
|
||||
// ************************ Standard C++ ************************ //
|
||||
|
||||
DARN::DARN()
|
||||
{
|
||||
if (!HasDARN())
|
||||
throw DARN_Err("HasDARN");
|
||||
|
||||
// Scratch buffer in case user buffers are unaligned.
|
||||
m_temp.New(8);
|
||||
}
|
||||
|
||||
void DARN::GenerateBlock(byte *output, size_t size)
|
||||
{
|
||||
CRYPTOPP_ASSERT((output && size) || !(output || size));
|
||||
if (size == 0) return;
|
||||
size_t i = 0;
|
||||
|
||||
#if (CRYPTOPP_BOOL_PPC64)
|
||||
|
||||
// Check alignment
|
||||
i = reinterpret_cast<uintptr_t>(output) & 0x7;
|
||||
if (i != 0)
|
||||
{
|
||||
DARN64(m_temp);
|
||||
std::memcpy(output, m_temp, i);
|
||||
|
||||
output += i;
|
||||
size -= i;
|
||||
}
|
||||
|
||||
// Output is aligned
|
||||
for (i = 0; i < size/8; i++)
|
||||
DARN64(output+i*8);
|
||||
|
||||
output += i*8;
|
||||
size -= i*8;
|
||||
|
||||
if (size)
|
||||
{
|
||||
DARN64(m_temp);
|
||||
std::memcpy(output, m_temp, size);
|
||||
}
|
||||
|
||||
#elif (CRYPTOPP_BOOL_PPC32)
|
||||
|
||||
// Check alignment
|
||||
i = reinterpret_cast<uintptr_t>(output) & 0x3;
|
||||
if (i != 0)
|
||||
{
|
||||
DARN32(m_temp);
|
||||
std::memcpy(output, m_temp, i);
|
||||
|
||||
output += i;
|
||||
size -= i;
|
||||
}
|
||||
|
||||
// Output is aligned
|
||||
for (i = 0; i < size/4; i++)
|
||||
DARN32(output+i*4);
|
||||
|
||||
output += i*4;
|
||||
size -= i*4;
|
||||
|
||||
if (size)
|
||||
{
|
||||
DARN32(m_temp);
|
||||
std::memcpy(output, m_temp, size);
|
||||
}
|
||||
|
||||
#else
|
||||
// No suitable compiler found
|
||||
CRYPTOPP_UNUSED(output);
|
||||
throw NotImplemented("DARN: failed to find a suitable implementation");
|
||||
#endif
|
||||
}
|
||||
|
||||
void DARN::DiscardBytes(size_t n)
|
||||
{
|
||||
// RoundUpToMultipleOf is used because a full word is read, and its cheaper
|
||||
// to discard full words. There's no sense in dealing with tail bytes.
|
||||
FixedSizeSecBlock<word64, 16> discard;
|
||||
n = RoundUpToMultipleOf(n, sizeof(word64));
|
||||
|
||||
size_t count = STDMIN(n, discard.SizeInBytes());
|
||||
while (count)
|
||||
{
|
||||
GenerateBlock(discard.BytePtr(), count);
|
||||
n -= count;
|
||||
count = STDMIN(n, discard.SizeInBytes());
|
||||
}
|
||||
}
|
||||
|
||||
#else // not PPC32 or PPC64
|
||||
|
||||
DARN::DARN()
|
||||
{
|
||||
throw DARN_Err("HasDARN");
|
||||
}
|
||||
|
||||
void DARN::GenerateBlock(byte *output, size_t size)
|
||||
{
|
||||
// Constructor will throw, should not get here
|
||||
CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size);
|
||||
}
|
||||
|
||||
void DARN::DiscardBytes(size_t n)
|
||||
{
|
||||
// Constructor will throw, should not get here
|
||||
CRYPTOPP_UNUSED(n);
|
||||
}
|
||||
|
||||
#endif // PPC32 or PPC64
|
||||
|
||||
NAMESPACE_END
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
// darn.h - written and placed in public domain by Jeffrey Walton
|
||||
// DARN requires POWER9/ISA 3.0.
|
||||
|
||||
// At the moment only GCC 7.0 (and above) seems to support __builtin_darn()
|
||||
// and __builtin_darn_32(). However, GCC generates incorrect code. Clang 7.0
|
||||
// does not provide them, but it does support assembly instructions. XLC is
|
||||
// unknown, but there are no hits when searching IBM's site. To cover more
|
||||
// platforms we provide GCC inline assembly like we do with RDRAND and RDSEED.
|
||||
// Platforms that don't support GCC inline assembly or the builtin will fail
|
||||
// to compile. Also see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91481 and
|
||||
// https://gcc.gnu.org/onlinedocs/gcc/Basic-PowerPC-Built-in-Functions-Available-on-ISA-3_002e0.html
|
||||
|
||||
/// \file darn.h
|
||||
/// \brief Classes for DARN RNG
|
||||
/// \sa <A HREF="https://openpowerfoundation.org/?resource_lib=power-isa-version-3-0">Power
|
||||
/// ISA Version 3.0B</A>
|
||||
/// \since Crypto++ 8.0
|
||||
|
||||
#ifndef CRYPTOPP_DARN_H
|
||||
#define CRYPTOPP_DARN_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief Exception thrown when a DARN generator encounters
|
||||
/// a generator related error.
|
||||
/// \since Crypto++ 8.0
|
||||
class DARN_Err : public Exception
|
||||
{
|
||||
public:
|
||||
DARN_Err(const std::string &operation)
|
||||
: Exception(OTHER_ERROR, "DARN: " + operation + " operation failed") {}
|
||||
};
|
||||
|
||||
/// \brief Hardware generated random numbers using DARN instruction
|
||||
/// \details DARN() provides access to Power9's random number generator. The
|
||||
/// Crypto++ implementation provides conditioned random numbers from the
|
||||
/// generator as opposed to raw random numbers. According to Power ISA 3.0B
|
||||
/// manual, a conditioned random number has been processed by hardware to
|
||||
/// reduce bias. A raw random number is unconditioned noise source output.
|
||||
/// \details According to Power ISA 3.0B manual, the random number generator
|
||||
/// provided by the <tt>darn</tt> instruction is NIST SP800-90B and SP800-90C
|
||||
/// compliant to the extent possible given the completeness of the standards
|
||||
/// at the time the hardware is designed. The random number generator provides
|
||||
/// a minimum of 0.5 bits of entropy per bit.
|
||||
/// \par Wraps
|
||||
/// darn instruction
|
||||
/// \sa <A HREF="https://openpowerfoundation.org/?resource_lib=power-isa-version-3-0">Power
|
||||
/// ISA Version 3.0B</A>, MaurerRandomnessTest() for random bit generators
|
||||
/// \since Crypto++ 8.0
|
||||
class DARN : public RandomNumberGenerator
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() { return "DARN"; }
|
||||
|
||||
virtual ~DARN() {}
|
||||
|
||||
/// \brief Construct a DARN generator
|
||||
/// \throw DARN_Err if the random number generator is not available
|
||||
DARN();
|
||||
|
||||
/// \brief Generate random array of bytes
|
||||
/// \param output the byte buffer
|
||||
/// \param size the length of the buffer, in bytes
|
||||
virtual void GenerateBlock(byte *output, size_t size);
|
||||
|
||||
/// \brief Generate and discard n bytes
|
||||
/// \param n the number of bytes to generate and discard
|
||||
/// \details the RDSEED generator discards words, not bytes. If n is
|
||||
/// not a multiple of a machine word, then it is rounded up to
|
||||
/// that size.
|
||||
virtual void DiscardBytes(size_t n);
|
||||
|
||||
/// \brief Update RNG state with additional unpredictable values
|
||||
/// \param input unused
|
||||
/// \param length unused
|
||||
/// \details The operation is a nop for this generator.
|
||||
virtual void IncorporateEntropy(const byte *input, size_t length)
|
||||
{
|
||||
// Override to avoid the base class' throw.
|
||||
CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
|
||||
}
|
||||
|
||||
std::string AlgorithmProvider() const {
|
||||
return "Power9";
|
||||
}
|
||||
|
||||
private:
|
||||
SecBlock<byte, AllocatorWithCleanup<byte, true> > m_temp;
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif // CRYPTOPP_DARN_H
|
||||
+1012
File diff suppressed because it is too large
Load Diff
+307
@@ -0,0 +1,307 @@
|
||||
// default.cpp - originally 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)
|
||||
#endif
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "filters.h"
|
||||
#include "smartptr.h"
|
||||
#include "default.h"
|
||||
#include "queue.h"
|
||||
|
||||
#include <time.h>
|
||||
#include <memory>
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
// The purpose of this function Mash() is to take an arbitrary length input
|
||||
// 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 string, whichever is smaller.
|
||||
|
||||
template <class H>
|
||||
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)H::DIGESTSIZE);
|
||||
byte b[2];
|
||||
SecByteBlock buf(bufSize);
|
||||
SecByteBlock outBuf(bufSize);
|
||||
H hash;
|
||||
|
||||
unsigned int i;
|
||||
for(i=0; i<outLen; i+=H::DIGESTSIZE)
|
||||
{
|
||||
b[0] = (byte) (i >> 8);
|
||||
b[1] = (byte) i;
|
||||
hash.Update(b, 2);
|
||||
hash.Update(in, inLen);
|
||||
hash.Final(outBuf+i);
|
||||
}
|
||||
|
||||
while (iterations-- > 1)
|
||||
{
|
||||
memcpy(buf, outBuf, bufSize);
|
||||
for (i=0; i<bufSize; i+=H::DIGESTSIZE)
|
||||
{
|
||||
b[0] = (byte) (i >> 8);
|
||||
b[1] = (byte) i;
|
||||
hash.Update(b, 2);
|
||||
hash.Update(buf, bufSize);
|
||||
hash.Final(outBuf+i);
|
||||
}
|
||||
}
|
||||
|
||||
memcpy(out, outBuf, outLen);
|
||||
}
|
||||
|
||||
template <class BC, class H, class Info>
|
||||
static void GenerateKeyIV(const byte *passphrase, size_t passphraseLength, const byte *salt, size_t saltLength, unsigned int iterations, byte *key, byte *IV)
|
||||
{
|
||||
// UBsan. User supplied params, may be NULL
|
||||
SecByteBlock temp(passphraseLength+saltLength);
|
||||
if (passphrase != NULLPTR)
|
||||
memcpy(temp, passphrase, passphraseLength);
|
||||
if (salt != NULLPTR)
|
||||
memcpy(temp+passphraseLength, salt, saltLength);
|
||||
|
||||
// OK. Derived params, cannot be NULL
|
||||
SecByteBlock keyIV(Info::KEYLENGTH+Info::BLOCKSIZE);
|
||||
Mash<H>(temp, passphraseLength + saltLength, keyIV, Info::KEYLENGTH+Info::BLOCKSIZE, iterations);
|
||||
memcpy(key, keyIV, Info::KEYLENGTH);
|
||||
memcpy(IV, keyIV+Info::KEYLENGTH, Info::BLOCKSIZE);
|
||||
}
|
||||
|
||||
// ********************************************************
|
||||
|
||||
template <class BC, class H, class Info>
|
||||
DataEncryptor<BC,H,Info>::DataEncryptor(const char *passphrase, BufferedTransformation *attachment)
|
||||
: ProxyFilter(NULLPTR, 0, 0, attachment), m_passphrase((const byte *)passphrase, strlen(passphrase))
|
||||
{
|
||||
CRYPTOPP_COMPILE_ASSERT((int)SALTLENGTH <= DIGESTSIZE);
|
||||
CRYPTOPP_COMPILE_ASSERT((int)BLOCKSIZE <= (int)DIGESTSIZE);
|
||||
}
|
||||
|
||||
template <class BC, class H, class Info>
|
||||
DataEncryptor<BC,H,Info>::DataEncryptor(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment)
|
||||
: ProxyFilter(NULLPTR, 0, 0, attachment), m_passphrase(passphrase, passphraseLength)
|
||||
{
|
||||
CRYPTOPP_COMPILE_ASSERT((int)SALTLENGTH <= (int)DIGESTSIZE);
|
||||
CRYPTOPP_COMPILE_ASSERT((int)BLOCKSIZE <= (int)DIGESTSIZE);
|
||||
}
|
||||
|
||||
template <class BC, class H, class Info>
|
||||
void DataEncryptor<BC,H,Info>::FirstPut(const byte *)
|
||||
{
|
||||
SecByteBlock salt(DIGESTSIZE), keyCheck(DIGESTSIZE);
|
||||
H hash;
|
||||
|
||||
// use hash(passphrase | time | clock) as salt
|
||||
hash.Update(m_passphrase, m_passphrase.size());
|
||||
time_t t=time(NULLPTR);
|
||||
hash.Update((byte *)&t, sizeof(t));
|
||||
clock_t c=clock();
|
||||
hash.Update((byte *)&c, sizeof(c));
|
||||
hash.Final(salt);
|
||||
|
||||
// use hash(passphrase | salt) as key check
|
||||
hash.Update(m_passphrase, m_passphrase.size());
|
||||
hash.Update(salt, SALTLENGTH);
|
||||
hash.Final(keyCheck);
|
||||
|
||||
AttachedTransformation()->Put(salt, SALTLENGTH);
|
||||
|
||||
// mash passphrase and salt together into key and IV
|
||||
SecByteBlock key(KEYLENGTH);
|
||||
SecByteBlock IV(BLOCKSIZE);
|
||||
GenerateKeyIV<BC,H,Info>(m_passphrase, m_passphrase.size(), salt, SALTLENGTH, ITERATIONS, key, IV);
|
||||
|
||||
m_cipher.SetKeyWithIV(key, key.size(), IV);
|
||||
SetFilter(new StreamTransformationFilter(m_cipher));
|
||||
|
||||
m_filter->Put(keyCheck, BLOCKSIZE);
|
||||
}
|
||||
|
||||
template <class BC, class H, class Info>
|
||||
void DataEncryptor<BC,H,Info>::LastPut(const byte *inString, size_t length)
|
||||
{
|
||||
CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
|
||||
m_filter->MessageEnd();
|
||||
}
|
||||
|
||||
// ********************************************************
|
||||
|
||||
template <class BC, class H, class Info>
|
||||
DataDecryptor<BC,H,Info>::DataDecryptor(const char *p, BufferedTransformation *attachment, bool throwException)
|
||||
: ProxyFilter(NULLPTR, SALTLENGTH+BLOCKSIZE, 0, attachment)
|
||||
, m_state(WAITING_FOR_KEYCHECK)
|
||||
, m_passphrase((const byte *)p, strlen(p))
|
||||
, m_throwException(throwException)
|
||||
{
|
||||
CRYPTOPP_COMPILE_ASSERT((int)SALTLENGTH <= (int)DIGESTSIZE);
|
||||
CRYPTOPP_COMPILE_ASSERT((int)BLOCKSIZE <= (int)DIGESTSIZE);
|
||||
}
|
||||
|
||||
template <class BC, class H, class Info>
|
||||
DataDecryptor<BC,H,Info>::DataDecryptor(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment, bool throwException)
|
||||
: ProxyFilter(NULLPTR, SALTLENGTH+BLOCKSIZE, 0, attachment)
|
||||
, m_state(WAITING_FOR_KEYCHECK)
|
||||
, m_passphrase(passphrase, passphraseLength)
|
||||
, m_throwException(throwException)
|
||||
{
|
||||
CRYPTOPP_COMPILE_ASSERT((int)SALTLENGTH <= (int)DIGESTSIZE);
|
||||
CRYPTOPP_COMPILE_ASSERT((int)BLOCKSIZE <= (int)DIGESTSIZE);
|
||||
}
|
||||
|
||||
template <class BC, class H, class Info>
|
||||
void DataDecryptor<BC,H,Info>::FirstPut(const byte *inString)
|
||||
{
|
||||
CheckKey(inString, inString+SALTLENGTH);
|
||||
}
|
||||
|
||||
template <class BC, class H, class Info>
|
||||
void DataDecryptor<BC,H,Info>::LastPut(const byte *inString, size_t length)
|
||||
{
|
||||
CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
|
||||
if (m_filter.get() == NULLPTR)
|
||||
{
|
||||
m_state = KEY_BAD;
|
||||
if (m_throwException)
|
||||
throw KeyBadErr();
|
||||
}
|
||||
else
|
||||
{
|
||||
m_filter->MessageEnd();
|
||||
m_state = WAITING_FOR_KEYCHECK;
|
||||
}
|
||||
}
|
||||
|
||||
template <class BC, class H, class Info>
|
||||
void DataDecryptor<BC,H,Info>::CheckKey(const byte *salt, const byte *keyCheck)
|
||||
{
|
||||
SecByteBlock check(STDMAX((unsigned int)2*BLOCKSIZE, (unsigned int)DIGESTSIZE));
|
||||
|
||||
H hash;
|
||||
hash.Update(m_passphrase, m_passphrase.size());
|
||||
hash.Update(salt, SALTLENGTH);
|
||||
hash.Final(check);
|
||||
|
||||
SecByteBlock key(KEYLENGTH);
|
||||
SecByteBlock IV(BLOCKSIZE);
|
||||
GenerateKeyIV<BC,H,Info>(m_passphrase, m_passphrase.size(), salt, SALTLENGTH, ITERATIONS, key, IV);
|
||||
|
||||
m_cipher.SetKeyWithIV(key, key.size(), IV);
|
||||
member_ptr<StreamTransformationFilter> decryptor(new StreamTransformationFilter(m_cipher));
|
||||
|
||||
decryptor->Put(keyCheck, BLOCKSIZE);
|
||||
decryptor->ForceNextPut();
|
||||
decryptor->Get(check+BLOCKSIZE, BLOCKSIZE);
|
||||
|
||||
SetFilter(decryptor.release());
|
||||
|
||||
if (!VerifyBufsEqual(check, check+BLOCKSIZE, BLOCKSIZE))
|
||||
{
|
||||
m_state = KEY_BAD;
|
||||
if (m_throwException)
|
||||
throw KeyBadErr();
|
||||
}
|
||||
else
|
||||
m_state = KEY_GOOD;
|
||||
}
|
||||
|
||||
// ********************************************************
|
||||
|
||||
template <class H, class MAC>
|
||||
static MAC* NewDataEncryptorMAC(const byte *passphrase, size_t passphraseLength)
|
||||
{
|
||||
size_t macKeyLength = MAC::StaticGetValidKeyLength(16);
|
||||
SecByteBlock macKey(macKeyLength);
|
||||
// since the MAC is encrypted there is no reason to mash the passphrase for many iterations
|
||||
Mash<H>(passphrase, passphraseLength, macKey, macKeyLength, 1);
|
||||
return new MAC(macKey, macKeyLength);
|
||||
}
|
||||
|
||||
template <class BC, class H, class MAC, class Info>
|
||||
DataEncryptorWithMAC<BC,H,MAC,Info>::DataEncryptorWithMAC(const char *passphrase, BufferedTransformation *attachment)
|
||||
: ProxyFilter(NULLPTR, 0, 0, attachment)
|
||||
, m_mac(NewDataEncryptorMAC<H,MAC>((const byte *)passphrase, strlen(passphrase)))
|
||||
{
|
||||
SetFilter(new HashFilter(*m_mac, new DataEncryptor<BC,H,Info>(passphrase), true));
|
||||
}
|
||||
|
||||
template <class BC, class H, class MAC, class Info>
|
||||
DataEncryptorWithMAC<BC,H,MAC,Info>::DataEncryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment)
|
||||
: ProxyFilter(NULLPTR, 0, 0, attachment)
|
||||
, m_mac(NewDataEncryptorMAC<H,MAC>(passphrase, passphraseLength))
|
||||
{
|
||||
SetFilter(new HashFilter(*m_mac, new DataEncryptor<BC,H,Info>(passphrase, passphraseLength), true));
|
||||
}
|
||||
|
||||
template <class BC, class H, class MAC, class Info>
|
||||
void DataEncryptorWithMAC<BC,H,MAC,Info>::LastPut(const byte *inString, size_t length)
|
||||
{
|
||||
CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
|
||||
m_filter->MessageEnd();
|
||||
}
|
||||
|
||||
// ********************************************************
|
||||
|
||||
template <class BC, class H, class MAC, class Info>
|
||||
DataDecryptorWithMAC<BC,H,MAC,Info>::DataDecryptorWithMAC(const char *passphrase, BufferedTransformation *attachment, bool throwException)
|
||||
: ProxyFilter(NULLPTR, 0, 0, attachment)
|
||||
, m_mac(NewDataEncryptorMAC<H,MAC>((const byte *)passphrase, strlen(passphrase)))
|
||||
, m_throwException(throwException)
|
||||
{
|
||||
SetFilter(new DataDecryptor<BC,H,Info>(passphrase, m_hashVerifier=new HashVerificationFilter(*m_mac, NULLPTR, HashVerificationFilter::PUT_MESSAGE), throwException));
|
||||
}
|
||||
|
||||
template <class BC, class H, class MAC, class Info>
|
||||
DataDecryptorWithMAC<BC,H,MAC,Info>::DataDecryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment, bool throwException)
|
||||
: ProxyFilter(NULLPTR, 0, 0, attachment)
|
||||
, m_mac(NewDataEncryptorMAC<H,MAC>(passphrase, passphraseLength))
|
||||
, m_throwException(throwException)
|
||||
{
|
||||
SetFilter(new DataDecryptor<BC,H,Info>(passphrase, passphraseLength, m_hashVerifier=new HashVerificationFilter(*m_mac, NULLPTR, HashVerificationFilter::PUT_MESSAGE), throwException));
|
||||
}
|
||||
|
||||
template <class BC, class H, class MAC, class Info>
|
||||
typename DataDecryptor<BC,H,Info>::State DataDecryptorWithMAC<BC,H,MAC,Info>::CurrentState() const
|
||||
{
|
||||
return static_cast<const DataDecryptor<BC,H,Info> *>(m_filter.get())->CurrentState();
|
||||
}
|
||||
|
||||
template <class BC, class H, class MAC, class Info>
|
||||
bool DataDecryptorWithMAC<BC,H,MAC,Info>::CheckLastMAC() const
|
||||
{
|
||||
return m_hashVerifier->GetLastResult();
|
||||
}
|
||||
|
||||
template <class BC, class H, class MAC, class Info>
|
||||
void DataDecryptorWithMAC<BC,H,MAC,Info>::LastPut(const byte *inString, size_t length)
|
||||
{
|
||||
CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
|
||||
m_filter->MessageEnd();
|
||||
if (m_throwException && !CheckLastMAC())
|
||||
throw MACBadErr();
|
||||
}
|
||||
|
||||
template struct DataParametersInfo<LegacyBlockCipher::BLOCKSIZE, LegacyBlockCipher::DEFAULT_KEYLENGTH, LegacyHashModule::DIGESTSIZE, 8, 200>;
|
||||
template struct DataParametersInfo<DefaultBlockCipher::BLOCKSIZE, DefaultBlockCipher::DEFAULT_KEYLENGTH, DefaultHashModule::DIGESTSIZE, 8, 2500>;
|
||||
|
||||
template class DataEncryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo>;
|
||||
template class DataDecryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo>;
|
||||
template class DataEncryptor<DefaultBlockCipher,DefaultHashModule,DefaultParametersInfo>;
|
||||
template class DataDecryptor<DefaultBlockCipher,DefaultHashModule,DefaultParametersInfo>;
|
||||
template class DataEncryptorWithMAC<LegacyBlockCipher,LegacyHashModule,LegacyMAC,LegacyParametersInfo>;
|
||||
template class DataDecryptorWithMAC<LegacyBlockCipher,LegacyHashModule,LegacyMAC,LegacyParametersInfo>;
|
||||
template class DataEncryptorWithMAC<DefaultBlockCipher,DefaultHashModule,DefaultMAC,DefaultParametersInfo>;
|
||||
template class DataDecryptorWithMAC<DefaultBlockCipher,DefaultHashModule,DefaultMAC,DefaultParametersInfo>;
|
||||
|
||||
NAMESPACE_END
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
// default.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file default.h
|
||||
/// \brief Classes for DefaultEncryptor, DefaultDecryptor, DefaultEncryptorWithMAC and DefaultDecryptorWithMAC
|
||||
|
||||
#ifndef CRYPTOPP_DEFAULT_H
|
||||
#define CRYPTOPP_DEFAULT_H
|
||||
|
||||
#include "sha.h"
|
||||
#include "hmac.h"
|
||||
#include "aes.h"
|
||||
#include "des.h"
|
||||
#include "modes.h"
|
||||
#include "filters.h"
|
||||
#include "smartptr.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief Legacy block cipher for LegacyEncryptor, LegacyDecryptor, LegacyEncryptorWithMAC and LegacyDecryptorWithMAC
|
||||
typedef DES_EDE2 LegacyBlockCipher;
|
||||
/// \brief Legacy hash for use with LegacyEncryptorWithMAC and LegacyDecryptorWithMAC
|
||||
typedef SHA1 LegacyHashModule;
|
||||
/// \brief Legacy HMAC for use withLegacyEncryptorWithMAC and LegacyDecryptorWithMAC
|
||||
typedef HMAC<LegacyHashModule> LegacyMAC;
|
||||
|
||||
/// \brief Default block cipher for DefaultEncryptor, DefaultDecryptor, DefaultEncryptorWithMAC and DefaultDecryptorWithMAC
|
||||
typedef AES DefaultBlockCipher;
|
||||
/// \brief Default hash for use with DefaultEncryptorWithMAC and DefaultDecryptorWithMAC
|
||||
typedef SHA256 DefaultHashModule;
|
||||
/// \brief Default HMAC for use withDefaultEncryptorWithMAC and DefaultDecryptorWithMAC
|
||||
typedef HMAC<DefaultHashModule> DefaultMAC;
|
||||
|
||||
/// \brief Exception thrown when LegacyDecryptorWithMAC or DefaultDecryptorWithMAC decryption error is encountered
|
||||
class DataDecryptorErr : public Exception
|
||||
{
|
||||
public:
|
||||
DataDecryptorErr(const std::string &s)
|
||||
: Exception(DATA_INTEGRITY_CHECK_FAILED, s) {}
|
||||
};
|
||||
|
||||
/// \brief Exception thrown when a bad key is encountered in DefaultDecryptorWithMAC and LegacyDecryptorWithMAC
|
||||
class KeyBadErr : public DataDecryptorErr
|
||||
{
|
||||
public: KeyBadErr()
|
||||
: DataDecryptorErr("DataDecryptor: cannot decrypt message with this passphrase") {}
|
||||
};
|
||||
|
||||
/// \brief Exception thrown when an incorrect MAC is encountered in DefaultDecryptorWithMAC and LegacyDecryptorWithMAC
|
||||
class MACBadErr : public DataDecryptorErr
|
||||
{
|
||||
public: MACBadErr()
|
||||
: DataDecryptorErr("DataDecryptorWithMAC: MAC check failed") {}
|
||||
};
|
||||
|
||||
/// \brief Algorithm information for password-based encryptors and decryptors
|
||||
template <unsigned int BlockSize, unsigned int KeyLength, unsigned int DigestSize, unsigned int SaltSize, unsigned int Iterations>
|
||||
struct DataParametersInfo
|
||||
{
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = BlockSize);
|
||||
CRYPTOPP_CONSTANT(KEYLENGTH = KeyLength);
|
||||
CRYPTOPP_CONSTANT(SALTLENGTH = SaltSize);
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = DigestSize);
|
||||
CRYPTOPP_CONSTANT(ITERATIONS = Iterations);
|
||||
};
|
||||
|
||||
typedef DataParametersInfo<LegacyBlockCipher::BLOCKSIZE, LegacyBlockCipher::DEFAULT_KEYLENGTH, LegacyHashModule::DIGESTSIZE, 8, 200> LegacyParametersInfo;
|
||||
typedef DataParametersInfo<DefaultBlockCipher::BLOCKSIZE, DefaultBlockCipher::DEFAULT_KEYLENGTH, DefaultHashModule::DIGESTSIZE, 8, 2500> DefaultParametersInfo;
|
||||
|
||||
/// \brief Password-based Encryptor
|
||||
/// \tparam BC BlockCipher based class used for encryption
|
||||
/// \tparam H HashTransformation based class used for mashing
|
||||
/// \tparam Info Constants used by the algorithms
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256.
|
||||
/// \sa DefaultEncryptor, DefaultDecryptor, LegacyEncryptor, LegacyDecryptor
|
||||
/// \since Crypto++ 2.0
|
||||
template <class BC, class H, class Info>
|
||||
class DataEncryptor : public ProxyFilter, public Info
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = Info::BLOCKSIZE);
|
||||
CRYPTOPP_CONSTANT(KEYLENGTH = Info::KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(SALTLENGTH = Info::SALTLENGTH);
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE);
|
||||
CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS);
|
||||
|
||||
/// \brief Construct a DataEncryptor
|
||||
/// \param passphrase a C-String password
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
DataEncryptor(const char *passphrase, BufferedTransformation *attachment = NULLPTR);
|
||||
|
||||
/// \brief Construct a DataEncryptor
|
||||
/// \param passphrase a byte string password
|
||||
/// \param passphraseLength the length of the byte string password
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
DataEncryptor(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR);
|
||||
|
||||
protected:
|
||||
void FirstPut(const byte *);
|
||||
void LastPut(const byte *inString, size_t length);
|
||||
|
||||
private:
|
||||
SecByteBlock m_passphrase;
|
||||
typename CBC_Mode<BC>::Encryption m_cipher;
|
||||
};
|
||||
|
||||
/// \brief Password-based Decryptor
|
||||
/// \tparam BC BlockCipher based class used for encryption
|
||||
/// \tparam H HashTransformation based class used for mashing
|
||||
/// \tparam Info Constants used by the algorithms
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256.
|
||||
/// \sa DefaultEncryptor, DefaultDecryptor, LegacyEncryptor, LegacyDecryptor
|
||||
/// \since Crypto++ 2.0
|
||||
template <class BC, class H, class Info>
|
||||
class DataDecryptor : public ProxyFilter, public Info
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = Info::BLOCKSIZE);
|
||||
CRYPTOPP_CONSTANT(KEYLENGTH = Info::KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(SALTLENGTH = Info::SALTLENGTH);
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE);
|
||||
CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS);
|
||||
|
||||
/// \brief Constructs a DataDecryptor
|
||||
/// \param passphrase a C-String password
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
/// \param throwException a flag specifiying whether an Exception should be thrown on error
|
||||
DataDecryptor(const char *passphrase, BufferedTransformation *attachment = NULLPTR, bool throwException=true);
|
||||
|
||||
/// \brief Constructs a DataDecryptor
|
||||
/// \param passphrase a byte string password
|
||||
/// \param passphraseLength the length of the byte string password
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
/// \param throwException a flag specifiying whether an Exception should be thrown on error
|
||||
DataDecryptor(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR, bool throwException=true);
|
||||
|
||||
enum State {WAITING_FOR_KEYCHECK, KEY_GOOD, KEY_BAD};
|
||||
State CurrentState() const {return m_state;}
|
||||
|
||||
protected:
|
||||
void FirstPut(const byte *inString);
|
||||
void LastPut(const byte *inString, size_t length);
|
||||
|
||||
State m_state;
|
||||
|
||||
private:
|
||||
void CheckKey(const byte *salt, const byte *keyCheck);
|
||||
|
||||
SecByteBlock m_passphrase;
|
||||
typename CBC_Mode<BC>::Decryption m_cipher;
|
||||
member_ptr<FilterWithBufferedInput> m_decryptor;
|
||||
bool m_throwException;
|
||||
|
||||
};
|
||||
|
||||
/// \brief Password-based encryptor with MAC
|
||||
/// \tparam BC BlockCipher based class used for encryption
|
||||
/// \tparam H HashTransformation based class used for mashing
|
||||
/// \tparam MAC HashTransformation based class used for authentication
|
||||
/// \tparam Info Constants used by the algorithms
|
||||
/// \details DataEncryptorWithMAC uses a non-standard mashup function called Mash() to derive key
|
||||
/// bits from the password.
|
||||
/// \details The purpose of the function Mash() is to take an arbitrary length input string and
|
||||
/// *deterministically* 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 string, whichever is smaller.
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256.
|
||||
/// \sa DefaultEncryptorWithMAC, DefaultDecryptorWithMAC, LegacyDecryptorWithMAC, LegacyEncryptorWithMAC
|
||||
/// \since Crypto++ 2.0
|
||||
template <class BC, class H, class MAC, class Info>
|
||||
class DataEncryptorWithMAC : public ProxyFilter
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = Info::BLOCKSIZE);
|
||||
CRYPTOPP_CONSTANT(KEYLENGTH = Info::KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(SALTLENGTH = Info::SALTLENGTH);
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE);
|
||||
CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS);
|
||||
|
||||
/// \brief Constructs a DataEncryptorWithMAC
|
||||
/// \param passphrase a C-String password
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
DataEncryptorWithMAC(const char *passphrase, BufferedTransformation *attachment = NULLPTR);
|
||||
|
||||
/// \brief Constructs a DataEncryptorWithMAC
|
||||
/// \param passphrase a byte string password
|
||||
/// \param passphraseLength the length of the byte string password
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
DataEncryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR);
|
||||
|
||||
protected:
|
||||
void FirstPut(const byte *inString) {CRYPTOPP_UNUSED(inString);}
|
||||
void LastPut(const byte *inString, size_t length);
|
||||
|
||||
private:
|
||||
member_ptr<MAC> m_mac;
|
||||
|
||||
};
|
||||
|
||||
/// \brief Password-based decryptor with MAC
|
||||
/// \tparam BC BlockCipher based class used for encryption
|
||||
/// \tparam H HashTransformation based class used for mashing
|
||||
/// \tparam MAC HashTransformation based class used for authentication
|
||||
/// \tparam Info Constants used by the algorithms
|
||||
/// \details DataDecryptorWithMAC uses a non-standard mashup function called Mash() to derive key
|
||||
/// bits from the password.
|
||||
/// \details The purpose of the function Mash() is to take an arbitrary length input string and
|
||||
/// *deterministically* 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 string, whichever is smaller.
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256.
|
||||
/// \sa DefaultEncryptorWithMAC, DefaultDecryptorWithMAC, LegacyDecryptorWithMAC, LegacyEncryptorWithMAC
|
||||
/// \since Crypto++ 2.0
|
||||
template <class BC, class H, class MAC, class Info>
|
||||
class DataDecryptorWithMAC : public ProxyFilter
|
||||
{
|
||||
public:
|
||||
CRYPTOPP_CONSTANT(BLOCKSIZE = Info::BLOCKSIZE);
|
||||
CRYPTOPP_CONSTANT(KEYLENGTH = Info::KEYLENGTH);
|
||||
CRYPTOPP_CONSTANT(SALTLENGTH = Info::SALTLENGTH);
|
||||
CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE);
|
||||
CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS);
|
||||
|
||||
/// \brief Constructs a DataDecryptor
|
||||
/// \param passphrase a C-String password
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
/// \param throwException a flag specifiying whether an Exception should be thrown on error
|
||||
DataDecryptorWithMAC(const char *passphrase, BufferedTransformation *attachment = NULLPTR, bool throwException=true);
|
||||
|
||||
/// \brief Constructs a DataDecryptor
|
||||
/// \param passphrase a byte string password
|
||||
/// \param passphraseLength the length of the byte string password
|
||||
/// \param attachment a BufferedTransformation to attach to this object
|
||||
/// \param throwException a flag specifiying whether an Exception should be thrown on error
|
||||
DataDecryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR, bool throwException=true);
|
||||
|
||||
typename DataDecryptor<BC,H,Info>::State CurrentState() const;
|
||||
bool CheckLastMAC() const;
|
||||
|
||||
protected:
|
||||
void FirstPut(const byte *inString) {CRYPTOPP_UNUSED(inString);}
|
||||
void LastPut(const byte *inString, size_t length);
|
||||
|
||||
private:
|
||||
member_ptr<MAC> m_mac;
|
||||
HashVerificationFilter *m_hashVerifier;
|
||||
bool m_throwException;
|
||||
};
|
||||
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
/// \brief Password-based encryptor (deprecated)
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
|
||||
/// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
|
||||
struct LegacyEncryptor : public DataEncryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo> {};
|
||||
/// \brief Password-based decryptor (deprecated)
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
|
||||
/// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
|
||||
struct LegacyDecryptor : public DataDecryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo> {};
|
||||
/// \brief Password-based encryptor
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
|
||||
/// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
|
||||
struct DefaultEncryptor : public DataEncryptor<DefaultBlockCipher,DefaultHashModule,DefaultParametersInfo> {};
|
||||
/// \brief Password-based decryptor
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
|
||||
/// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
|
||||
struct DefaultDecryptor : public DataDecryptor<DefaultBlockCipher,DefaultHashModule,DefaultParametersInfo> {};
|
||||
/// \brief Password-based encryptor with MAC (deprecated)
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
|
||||
/// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
|
||||
struct LegacyEncryptorWithMAC : public DataEncryptorWithMAC<LegacyBlockCipher,LegacyHashModule,LegacyMAC,LegacyParametersInfo> {};
|
||||
/// \brief Password-based decryptor with MAC (deprecated)
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
|
||||
/// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
|
||||
struct LegacyDecryptorWithMAC : public DataDecryptorWithMAC<LegacyBlockCipher,LegacyHashModule,LegacyMAC,LegacyParametersInfo> {};
|
||||
/// \brief Password-based encryptor with MAC
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
|
||||
/// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
|
||||
struct DefaultEncryptorWithMAC : public DataEncryptorWithMAC<DefaultBlockCipher,DefaultHashModule,DefaultMAC,DefaultParametersInfo> {};
|
||||
/// \brief Password-based decryptor with MAC
|
||||
/// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
|
||||
/// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
|
||||
/// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
|
||||
struct DefaultDecryptorWithMAC : public DataDecryptorWithMAC<DefaultBlockCipher,DefaultHashModule,DefaultMAC,DefaultParametersInfo> {};
|
||||
#else
|
||||
typedef DataEncryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo> LegacyEncryptor;
|
||||
typedef DataDecryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo> LegacyDecryptor;
|
||||
|
||||
typedef DataEncryptor<DefaultBlockCipher,DefaultHashModule,DefaultParametersInfo> DefaultEncryptor;
|
||||
typedef DataDecryptor<DefaultBlockCipher,DefaultHashModule,DefaultParametersInfo> DefaultDecryptor;
|
||||
|
||||
typedef DataEncryptorWithMAC<LegacyBlockCipher,LegacyHashModule,LegacyMAC,LegacyParametersInfo> LegacyEncryptorWithMAC;
|
||||
typedef DataDecryptorWithMAC<LegacyBlockCipher,LegacyHashModule,LegacyMAC,LegacyParametersInfo> LegacyDecryptorWithMAC;
|
||||
|
||||
typedef DataEncryptorWithMAC<DefaultBlockCipher,DefaultHashModule,DefaultMAC,DefaultParametersInfo> DefaultEncryptorWithMAC;
|
||||
typedef DataDecryptorWithMAC<DefaultBlockCipher,DefaultHashModule,DefaultMAC,DefaultParametersInfo> DefaultDecryptorWithMAC;
|
||||
#endif
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+465
@@ -0,0 +1,465 @@
|
||||
// des.cpp - modified by Wei Dai from Phil Karn's des.c
|
||||
// The original code and all modifications are in the public domain.
|
||||
|
||||
/*
|
||||
* This is a major rewrite of my old public domain DES code written
|
||||
* circa 1987, which in turn borrowed heavily from Jim Gillogly's 1977
|
||||
* public domain code. I pretty much kept my key scheduling code, but
|
||||
* the actual encrypt/decrypt routines are taken from from Richard
|
||||
* Outerbridge's DES code as printed in Schneier's "Applied Cryptography."
|
||||
*
|
||||
* This code is in the public domain. I would appreciate bug reports and
|
||||
* enhancements.
|
||||
*
|
||||
* Phil Karn KA9Q, karn@unix.ka9q.ampr.org, August 1994.
|
||||
*/
|
||||
|
||||
#include "pch.h"
|
||||
#include "misc.h"
|
||||
#include "des.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
typedef BlockGetAndPut<word32, BigEndian> Block;
|
||||
|
||||
// Richard Outerbridge's initial permutation algorithm
|
||||
/*
|
||||
inline void IPERM(word32 &left, word32 &right)
|
||||
{
|
||||
word32 work;
|
||||
|
||||
work = ((left >> 4) ^ right) & 0x0f0f0f0f;
|
||||
right ^= work;
|
||||
left ^= work << 4;
|
||||
work = ((left >> 16) ^ right) & 0xffff;
|
||||
right ^= work;
|
||||
left ^= work << 16;
|
||||
work = ((right >> 2) ^ left) & 0x33333333;
|
||||
left ^= work;
|
||||
right ^= (work << 2);
|
||||
work = ((right >> 8) ^ left) & 0xff00ff;
|
||||
left ^= work;
|
||||
right ^= (work << 8);
|
||||
right = rotl(right, 1);
|
||||
work = (left ^ right) & 0xaaaaaaaa;
|
||||
left ^= work;
|
||||
right ^= work;
|
||||
left = rotl(left, 1);
|
||||
}
|
||||
inline void FPERM(word32 &left, word32 &right)
|
||||
{
|
||||
word32 work;
|
||||
|
||||
right = rotr(right, 1);
|
||||
work = (left ^ right) & 0xaaaaaaaa;
|
||||
left ^= work;
|
||||
right ^= work;
|
||||
left = rotr(left, 1);
|
||||
work = ((left >> 8) ^ right) & 0xff00ff;
|
||||
right ^= work;
|
||||
left ^= work << 8;
|
||||
work = ((left >> 2) ^ right) & 0x33333333;
|
||||
right ^= work;
|
||||
left ^= work << 2;
|
||||
work = ((right >> 16) ^ left) & 0xffff;
|
||||
left ^= work;
|
||||
right ^= work << 16;
|
||||
work = ((right >> 4) ^ left) & 0x0f0f0f0f;
|
||||
left ^= work;
|
||||
right ^= work << 4;
|
||||
}
|
||||
*/
|
||||
|
||||
// Wei Dai's modification to Richard Outerbridge's initial permutation
|
||||
// algorithm, this one is faster if you have access to rotate instructions
|
||||
// (like in MSVC)
|
||||
static inline void IPERM(word32 &left, word32 &right)
|
||||
{
|
||||
word32 work;
|
||||
|
||||
right = rotlConstant<4>(right);
|
||||
work = (left ^ right) & 0xf0f0f0f0;
|
||||
left ^= work;
|
||||
right = rotrConstant<20>(right^work);
|
||||
work = (left ^ right) & 0xffff0000;
|
||||
left ^= work;
|
||||
right = rotrConstant<18>(right^work);
|
||||
work = (left ^ right) & 0x33333333;
|
||||
left ^= work;
|
||||
right = rotrConstant<6>(right^work);
|
||||
work = (left ^ right) & 0x00ff00ff;
|
||||
left ^= work;
|
||||
right = rotlConstant<9>(right^work);
|
||||
work = (left ^ right) & 0xaaaaaaaa;
|
||||
left = rotlConstant<1>(left^work);
|
||||
right ^= work;
|
||||
}
|
||||
|
||||
static inline void FPERM(word32 &left, word32 &right)
|
||||
{
|
||||
word32 work;
|
||||
|
||||
right = rotrConstant<1>(right);
|
||||
work = (left ^ right) & 0xaaaaaaaa;
|
||||
right ^= work;
|
||||
left = rotrConstant<9>(left^work);
|
||||
work = (left ^ right) & 0x00ff00ff;
|
||||
right ^= work;
|
||||
left = rotlConstant<6>(left^work);
|
||||
work = (left ^ right) & 0x33333333;
|
||||
right ^= work;
|
||||
left = rotlConstant<18>(left^work);
|
||||
work = (left ^ right) & 0xffff0000;
|
||||
right ^= work;
|
||||
left = rotlConstant<20>(left^work);
|
||||
work = (left ^ right) & 0xf0f0f0f0;
|
||||
right ^= work;
|
||||
left = rotrConstant<4>(left^work);
|
||||
}
|
||||
|
||||
void DES::Base::UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs &)
|
||||
{
|
||||
AssertValidKeyLength(length);
|
||||
|
||||
RawSetKey(GetCipherDirection(), userKey);
|
||||
}
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
/* Tables defined in the Data Encryption Standard documents
|
||||
* Three of these tables, the initial permutation, the final
|
||||
* permutation and the expansion operator, are regular enough that
|
||||
* for speed, we hard-code them. They're here for reference only.
|
||||
* Also, the S and P boxes are used by a separate program, gensp.c,
|
||||
* to build the combined SP box, Spbox[]. They're also here just
|
||||
* for reference.
|
||||
*/
|
||||
#ifdef notdef
|
||||
/* initial permutation IP */
|
||||
static byte ip[] = {
|
||||
58, 50, 42, 34, 26, 18, 10, 2,
|
||||
60, 52, 44, 36, 28, 20, 12, 4,
|
||||
62, 54, 46, 38, 30, 22, 14, 6,
|
||||
64, 56, 48, 40, 32, 24, 16, 8,
|
||||
57, 49, 41, 33, 25, 17, 9, 1,
|
||||
59, 51, 43, 35, 27, 19, 11, 3,
|
||||
61, 53, 45, 37, 29, 21, 13, 5,
|
||||
63, 55, 47, 39, 31, 23, 15, 7
|
||||
};
|
||||
|
||||
/* final permutation IP^-1 */
|
||||
static byte fp[] = {
|
||||
40, 8, 48, 16, 56, 24, 64, 32,
|
||||
39, 7, 47, 15, 55, 23, 63, 31,
|
||||
38, 6, 46, 14, 54, 22, 62, 30,
|
||||
37, 5, 45, 13, 53, 21, 61, 29,
|
||||
36, 4, 44, 12, 52, 20, 60, 28,
|
||||
35, 3, 43, 11, 51, 19, 59, 27,
|
||||
34, 2, 42, 10, 50, 18, 58, 26,
|
||||
33, 1, 41, 9, 49, 17, 57, 25
|
||||
};
|
||||
/* expansion operation matrix */
|
||||
static byte ei[] = {
|
||||
32, 1, 2, 3, 4, 5,
|
||||
4, 5, 6, 7, 8, 9,
|
||||
8, 9, 10, 11, 12, 13,
|
||||
12, 13, 14, 15, 16, 17,
|
||||
16, 17, 18, 19, 20, 21,
|
||||
20, 21, 22, 23, 24, 25,
|
||||
24, 25, 26, 27, 28, 29,
|
||||
28, 29, 30, 31, 32, 1
|
||||
};
|
||||
/* The (in)famous S-boxes */
|
||||
static byte sbox[8][64] = {
|
||||
/* S1 */
|
||||
14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
|
||||
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
|
||||
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
|
||||
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13,
|
||||
|
||||
/* S2 */
|
||||
15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
|
||||
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
|
||||
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
|
||||
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9,
|
||||
|
||||
/* S3 */
|
||||
10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
|
||||
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
|
||||
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
|
||||
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12,
|
||||
|
||||
/* S4 */
|
||||
7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
|
||||
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
|
||||
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
|
||||
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14,
|
||||
|
||||
/* S5 */
|
||||
2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
|
||||
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
|
||||
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
|
||||
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3,
|
||||
|
||||
/* S6 */
|
||||
12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
|
||||
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
|
||||
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
|
||||
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13,
|
||||
|
||||
/* S7 */
|
||||
4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
|
||||
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
|
||||
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
|
||||
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12,
|
||||
|
||||
/* S8 */
|
||||
13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
|
||||
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
|
||||
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
|
||||
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11
|
||||
};
|
||||
|
||||
/* 32-bit permutation function P used on the output of the S-boxes */
|
||||
namespace {
|
||||
const byte p32i[] = {
|
||||
16, 7, 20, 21,
|
||||
29, 12, 28, 17,
|
||||
1, 15, 23, 26,
|
||||
5, 18, 31, 10,
|
||||
2, 8, 24, 14,
|
||||
32, 27, 3, 9,
|
||||
19, 13, 30, 6,
|
||||
22, 11, 4, 25
|
||||
};
|
||||
}
|
||||
#endif
|
||||
|
||||
/* permuted choice table (key) */
|
||||
namespace {
|
||||
const byte pc1[] = {
|
||||
57, 49, 41, 33, 25, 17, 9,
|
||||
1, 58, 50, 42, 34, 26, 18,
|
||||
10, 2, 59, 51, 43, 35, 27,
|
||||
19, 11, 3, 60, 52, 44, 36,
|
||||
|
||||
63, 55, 47, 39, 31, 23, 15,
|
||||
7, 62, 54, 46, 38, 30, 22,
|
||||
14, 6, 61, 53, 45, 37, 29,
|
||||
21, 13, 5, 28, 20, 12, 4
|
||||
};
|
||||
}
|
||||
|
||||
/* number left rotations of pc1 */
|
||||
namespace {
|
||||
const byte totrot[] = {
|
||||
1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28
|
||||
};
|
||||
}
|
||||
|
||||
/* permuted choice key (table) */
|
||||
namespace {
|
||||
const byte pc2[] = {
|
||||
14, 17, 11, 24, 1, 5,
|
||||
3, 28, 15, 6, 21, 10,
|
||||
23, 19, 12, 4, 26, 8,
|
||||
16, 7, 27, 20, 13, 2,
|
||||
41, 52, 31, 37, 47, 55,
|
||||
30, 40, 51, 45, 33, 48,
|
||||
44, 49, 39, 56, 34, 53,
|
||||
46, 42, 50, 36, 29, 32
|
||||
};
|
||||
}
|
||||
|
||||
/* End of DES-defined tables */
|
||||
|
||||
/* bit 0 is left-most in byte */
|
||||
namespace {
|
||||
const int bytebit[] = {
|
||||
0200,0100,040,020,010,04,02,01
|
||||
};
|
||||
}
|
||||
|
||||
/* 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 */
|
||||
#else
|
||||
# define REGISTER register
|
||||
#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;
|
||||
REGISTER int i,j,l;
|
||||
int m;
|
||||
|
||||
for (j=0; j<56; j++) { /* convert pc1 to bits of key */
|
||||
l=pc1[j]-1; /* integer bit location */
|
||||
m = l & 07; /* find bit */
|
||||
pc1m[j]=(key[l>>3] & /* find which key byte l is in */
|
||||
bytebit[m]) /* and which bit of that byte */
|
||||
? 1 : 0; /* and store 1-bit result */
|
||||
}
|
||||
for (i=0; i<16; i++) { /* key chunk for each iteration */
|
||||
memset(ks,0,8); /* Clear key schedule */
|
||||
for (j=0; j<56; j++) /* rotate pc1 the right amount */
|
||||
pcr[j] = pc1m[(l=j+totrot[i])<(j<28? 28 : 56) ? l: l-28];
|
||||
/* rotate left and right halves independently */
|
||||
for (j=0; j<48; j++){ /* select bits individually */
|
||||
/* check bit that goes to ks[j] */
|
||||
if (pcr[pc2[j]-1]){
|
||||
/* mask it in if it's there */
|
||||
l= j % 6;
|
||||
ks[j/6] |= bytebit[l] >> 2;
|
||||
}
|
||||
}
|
||||
/* Now convert to odd/even interleaved form for use in F */
|
||||
k[2*i] = ((word32)ks[0] << 24)
|
||||
| ((word32)ks[2] << 16)
|
||||
| ((word32)ks[4] << 8)
|
||||
| ((word32)ks[6]);
|
||||
k[2*i+1] = ((word32)ks[1] << 24)
|
||||
| ((word32)ks[3] << 16)
|
||||
| ((word32)ks[5] << 8)
|
||||
| ((word32)ks[7]);
|
||||
}
|
||||
|
||||
if (dir==DECRYPTION) // reverse key schedule order
|
||||
for (i=0; i<16; i+=2)
|
||||
{
|
||||
std::swap(k[i], k[32-2-i]);
|
||||
std::swap(k[i+1], k[32-1-i]);
|
||||
}
|
||||
}
|
||||
|
||||
void RawDES::RawProcessBlock(word32 &l_, word32 &r_) const
|
||||
{
|
||||
word32 l = l_, r = r_;
|
||||
const word32 *kptr=k;
|
||||
|
||||
for (unsigned i=0; i<8; i++)
|
||||
{
|
||||
word32 work = rotrConstant<4>(r) ^ kptr[4 * i + 0];
|
||||
l ^= Spbox[6][(work) & 0x3f]
|
||||
^ Spbox[4][(work >> 8) & 0x3f]
|
||||
^ Spbox[2][(work >> 16) & 0x3f]
|
||||
^ Spbox[0][(work >> 24) & 0x3f];
|
||||
work = r ^ kptr[4*i+1];
|
||||
l ^= Spbox[7][(work) & 0x3f]
|
||||
^ Spbox[5][(work >> 8) & 0x3f]
|
||||
^ Spbox[3][(work >> 16) & 0x3f]
|
||||
^ Spbox[1][(work >> 24) & 0x3f];
|
||||
|
||||
work = rotrConstant<4>(l) ^ kptr[4 * i + 2];
|
||||
r ^= Spbox[6][(work) & 0x3f]
|
||||
^ Spbox[4][(work >> 8) & 0x3f]
|
||||
^ Spbox[2][(work >> 16) & 0x3f]
|
||||
^ Spbox[0][(work >> 24) & 0x3f];
|
||||
work = l ^ kptr[4*i+3];
|
||||
r ^= Spbox[7][(work) & 0x3f]
|
||||
^ Spbox[5][(work >> 8) & 0x3f]
|
||||
^ Spbox[3][(work >> 16) & 0x3f]
|
||||
^ Spbox[1][(work >> 24) & 0x3f];
|
||||
}
|
||||
|
||||
l_ = l; r_ = r;
|
||||
}
|
||||
|
||||
void DES_EDE2::Base::UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs &)
|
||||
{
|
||||
AssertValidKeyLength(length);
|
||||
|
||||
m_des1.RawSetKey(GetCipherDirection(), userKey);
|
||||
m_des2.RawSetKey(ReverseCipherDir(GetCipherDirection()), userKey+8);
|
||||
}
|
||||
|
||||
void DES_EDE2::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
word32 l,r;
|
||||
Block::Get(inBlock)(l)(r);
|
||||
IPERM(l,r);
|
||||
m_des1.RawProcessBlock(l, r);
|
||||
m_des2.RawProcessBlock(r, l);
|
||||
m_des1.RawProcessBlock(l, r);
|
||||
FPERM(l,r);
|
||||
Block::Put(xorBlock, outBlock)(r)(l);
|
||||
}
|
||||
|
||||
void DES_EDE3::Base::UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs &)
|
||||
{
|
||||
AssertValidKeyLength(length);
|
||||
|
||||
m_des1.RawSetKey(GetCipherDirection(), userKey + (IsForwardTransformation() ? 0 : 16));
|
||||
m_des2.RawSetKey(ReverseCipherDir(GetCipherDirection()), userKey + 8);
|
||||
m_des3.RawSetKey(GetCipherDirection(), userKey + (IsForwardTransformation() ? 16 : 0));
|
||||
}
|
||||
|
||||
void DES_EDE3::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
word32 l,r;
|
||||
Block::Get(inBlock)(l)(r);
|
||||
IPERM(l,r);
|
||||
m_des1.RawProcessBlock(l, r);
|
||||
m_des2.RawProcessBlock(r, l);
|
||||
m_des3.RawProcessBlock(l, r);
|
||||
FPERM(l,r);
|
||||
Block::Put(xorBlock, outBlock)(r)(l);
|
||||
}
|
||||
|
||||
#endif // #ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
static inline bool CheckParity(byte b)
|
||||
{
|
||||
unsigned int a = b ^ (b >> 4);
|
||||
return ((a ^ (a>>1) ^ (a>>2) ^ (a>>3)) & 1) == 1;
|
||||
}
|
||||
|
||||
bool DES::CheckKeyParityBits(const byte *key)
|
||||
{
|
||||
for (unsigned int i=0; i<8; i++)
|
||||
if (!CheckParity(key[i]))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
void DES::CorrectKeyParityBits(byte *key)
|
||||
{
|
||||
for (unsigned int i=0; i<8; i++)
|
||||
if (!CheckParity(key[i]))
|
||||
key[i] ^= 1;
|
||||
}
|
||||
|
||||
// Encrypt or decrypt a block of data in ECB mode
|
||||
void DES::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
word32 l,r;
|
||||
Block::Get(inBlock)(l)(r);
|
||||
IPERM(l,r);
|
||||
RawProcessBlock(l, r);
|
||||
FPERM(l,r);
|
||||
Block::Put(xorBlock, outBlock)(r)(l);
|
||||
}
|
||||
|
||||
void DES_XEX3::Base::UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &)
|
||||
{
|
||||
AssertValidKeyLength(length);
|
||||
|
||||
if (!m_des.get())
|
||||
m_des.reset(new DES::Encryption);
|
||||
|
||||
memcpy(m_x1, key + (IsForwardTransformation() ? 0 : 16), BLOCKSIZE);
|
||||
m_des->RawSetKey(GetCipherDirection(), key + 8);
|
||||
memcpy(m_x3, key + (IsForwardTransformation() ? 16 : 0), BLOCKSIZE);
|
||||
}
|
||||
|
||||
void DES_XEX3::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
|
||||
{
|
||||
xorbuf(outBlock, inBlock, m_x1, BLOCKSIZE);
|
||||
m_des->ProcessAndXorBlock(outBlock, xorBlock, outBlock);
|
||||
xorbuf(outBlock, m_x3, BLOCKSIZE);
|
||||
}
|
||||
|
||||
NAMESPACE_END
|
||||
Vendored
+163
@@ -0,0 +1,163 @@
|
||||
// des.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file des.h
|
||||
/// \brief Classes for DES, 2-key Triple-DES, 3-key Triple-DES and DESX
|
||||
|
||||
#ifndef CRYPTOPP_DES_H
|
||||
#define CRYPTOPP_DES_H
|
||||
|
||||
#include "seckey.h"
|
||||
#include "secblock.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief DES block cipher base class
|
||||
/// \since Crypto++ 1.0
|
||||
class CRYPTOPP_DLL RawDES
|
||||
{
|
||||
public:
|
||||
void RawSetKey(CipherDir direction, const byte *userKey);
|
||||
void RawProcessBlock(word32 &l, word32 &r) const;
|
||||
|
||||
protected:
|
||||
static const word32 Spbox[8][64];
|
||||
|
||||
FixedSizeSecBlock<word32, 32> k;
|
||||
};
|
||||
|
||||
/// \brief DES block cipher information
|
||||
/// \since Crypto++ 1.0
|
||||
struct DES_Info : public FixedBlockSize<8>, public FixedKeyLength<8>
|
||||
{
|
||||
// disable DES in DLL version by not exporting this function
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "DES";}
|
||||
};
|
||||
|
||||
/// \brief DES block cipher
|
||||
/// \details The DES implementation in Crypto++ ignores the parity bits
|
||||
/// (the least significant bits of each byte) in the key. However you can use CheckKeyParityBits()
|
||||
/// and CorrectKeyParityBits() to check or correct the parity bits if you wish.
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES</a>
|
||||
/// \since Crypto++ 1.0
|
||||
class DES : public DES_Info, public BlockCipherDocumentation
|
||||
{
|
||||
/// \brief DES block cipher default operation
|
||||
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_Info>, public RawDES
|
||||
{
|
||||
public:
|
||||
void UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs ¶ms);
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
};
|
||||
|
||||
public:
|
||||
/// check DES key parity bits
|
||||
static bool CheckKeyParityBits(const byte *key);
|
||||
/// correct DES key parity bits
|
||||
static void CorrectKeyParityBits(byte *key);
|
||||
|
||||
typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
|
||||
typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
|
||||
};
|
||||
|
||||
/// \brief 2-key TripleDES block cipher information
|
||||
/// \since Crypto++ 1.0
|
||||
struct DES_EDE2_Info : public FixedBlockSize<8>, public FixedKeyLength<16>
|
||||
{
|
||||
CRYPTOPP_DLL static const char * CRYPTOPP_API StaticAlgorithmName() {return "DES-EDE2";}
|
||||
};
|
||||
|
||||
/// \brief 2-key TripleDES block cipher
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES-EDE2</a>
|
||||
/// \since Crypto++ 1.0
|
||||
class DES_EDE2 : public DES_EDE2_Info, public BlockCipherDocumentation
|
||||
{
|
||||
/// \brief DES_EDE2 block cipher default operation
|
||||
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_EDE2_Info>
|
||||
{
|
||||
public:
|
||||
void UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs ¶ms);
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
|
||||
protected:
|
||||
RawDES m_des1, m_des2;
|
||||
};
|
||||
|
||||
public:
|
||||
typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
|
||||
typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
|
||||
};
|
||||
|
||||
/// \brief 3-key TripleDES block cipher information
|
||||
/// \since Crypto++ 1.0
|
||||
struct DES_EDE3_Info : public FixedBlockSize<8>, public FixedKeyLength<24>
|
||||
{
|
||||
CRYPTOPP_DLL static const char * CRYPTOPP_API StaticAlgorithmName() {return "DES-EDE3";}
|
||||
};
|
||||
|
||||
/// \brief 3-key TripleDES block cipher
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES-EDE3</a>
|
||||
/// \since Crypto++ 1.0
|
||||
class DES_EDE3 : public DES_EDE3_Info, public BlockCipherDocumentation
|
||||
{
|
||||
/// \brief DES_EDE3 block cipher default operation
|
||||
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_EDE3_Info>
|
||||
{
|
||||
public:
|
||||
void UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs ¶ms);
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
|
||||
protected:
|
||||
RawDES m_des1, m_des2, m_des3;
|
||||
};
|
||||
|
||||
public:
|
||||
typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
|
||||
typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
|
||||
};
|
||||
|
||||
/// \brief DESX block cipher information
|
||||
/// \since Crypto++ 3.2
|
||||
struct DES_XEX3_Info : public FixedBlockSize<8>, public FixedKeyLength<24>
|
||||
{
|
||||
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "DES-XEX3";}
|
||||
};
|
||||
|
||||
/// \brief DESX block cipher
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES-XEX3</a>, AKA DESX
|
||||
/// \since Crypto++ 3.2
|
||||
class DES_XEX3 : public DES_XEX3_Info, public BlockCipherDocumentation
|
||||
{
|
||||
/// \brief DES_XEX3 block cipher default operation
|
||||
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_XEX3_Info>
|
||||
{
|
||||
public:
|
||||
void UncheckedSetKey(const byte *userKey, unsigned int length, const NameValuePairs ¶ms);
|
||||
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
|
||||
|
||||
protected:
|
||||
FixedSizeSecBlock<byte, BLOCKSIZE> m_x1, m_x3;
|
||||
// VS2005 workaround: calling modules compiled with /clr gets unresolved external symbol DES::Base::ProcessAndXorBlock
|
||||
// if we use DES::Encryption here directly without value_ptr.
|
||||
value_ptr<DES::Encryption> m_des;
|
||||
};
|
||||
|
||||
public:
|
||||
typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
|
||||
typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
|
||||
};
|
||||
|
||||
typedef DES::Encryption DESEncryption;
|
||||
typedef DES::Decryption DESDecryption;
|
||||
|
||||
typedef DES_EDE2::Encryption DES_EDE2_Encryption;
|
||||
typedef DES_EDE2::Decryption DES_EDE2_Decryption;
|
||||
|
||||
typedef DES_EDE3::Encryption DES_EDE3_Encryption;
|
||||
typedef DES_EDE3::Decryption DES_EDE3_Decryption;
|
||||
|
||||
typedef DES_XEX3::Encryption DES_XEX3_Encryption;
|
||||
typedef DES_XEX3::Decryption DES_XEX3_Decryption;
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
// This file is mostly generated by Phil Karn's gensp.c
|
||||
|
||||
#include "pch.h"
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
#include "des.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
const word32 RawDES::Spbox[8][64] = {
|
||||
{
|
||||
0x01010400,0x00000000,0x00010000,0x01010404, 0x01010004,0x00010404,0x00000004,0x00010000,
|
||||
0x00000400,0x01010400,0x01010404,0x00000400, 0x01000404,0x01010004,0x01000000,0x00000004,
|
||||
0x00000404,0x01000400,0x01000400,0x00010400, 0x00010400,0x01010000,0x01010000,0x01000404,
|
||||
0x00010004,0x01000004,0x01000004,0x00010004, 0x00000000,0x00000404,0x00010404,0x01000000,
|
||||
0x00010000,0x01010404,0x00000004,0x01010000, 0x01010400,0x01000000,0x01000000,0x00000400,
|
||||
0x01010004,0x00010000,0x00010400,0x01000004, 0x00000400,0x00000004,0x01000404,0x00010404,
|
||||
0x01010404,0x00010004,0x01010000,0x01000404, 0x01000004,0x00000404,0x00010404,0x01010400,
|
||||
0x00000404,0x01000400,0x01000400,0x00000000, 0x00010004,0x00010400,0x00000000,0x01010004},
|
||||
{
|
||||
0x80108020,0x80008000,0x00008000,0x00108020, 0x00100000,0x00000020,0x80100020,0x80008020,
|
||||
0x80000020,0x80108020,0x80108000,0x80000000, 0x80008000,0x00100000,0x00000020,0x80100020,
|
||||
0x00108000,0x00100020,0x80008020,0x00000000, 0x80000000,0x00008000,0x00108020,0x80100000,
|
||||
0x00100020,0x80000020,0x00000000,0x00108000, 0x00008020,0x80108000,0x80100000,0x00008020,
|
||||
0x00000000,0x00108020,0x80100020,0x00100000, 0x80008020,0x80100000,0x80108000,0x00008000,
|
||||
0x80100000,0x80008000,0x00000020,0x80108020, 0x00108020,0x00000020,0x00008000,0x80000000,
|
||||
0x00008020,0x80108000,0x00100000,0x80000020, 0x00100020,0x80008020,0x80000020,0x00100020,
|
||||
0x00108000,0x00000000,0x80008000,0x00008020, 0x80000000,0x80100020,0x80108020,0x00108000},
|
||||
{
|
||||
0x00000208,0x08020200,0x00000000,0x08020008, 0x08000200,0x00000000,0x00020208,0x08000200,
|
||||
0x00020008,0x08000008,0x08000008,0x00020000, 0x08020208,0x00020008,0x08020000,0x00000208,
|
||||
0x08000000,0x00000008,0x08020200,0x00000200, 0x00020200,0x08020000,0x08020008,0x00020208,
|
||||
0x08000208,0x00020200,0x00020000,0x08000208, 0x00000008,0x08020208,0x00000200,0x08000000,
|
||||
0x08020200,0x08000000,0x00020008,0x00000208, 0x00020000,0x08020200,0x08000200,0x00000000,
|
||||
0x00000200,0x00020008,0x08020208,0x08000200, 0x08000008,0x00000200,0x00000000,0x08020008,
|
||||
0x08000208,0x00020000,0x08000000,0x08020208, 0x00000008,0x00020208,0x00020200,0x08000008,
|
||||
0x08020000,0x08000208,0x00000208,0x08020000, 0x00020208,0x00000008,0x08020008,0x00020200},
|
||||
{
|
||||
0x00802001,0x00002081,0x00002081,0x00000080, 0x00802080,0x00800081,0x00800001,0x00002001,
|
||||
0x00000000,0x00802000,0x00802000,0x00802081, 0x00000081,0x00000000,0x00800080,0x00800001,
|
||||
0x00000001,0x00002000,0x00800000,0x00802001, 0x00000080,0x00800000,0x00002001,0x00002080,
|
||||
0x00800081,0x00000001,0x00002080,0x00800080, 0x00002000,0x00802080,0x00802081,0x00000081,
|
||||
0x00800080,0x00800001,0x00802000,0x00802081, 0x00000081,0x00000000,0x00000000,0x00802000,
|
||||
0x00002080,0x00800080,0x00800081,0x00000001, 0x00802001,0x00002081,0x00002081,0x00000080,
|
||||
0x00802081,0x00000081,0x00000001,0x00002000, 0x00800001,0x00002001,0x00802080,0x00800081,
|
||||
0x00002001,0x00002080,0x00800000,0x00802001, 0x00000080,0x00800000,0x00002000,0x00802080},
|
||||
{
|
||||
0x00000100,0x02080100,0x02080000,0x42000100, 0x00080000,0x00000100,0x40000000,0x02080000,
|
||||
0x40080100,0x00080000,0x02000100,0x40080100, 0x42000100,0x42080000,0x00080100,0x40000000,
|
||||
0x02000000,0x40080000,0x40080000,0x00000000, 0x40000100,0x42080100,0x42080100,0x02000100,
|
||||
0x42080000,0x40000100,0x00000000,0x42000000, 0x02080100,0x02000000,0x42000000,0x00080100,
|
||||
0x00080000,0x42000100,0x00000100,0x02000000, 0x40000000,0x02080000,0x42000100,0x40080100,
|
||||
0x02000100,0x40000000,0x42080000,0x02080100, 0x40080100,0x00000100,0x02000000,0x42080000,
|
||||
0x42080100,0x00080100,0x42000000,0x42080100, 0x02080000,0x00000000,0x40080000,0x42000000,
|
||||
0x00080100,0x02000100,0x40000100,0x00080000, 0x00000000,0x40080000,0x02080100,0x40000100},
|
||||
{
|
||||
0x20000010,0x20400000,0x00004000,0x20404010, 0x20400000,0x00000010,0x20404010,0x00400000,
|
||||
0x20004000,0x00404010,0x00400000,0x20000010, 0x00400010,0x20004000,0x20000000,0x00004010,
|
||||
0x00000000,0x00400010,0x20004010,0x00004000, 0x00404000,0x20004010,0x00000010,0x20400010,
|
||||
0x20400010,0x00000000,0x00404010,0x20404000, 0x00004010,0x00404000,0x20404000,0x20000000,
|
||||
0x20004000,0x00000010,0x20400010,0x00404000, 0x20404010,0x00400000,0x00004010,0x20000010,
|
||||
0x00400000,0x20004000,0x20000000,0x00004010, 0x20000010,0x20404010,0x00404000,0x20400000,
|
||||
0x00404010,0x20404000,0x00000000,0x20400010, 0x00000010,0x00004000,0x20400000,0x00404010,
|
||||
0x00004000,0x00400010,0x20004010,0x00000000, 0x20404000,0x20000000,0x00400010,0x20004010},
|
||||
{
|
||||
0x00200000,0x04200002,0x04000802,0x00000000, 0x00000800,0x04000802,0x00200802,0x04200800,
|
||||
0x04200802,0x00200000,0x00000000,0x04000002, 0x00000002,0x04000000,0x04200002,0x00000802,
|
||||
0x04000800,0x00200802,0x00200002,0x04000800, 0x04000002,0x04200000,0x04200800,0x00200002,
|
||||
0x04200000,0x00000800,0x00000802,0x04200802, 0x00200800,0x00000002,0x04000000,0x00200800,
|
||||
0x04000000,0x00200800,0x00200000,0x04000802, 0x04000802,0x04200002,0x04200002,0x00000002,
|
||||
0x00200002,0x04000000,0x04000800,0x00200000, 0x04200800,0x00000802,0x00200802,0x04200800,
|
||||
0x00000802,0x04000002,0x04200802,0x04200000, 0x00200800,0x00000000,0x00000002,0x04200802,
|
||||
0x00000000,0x00200802,0x04200000,0x00000800, 0x04000002,0x04000800,0x00000800,0x00200002},
|
||||
{
|
||||
0x10001040,0x00001000,0x00040000,0x10041040, 0x10000000,0x10001040,0x00000040,0x10000000,
|
||||
0x00040040,0x10040000,0x10041040,0x00041000, 0x10041000,0x00041040,0x00001000,0x00000040,
|
||||
0x10040000,0x10000040,0x10001000,0x00001040, 0x00041000,0x00040040,0x10040040,0x10041000,
|
||||
0x00001040,0x00000000,0x00000000,0x10040040, 0x10000040,0x10001000,0x00041040,0x00040000,
|
||||
0x00041040,0x00040000,0x10041000,0x00001000, 0x00000040,0x10040040,0x00001000,0x00041040,
|
||||
0x10001000,0x00000040,0x10000040,0x10040000, 0x10040040,0x10000000,0x00040000,0x10001040,
|
||||
0x00000000,0x10041040,0x00040040,0x10000040, 0x10040000,0x10001000,0x10001040,0x00000000,
|
||||
0x10041040,0x00041000,0x00041000,0x00001040, 0x00001040,0x00040040,0x10000000,0x10041000}
|
||||
};
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
// dh.cpp - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
#include "pch.h"
|
||||
|
||||
#ifndef CRYPTOPP_IMPORTS
|
||||
|
||||
#include "dh.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
#if defined(CRYPTOPP_DEBUG) && !defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
void DH_TestInstantiations()
|
||||
{
|
||||
DH dh1;
|
||||
DH dh2(NullRNG(), 10);
|
||||
}
|
||||
#endif
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
Vendored
+275
@@ -0,0 +1,275 @@
|
||||
// dh.h - originally written and placed in the public domain by Wei Dai
|
||||
|
||||
/// \file dh.h
|
||||
/// \brief Classes for Diffie-Hellman key exchange
|
||||
|
||||
#ifndef CRYPTOPP_DH_H
|
||||
#define CRYPTOPP_DH_H
|
||||
|
||||
#include "cryptlib.h"
|
||||
#include "gfpcrypt.h"
|
||||
#include "algebra.h"
|
||||
|
||||
NAMESPACE_BEGIN(CryptoPP)
|
||||
|
||||
/// \brief Diffie-Hellman domain
|
||||
/// \tparam GROUP_PARAMETERS group parameters
|
||||
/// \tparam COFACTOR_OPTION cofactor multiplication option
|
||||
/// \details A Diffie-Hellman domain is a set of parameters that must be shared
|
||||
/// by two parties in a key agreement protocol, along with the algorithms
|
||||
/// for generating key pairs and deriving agreed values.
|
||||
/// \details For COFACTOR_OPTION, see CofactorMultiplicationOption.
|
||||
/// \sa DL_SimpleKeyAgreementDomainBase
|
||||
/// \since Crypto++ 1.0
|
||||
template <class GROUP_PARAMETERS, class COFACTOR_OPTION = typename GROUP_PARAMETERS::DefaultCofactorOption>
|
||||
class DH_Domain : public DL_SimpleKeyAgreementDomainBase<typename GROUP_PARAMETERS::Element>
|
||||
{
|
||||
typedef DL_SimpleKeyAgreementDomainBase<typename GROUP_PARAMETERS::Element> Base;
|
||||
|
||||
public:
|
||||
typedef GROUP_PARAMETERS GroupParameters;
|
||||
typedef typename GroupParameters::Element Element;
|
||||
typedef DL_KeyAgreementAlgorithm_DH<Element, COFACTOR_OPTION> DH_Algorithm;
|
||||
typedef DH_Domain<GROUP_PARAMETERS, COFACTOR_OPTION> Domain;
|
||||
|
||||
virtual ~DH_Domain() {}
|
||||
|
||||
/// \brief Construct a Diffie-Hellman domain
|
||||
DH_Domain() {}
|
||||
|
||||
/// \brief Construct a Diffie-Hellman domain
|
||||
/// \param params group parameters and options
|
||||
DH_Domain(const GroupParameters ¶ms)
|
||||
: m_groupParameters(params) {}
|
||||
|
||||
/// \brief Construct a Diffie-Hellman domain
|
||||
/// \param bt BufferedTransformation with group parameters and options
|
||||
DH_Domain(BufferedTransformation &bt)
|
||||
{m_groupParameters.BERDecode(bt);}
|
||||
|
||||
/// \brief Create a Diffie-Hellman domain
|
||||
/// \tparam T2 template parameter used as a constructor parameter
|
||||
/// \param v1 RandomNumberGenerator derived class
|
||||
/// \param v2 second parameter
|
||||
/// \details v1 and v2 are passed directly to the GROUP_PARAMETERS object.
|
||||
template <class T2>
|
||||
DH_Domain(RandomNumberGenerator &v1, const T2 &v2)
|
||||
{m_groupParameters.Initialize(v1, v2);}
|
||||
|
||||
/// \brief Create a Diffie-Hellman domain
|
||||
/// \tparam T2 template parameter used as a constructor parameter
|
||||
/// \tparam T3 template parameter used as a constructor parameter
|
||||
/// \param v1 RandomNumberGenerator derived class
|
||||
/// \param v2 second parameter
|
||||
/// \param v3 third parameter
|
||||
/// \details v1, v2 and v3 are passed directly to the GROUP_PARAMETERS object.
|
||||
template <class T2, class T3>
|
||||
DH_Domain(RandomNumberGenerator &v1, const T2 &v2, const T3 &v3)
|
||||
{m_groupParameters.Initialize(v1, v2, v3);}
|
||||
|
||||
/// \brief Create a Diffie-Hellman domain
|
||||
/// \tparam T2 template parameter used as a constructor parameter
|
||||
/// \tparam T3 template parameter used as a constructor parameter
|
||||
/// \tparam T4 template parameter used as a constructor parameter
|
||||
/// \param v1 RandomNumberGenerator derived class
|
||||
/// \param v2 second parameter
|
||||
/// \param v3 third parameter
|
||||
/// \param v4 fourth parameter
|
||||
/// \details v1, v2, v3 and v4 are passed directly to the GROUP_PARAMETERS object.
|
||||
template <class T2, class T3, class T4>
|
||||
DH_Domain(RandomNumberGenerator &v1, const T2 &v2, const T3 &v3, const T4 &v4)
|
||||
{m_groupParameters.Initialize(v1, v2, v3, v4);}
|
||||
|
||||
/// \brief Construct a Diffie-Hellman domain
|
||||
/// \tparam T1 template parameter used as a constructor parameter
|
||||
/// \tparam T2 template parameter used as a constructor parameter
|
||||
/// \param v1 first parameter
|
||||
/// \param v2 second parameter
|
||||
/// \details v1 and v2 are passed directly to the GROUP_PARAMETERS object.
|
||||
template <class T1, class T2>
|
||||
DH_Domain(const T1 &v1, const T2 &v2)
|
||||
{m_groupParameters.Initialize(v1, v2);}
|
||||
|
||||
/// \brief Construct a Diffie-Hellman domain
|
||||
/// \tparam T1 template parameter used as a constructor parameter
|
||||
/// \tparam T2 template parameter used as a constructor parameter
|
||||
/// \tparam T3 template parameter used as a constructor parameter
|
||||
/// \param v1 first parameter
|
||||
/// \param v2 second parameter
|
||||
/// \param v3 third parameter
|
||||
/// \details v1, v2 and v3 are passed directly to the GROUP_PARAMETERS object.
|
||||
template <class T1, class T2, class T3>
|
||||
DH_Domain(const T1 &v1, const T2 &v2, const T3 &v3)
|
||||
{m_groupParameters.Initialize(v1, v2, v3);}
|
||||
|
||||
/// \brief Construct a Diffie-Hellman domain
|
||||
/// \tparam T1 template parameter used as a constructor parameter
|
||||
/// \tparam T2 template parameter used as a constructor parameter
|
||||
/// \tparam T3 template parameter used as a constructor parameter
|
||||
/// \tparam T4 template parameter used as a constructor parameter
|
||||
/// \param v1 first parameter
|
||||
/// \param v2 second parameter
|
||||
/// \param v3 third parameter
|
||||
/// \param v4 fourth parameter
|
||||
/// \details v1, v2, v3 and v4 are passed directly to the GROUP_PARAMETERS object.
|
||||
template <class T1, class T2, class T3, class T4>
|
||||
DH_Domain(const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4)
|
||||
{m_groupParameters.Initialize(v1, v2, v3, v4);}
|
||||
|
||||
/// \brief Retrieves the group parameters for this domain
|
||||
/// \return the group parameters for this domain as a const reference
|
||||
const GroupParameters & GetGroupParameters() const {return m_groupParameters;}
|
||||
/// \brief Retrieves the group parameters for this domain
|
||||
/// \return the group parameters for this domain as a non-const reference
|
||||
GroupParameters & AccessGroupParameters() {return m_groupParameters;}
|
||||
|
||||
/// \brief Generate a public key from a private key in this domain
|
||||
/// \param rng RandomNumberGenerator derived class
|
||||
/// \param privateKey byte buffer with the previously generated private key
|
||||
/// \param publicKey byte buffer for the generated public key in this domain
|
||||
/// \details If using a FIPS 140-2 validated library on Windows, then this class will perform
|
||||
/// a self test to ensure the key pair is pairwise consistent. Non-FIPS and non-Windows
|
||||
/// builds of the library do not provide FIPS validated cryptography, so the code should be
|
||||
/// removed by the optimizer.
|
||||
/// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
|
||||
void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const
|
||||
{
|
||||
Base::GeneratePublicKey(rng, privateKey, publicKey);
|
||||
|
||||
if (FIPS_140_2_ComplianceEnabled())
|
||||
{
|
||||
SecByteBlock privateKey2(this->PrivateKeyLength());
|
||||
this->GeneratePrivateKey(rng, privateKey2);
|
||||
|
||||
SecByteBlock publicKey2(this->PublicKeyLength());
|
||||
Base::GeneratePublicKey(rng, privateKey2, publicKey2);
|
||||
|
||||
SecByteBlock agreedValue(this->AgreedValueLength()), agreedValue2(this->AgreedValueLength());
|
||||
bool agreed1 = this->Agree(agreedValue, privateKey, publicKey2);
|
||||
bool agreed2 = this->Agree(agreedValue2, privateKey2, publicKey);
|
||||
|
||||
if (!agreed1 || !agreed2 || agreedValue != agreedValue2)
|
||||
throw SelfTestFailure(this->AlgorithmName() + ": pairwise consistency test failed");
|
||||
}
|
||||
}
|
||||
|
||||
static std::string CRYPTOPP_API StaticAlgorithmName()
|
||||
{return GroupParameters::StaticAlgorithmNamePrefix() + DH_Algorithm::StaticAlgorithmName();}
|
||||
std::string AlgorithmName() const {return StaticAlgorithmName();}
|
||||
|
||||
private:
|
||||
const DL_KeyAgreementAlgorithm<Element> & GetKeyAgreementAlgorithm() const
|
||||
{return Singleton<DH_Algorithm>().Ref();}
|
||||
DL_GroupParameters<Element> & AccessAbstractGroupParameters()
|
||||
{return m_groupParameters;}
|
||||
|
||||
GroupParameters m_groupParameters;
|
||||
};
|
||||
|
||||
CRYPTOPP_DLL_TEMPLATE_CLASS DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime>;
|
||||
|
||||
/// \brief Diffie-Hellman in GF(p)
|
||||
/// \details DH() class is a typedef of DH_Domain(). The documentation that follows
|
||||
/// does not exist. Rather the documentation was created in response to <a href="https://github.com/weidai11/cryptopp/issues/328">Issue
|
||||
/// 328, Diffie-Hellman example code not compiling</a>.
|
||||
/// \details Generally speaking, a DH() object is ephemeral and is intended to execute one instance of the Diffie-Hellman protocol. The
|
||||
/// private and public key parts are not intended to be set or persisted. Rather, a new set of domain parameters are generated each
|
||||
/// time an object is created.
|
||||
/// \details Once a DH() object is created, once can retrieve the ephemeral public key for the other party with code similar to the
|
||||
/// following.
|
||||
/// <pre> AutoSeededRandomPool prng;
|
||||
/// Integer p, q, g;
|
||||
/// PrimeAndGenerator pg;
|
||||
///
|
||||
/// pg.Generate(1, prng, 512, 511);
|
||||
/// p = pg.Prime();
|
||||
/// q = pg.SubPrime();
|
||||
/// g = pg.Generator();
|
||||
///
|
||||
/// DH dh(p, q, g);
|
||||
/// SecByteBlock t1(dh.PrivateKeyLength()), t2(dh.PublicKeyLength());
|
||||
/// dh.GenerateKeyPair(prng, t1, t2);
|
||||
/// Integer k1(t1, t1.size()), k2(t2, t2.size());
|
||||
///
|
||||
/// cout << "Private key:\n";
|
||||
/// cout << hex << k1 << endl;
|
||||
///
|
||||
/// cout << "Public key:\n";
|
||||
/// cout << hex << k2 << endl;</pre>
|
||||
///
|
||||
/// \details Output of the program above will be similar to the following.
|
||||
/// <pre> $ ./cryptest.exe
|
||||
/// Private key:
|
||||
/// 72b45a42371545e9d4880f48589aefh
|
||||
/// Public key:
|
||||
/// 45fdb13f97b1840626f0250cec1dba4a23b894100b51fb5d2dd13693d789948f8bfc88f9200014b2
|
||||
/// ba8dd8a6debc471c69ef1e2326c61184a2eca88ec866346bh</pre>
|
||||
/// \sa <a href="http://www.cryptopp.com/wiki/Diffie-Hellman">Diffie-Hellman on the Crypto++ wiki</a> and
|
||||
/// <a href="http://www.weidai.com/scan-mirror/ka.html#DH">Diffie-Hellman</a> in GF(p) with key validation
|
||||
/// \since Crypto++ 1.0
|
||||
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
|
||||
struct DH : public DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime>
|
||||
{
|
||||
typedef DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime> GroupParameters;
|
||||
typedef GroupParameters::Element Element;
|
||||
|
||||
virtual ~DH() {}
|
||||
|
||||
/// \brief Create an uninitialized Diffie-Hellman object
|
||||
DH() : DH_Domain() {}
|
||||
|
||||
/// \brief Initialize a Diffie-Hellman object
|
||||
/// \param bt BufferedTransformation with group parameters and options
|
||||
DH(BufferedTransformation &bt) : DH_Domain(bt) {}
|
||||
|
||||
/// \brief Initialize a Diffie-Hellman object
|
||||
/// \param params group parameters and options
|
||||
DH(const GroupParameters ¶ms) : DH_Domain(params) {}
|
||||
|
||||
/// \brief Create a Diffie-Hellman object
|
||||
/// \param rng a RandomNumberGenerator derived class
|
||||
/// \param modulusBits the size of the modulus, in bits
|
||||
/// \details This function overload of Initialize() creates a new Diffie-Hellman object because it
|
||||
/// takes a RandomNumberGenerator() as a parameter.
|
||||
DH(RandomNumberGenerator &rng, unsigned int modulusBits) : DH_Domain(rng, modulusBits) {}
|
||||
|
||||
/// \brief Initialize a Diffie-Hellman object
|
||||
/// \param p the modulus
|
||||
/// \param g the generator
|
||||
DH(const Integer &p, const Integer &g) : DH_Domain(p, g) {}
|
||||
|
||||
/// \brief Initialize a Diffie-Hellman object
|
||||
/// \param p the modulus
|
||||
/// \param q the subgroup order
|
||||
/// \param g the generator
|
||||
DH(const Integer &p, const Integer &q, const Integer &g) : DH_Domain(p, q, g) {}
|
||||
|
||||
/// \brief Creates a Diffie-Hellman object
|
||||
/// \param rng a RandomNumberGenerator derived class
|
||||
/// \param modulusBits the size of the modulus, in bits
|
||||
/// \details This function overload of Initialize() creates a new Diffie-Hellman object because it
|
||||
/// takes a RandomNumberGenerator() as a parameter.
|
||||
void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits)
|
||||
{AccessGroupParameters().Initialize(rng, modulusBits);}
|
||||
|
||||
/// \brief Initialize a Diffie-Hellman object
|
||||
/// \param p the modulus
|
||||
/// \param g the generator
|
||||
void Initialize(const Integer &p, const Integer &g)
|
||||
{AccessGroupParameters().Initialize(p, g);}
|
||||
|
||||
/// \brief Initialize a Diffie-Hellman object
|
||||
/// \param p the modulus
|
||||
/// \param q the subgroup order
|
||||
/// \param g the generator
|
||||
void Initialize(const Integer &p, const Integer &q, const Integer &g)
|
||||
{AccessGroupParameters().Initialize(p, q, g);}
|
||||
};
|
||||
#else
|
||||
// The real DH class is a typedef.
|
||||
typedef DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime> DH;
|
||||
#endif
|
||||
|
||||
NAMESPACE_END
|
||||
|
||||
#endif
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user