some small fixes

This commit is contained in:
Mari Wahl 2014-10-11 01:54:02 -04:00
parent 52067188ed
commit 9cdfa95054
89 changed files with 27401 additions and 0 deletions

View File

@ -0,0 +1,58 @@
Acknowledgements
----------------
This list is sorted in alphabetical order, and is probably incomplete.
I'd like to thank everybody who contributed in any way, with code, bug
reports, and comments.
This list should not be interpreted as an endorsement of PyCrypto by the
people on it.
Please let me know if your name isn't here and should be!
- Dwayne C. Litzenberger
Nevins Bartolomeo
Thorsten E. Behrens
Tim Berners-Lee
Frédéric Bertolus
Ian Bicking
Joris Bontje
Antoon Bosselaers
Andrea Bottoni
Jean-Paul Calderone
Sergey Chernov
Geremy Condra
Jan Dittberner
Andrew Eland
Philippe Frycia
Peter Gutmann
Hirendra Hindocha
Nikhil Jhingan
Sebastian Kayser
Ryan Kelly
Andrew M. Kuchling
Piers Lauder
Legrandin <gooksankoo@hoiptorrow.mailexpire.com>
M.-A. Lemburg
Wim Lewis
Mark Moraes
Lim Chee Siang
Bryan Olson
Wallace Owen
Colin Plumb
Robey Pointer
Lorenz Quack
Sebastian Ramacher
Jeethu Rao
James P. Rutledge
Matt Schreiner
Peter Simmons
Janne Snabb
Tom St. Denis
Anders Sundman
Paul Swartz
Kevin M. Turner
Barry A. Warsaw
Eric Young

View File

@ -0,0 +1,69 @@
Copyright and licensing of the Python Cryptography Toolkit ("PyCrypto"):
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Previously, the copyright and/or licensing status of the Python
Cryptography Toolkit ("PyCrypto") had been somewhat ambiguous. The
original intention of Andrew M. Kuchling and other contributors has
been to dedicate PyCrypto to the public domain, but that intention was
not necessarily made clear in the original disclaimer (see
LEGAL/copy/LICENSE.orig).
Additionally, some files within PyCrypto had specified their own
licenses that differed from the PyCrypto license itself. For example,
the original RIPEMD.c module simply had a copyright statement and
warranty disclaimer, without clearly specifying any license terms.
(An updated version on the author's website came with a license that
contained a GPL-incompatible advertising clause.)
To rectify this situation for PyCrypto 2.1, the following steps have
been taken:
1. Obtaining explicit permission from the original contributors to
dedicate their contributions to the public domain if they have not
already done so. (See the "LEGAL/copy/stmts" directory for
contributors' statements.)
2. Replacing some modules with clearly-licensed code from other
sources (e.g. the DES and DES3 modules were replaced with new ones
based on Tom St. Denis's public-domain LibTomCrypt library.)
3. Replacing some modules with code written from scratch (e.g. the
RIPEMD and Blowfish modules were re-implemented from their
respective algorithm specifications without reference to the old
implementations).
4. Removing some modules altogether without replacing them.
To the best of our knowledge, with the exceptions noted below or
within the files themselves, the files that constitute PyCrypto are in
the public domain. Most are distributed with the following notice:
The contents of this file are dedicated to the public domain. To
the extent that dedication to the public domain is not available,
everyone is granted a worldwide, perpetual, royalty-free,
non-exclusive license to exercise all rights associated with the
contents of this file for any purpose whatsoever.
No rights are reserved.
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 AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Exception:
- Portions of HMAC.py and setup.py are derived from Python 2.2, and
are therefore Copyright (c) 2001, 2002, 2003 Python Software
Foundation (All Rights Reserved). They are licensed by the PSF
under the terms of the Python 2.2 license. (See the file
LEGAL/copy/LICENSE.python-2.2 for details.)
EXPORT RESTRICTIONS:
Note that the export or re-export of cryptographic software and/or
source code may be subject to regulation in your jurisdiction.

View File

@ -0,0 +1,699 @@
2.6.1
=====
* [CVE-2013-1445] Fix PRNG not correctly reseeded in some situations.
In previous versions of PyCrypto, the Crypto.Random PRNG exhibits a
race condition that may cause forked processes to generate identical
sequences of 'random' numbers.
This is a fairly obscure bug that will (hopefully) not affect many
applications, but the failure scenario is pretty bad. Here is some
sample code that illustrates the problem:
from binascii import hexlify
import multiprocessing, pprint, time
import Crypto.Random
def task_main(arg):
a = Crypto.Random.get_random_bytes(8)
time.sleep(0.1)
b = Crypto.Random.get_random_bytes(8)
rdy, ack = arg
rdy.set()
ack.wait()
return "%s,%s" % (hexlify(a).decode(),
hexlify(b).decode())
n_procs = 4
manager = multiprocessing.Manager()
rdys = [manager.Event() for i in range(n_procs)]
acks = [manager.Event() for i in range(n_procs)]
Crypto.Random.get_random_bytes(1)
pool = multiprocessing.Pool(processes=n_procs,
initializer=Crypto.Random.atfork)
res_async = pool.map_async(task_main, zip(rdys, acks))
pool.close()
[rdy.wait() for rdy in rdys]
[ack.set() for ack in acks]
res = res_async.get()
pprint.pprint(sorted(res))
pool.join()
The output should be random, but it looked like this:
['c607803ae01aa8c0,2e4de6457a304b34',
'c607803ae01aa8c0,af80d08942b4c987',
'c607803ae01aa8c0,b0e4c0853de927c4',
'c607803ae01aa8c0,f0362585b3fceba4']
This release fixes the problem by resetting the rate-limiter when
Crypto.Random.atfork() is invoked. It also adds some tests and a
few related comments.
2.6
===
* [CVE-2012-2417] Fix LP#985164: insecure ElGamal key generation.
(thanks: Legrandin)
In the ElGamal schemes (for both encryption and signatures), g is
supposed to be the generator of the entire Z^*_p group. However, in
PyCrypto 2.5 and earlier, g is more simply the generator of a random
sub-group of Z^*_p.
The result is that the signature space (when the key is used for
signing) or the public key space (when the key is used for encryption)
may be greatly reduced from its expected size of log(p) bits, possibly
down to 1 bit (the worst case if the order of g is 2).
While it has not been confirmed, it has also been suggested that an
attacker might be able to use this fact to determine the private key.
Anyone using ElGamal keys should generate new keys as soon as practical.
Any additional information about this bug will be tracked at
https://bugs.launchpad.net/pycrypto/+bug/985164
* Huge documentation cleanup (thanks: Legrandin).
* Added more tests, including test vectors from NIST 800-38A
(thanks: Legrandin)
* Remove broken MODE_PGP, which never actually worked properly.
A new mode, MODE_OPENPGP, has been added for people wishing to write
OpenPGP implementations. Note that this does not implement the full
OpenPGP specification, only the "OpenPGP CFB mode" part of that
specification.
https://bugs.launchpad.net/pycrypto/+bug/996814
* Fix: getPrime with invalid input causes Python to abort with fatal error
https://bugs.launchpad.net/pycrypto/+bug/988431
* Fix: Segfaults within error-handling paths
(thanks: Paul Howarth & Dave Malcolm)
https://bugs.launchpad.net/pycrypto/+bug/934294
* Fix: Block ciphers allow empty string as IV
https://bugs.launchpad.net/pycrypto/+bug/997464
* Fix DevURandomRNG to work with Python3's new I/O stack.
(thanks: Sebastian Ramacher)
* Remove automagic dependencies on libgmp and libmpir, let the caller
disable them using args.
* Many other minor bug fixes and improvements (mostly thanks to Legrandin)
2.5
===
* Added PKCS#1 encryption schemes (v1.5 and OAEP). We now have
a decent, easy-to-use non-textbook RSA implementation. Yay!
* Added PKCS#1 signature schemes (v1.5 and PSS). v1.5 required some
extensive changes to Hash modules to contain the algorithm specific
ASN.1 OID. To that end, we now always have a (thin) Python module to
hide the one in pure C.
* Added 2 standard Key Derivation Functions (PBKDF1 and PBKDF2).
* Added export/import of RSA keys in OpenSSH and PKCS#8 formats.
* Added password-protected export/import of RSA keys (one old method
for PKCS#8 PEM only).
* Added ability to generate RSA key pairs with configurable public
exponent e.
* Added ability to construct an RSA key pair even if only the private
exponent d is known, and not p and q.
* Added SHA-2 C source code (fully from Lorenz Quack).
* Unit tests for all the above.
* Updates to documentation (both inline and in Doc/pycrypt.rst)
* All of the above changes were put together by Legrandin (Thanks!)
* Minor bug fixes (setup.py and tests).
2.4.1
=====
* Fix "error: Setup script exited with error: src/config.h: No such file or
directory" when installing via easy_install. (Sebastian Ramacher)
2.4
===
* Python 3 support! (Thorsten E. Behrens, Anders Sundman)
PyCrypto now supports every version of Python from 2.1 through 3.2.
* Timing-attack countermeasures in _fastmath: When built against
libgmp version 5 or later, we use mpz_powm_sec instead of mpz_powm.
This should prevent the timing attack described by Geremy Condra at
PyCon 2011:
http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-through-the-side-channel-timing-and-implementation-attacks-in-python-4897955
* New hash modules (for Python >= 2.5 only): SHA224, SHA384, and
SHA512 (Frédéric Bertolus)
* Configuration using GNU autoconf. This should help fix a bunch of
build issues.
* Support using MPIR as an alternative to GMP.
* Improve the test command in setup.py, by allowing tests to be
performed on a single sub-package or module only. (Legrandin)
You can now do something like this:
python setup.py test -m Hash.SHA256 --skip-slow-tests
* Fix double-decref of "counter" when Cipher object initialisation
fails (Ryan Kelly)
* Apply patches from Debian's python-crypto 2.3-3 package (Jan
Dittberner, Sebastian Ramacher):
- fix-RSA-generate-exception.patch
- epydoc-exclude-introspect.patch
- no-usr-local.patch
* Fix launchpad bug #702835: "Import key code is not compatible with
GMP library" (Legrandin)
* More tests, better documentation, various bugfixes.
2.3
===
* Fix NameError when attempting to use deprecated getRandomNumber()
function.
* _slowmath: Compute RSA u parameter when it's not given to
RSA.construct. This makes _slowmath behave the same as _fastmath in
this regard.
* Make RSA.generate raise a more user-friendly exception message when
the user tries to generate a bogus-length key.
2.2
===
* Deprecated Crypto.Util.number.getRandomNumber(), which had confusing
semantics. It's been replaced by getRandomNBitInteger and
getRandomInteger. (Thanks: Lorenz Quack)
* Better isPrime() and getPrime() implementations that do a real
Rabin-Miller probabilistic primality test (not the phony test we did
before with fixed bases). (Thanks: Lorenz Quack)
* getStrongPrime() implementation for generating RSA primes.
(Thanks: Lorenz Quack)
* Support for importing and exporting RSA keys in DER and PEM format.
(Thanks: Legrandin)
* Fix PyCrypto when floor division (python -Qnew) is enabled.
* When building using gcc, use -std=c99 for compilation. This should
fix building on FreeBSD and NetBSD.
2.1.0
=====
* Fix building PyCrypto on Win64 using MS Visual Studio 9.
(Thanks: Nevins Bartolomeo.)
2.1.0beta1
==========
* Modified RSA.generate() to ensure that e is coprime to p-1 and q-1.
Apparently, RSA.generate was capable of generating unusable keys.
2.1.0alpha2
===========
* Modified isPrime() to release the global interpreter lock while
performing computations. (patch from Lorenz Quack)
* Release the GIL while encrypting, decrypting, and hashing (but not
during initialization or finalization).
* API changes:
- Removed RandomPoolCompat and made Crypto.Util.randpool.RandomPool
a wrapper around Crypto.Random that emits a DeprecationWarning.
This is to discourage developers from attempting to provide
backwards compatibility for systems where there are NO strong
entropy sources available.
- Added Crypto.Random.get_random_bytes(). This should allow people
to use something like this if they want backwards-compatibility:
try:
from Crypto.Random import get_random_bytes
except ImportError:
try:
from os import urandom as get_random_bytes
except ImportError:
get_random_bytes = open("/dev/urandom", "rb").read
- Implemented __ne__() on pubkey, which fixes the following broken
behaviour:
>>> pk.publickey() == pk.publickey()
True
>>> pk.publickey() != pk.publickey()
True
(patch from Lorenz Quack)
- Block ciphers created with MODE_CTR can now operate on strings of
any size, rather than just multiples of the underlying cipher's
block size.
- Crypto.Util.Counter objects now raise OverflowError when they wrap
around to zero. You can override this new behaviour by passing
allow_wraparound=True to Counter.new()
2.1.0alpha1
===========
* This version supports Python versions 2.1 through 2.6.
* Clarified copyright status of much of the existing code by tracking
down Andrew M. Kuchling, Barry A. Warsaw, Jeethu Rao, Joris Bontje,
Mark Moraes, Paul Swartz, Robey Pointer, and Wim Lewis and getting
their permission to clarify the license/public-domain status of their
contributions. Many thanks to all involved!
* Replaced the test suite with a new, comprehensive package
(Crypto.SelfTest) that includes documentation about where its test
vectors came from, or how they were derived.
Use "python setup.py test" to run the tests after building.
* API changes:
- Added Crypto.version_info, which from now on will contain version
information in a format similar to Python's sys.version_info.
- Added a new random numbers API (Crypto.Random), and deprecated the
old one (Crypto.Util.randpool.RandomPool), which was misused more
often than not.
The new API is used by invoking Crypto.Random.new() and then just
reading from the file-like object that is returned.
CAVEAT: To maintain the security of the PRNG, you must call
Crypto.Random.atfork() in both the parent and the child processes
whenever you use os.fork(). Otherwise, the parent and child will
share copies of the same entropy pool, causing them to return the
same results! This is a limitation of Python, which does not
provide readily-accessible hooks to os.fork(). It's also a
limitation caused by the failure of operating systems to provide
sufficiently fast, trustworthy sources of cryptographically-strong
random numbers.
- Crypto.PublicKey now raises ValueError/TypeError/RuntimeError
instead of the various custom "error" exceptions
- Removed the IDEA and RC5 modules due to software patents. Debian
has been doing this for a while
- Added Crypto.Random.random, a strong version of the standard Python
'random' module.
- Added Crypto.Util.Counter, providing fast counter implementations
for use with CTR-mode ciphers.
* Bug fixes:
- Fixed padding bug in SHA256; this resulted in bad digests whenever
(the number of bytes hashed) mod 64 == 55.
- Fixed a 32-bit limitation on the length of messages the SHA256 module
could hash.
- AllOrNothing: Fixed padding bug in digest()
- Fixed a bad behaviour of the XOR cipher module: It would silently
truncate all keys to 32 bytes. Now it raises ValueError when the
key is too long.
- DSA: Added code to enforce FIPS 186-2 requirements on the size of
the prime p
- Fixed the winrandom module, which had been omitted from the build
process, causing security problems for programs that misuse RandomPool.
- Fixed infinite loop when attempting to generate RSA keys with an
odd number of bits in the modulus. (Not that you should do that.)
* Clarified the documentation for Crypto.Util.number.getRandomNumber.
Confusingly, this function does NOT return N random bits; It returns
a random N-bit number, i.e. a random number between 2**(N-1) and (2**N)-1.
Note that getRandomNumber is for internal use only and may be
renamed or removed in future releases.
* Replaced RIPEMD.c with a new implementation (RIPEMD160.c) to
alleviate copyright concerns.
* Replaced the DES/DES3 modules with ones based on libtomcrypt-1.16 to
alleviate copyright concerns.
* Replaced Blowfish.c with a new implementation to alleviate copyright
concerns.
* Added a string-XOR implementation written in C (Crypto.Util.strxor)
and used it to speed up Crypto.Hash.HMAC
* Converted documentation to reStructured Text.
* Added epydoc configuration Doc/epydoc-config
* setup.py now emits a warning when building without GMP.
* Added pct-speedtest.py to the source tree for doing performance
testing on the new code.
* Cleaned up the code in several places.
2.0.1
=====
* Fix SHA256 and RIPEMD on AMD64 platform.
* Deleted Demo/ directory.
* Add PublicKey to Crypto.__all__
2.0
===
* Added SHA256 module contributed by Jeethu Rao, with test data
from Taylor Boon.
* Fixed AES.c compilation problems with Borland C.
(Contributed by Jeethu Rao.)
* Fix ZeroDivisionErrors on Windows, caused by the system clock
not having enough resolution.
* Fix 2.1/2.2-incompatible use of (key not in dict),
pointed out by Ian Bicking.
* Fix FutureWarning in Crypto.Util.randpool, noted by James P Rutledge.
1.9alpha6
=========
* Util.number.getPrime() would inadvertently round off the bit
size; if you asked for a 129-bit prime or 135-bit prime, you
got a 128-bit prime.
* Added Util/test/prime_speed.py to measure the speed of prime
generation, and PublicKey/test/rsa_speed.py to measure
the speed of RSA operations.
* Merged the _rsa.c and _dsa.c files into a single accelerator
module, _fastmath.c.
* Speed improvements: Added fast isPrime() function to _fastmath,
cutting the time to generate a 1024-bit prime by a factor of 10.
Optimized the C version of RSA decryption to use a longer series
of operations that's roughly 3x faster than a single
exponentiation. (Contributed by Joris Bontje.)
* Added support to RSA key objects for blinding and unblinding
data. (Contributed by Joris Bontje.)
* Simplified RSA key generation: hard-wired the encryption
exponent to 65537 instead of generating a random prime;
generate prime factors in a loop until the product
is large enough.
* Renamed cansign(), canencrypt(), hasprivate(), to
can_sign, can_encrypt, has_private. If people shriek about
this change very loudly, I'll add aliases for the old method
names that log a warning and call the new method.
1.9alpha5
=========
* Many randpool changes. RandomPool now has a
randomize(N:int) method that can be called to get N
bytes of entropy for the pool (N defaults to 0,
which 'fills up' the pool's entropy) KeyboardRandom
overloads this method.
* Added src/winrand.c for Crypto.Util.winrandom and
now use winrandom for _randomize if possible.
(Calls Windows CryptoAPI CryptGenRandom)
* Several additional places for stirring the pool,
capturing inter-event entropy when reading/writing,
stirring before and after saves.
* RandomPool.add_event now returns the number of
estimated bits of added entropy, rather than the
pool entropy itself (since the pool entropy is
capped at the number of bits in the pool)
* Moved termios code from KeyboardRandomPool into a
KeyboardEntry class, provided a version for Windows
using msvcrt.
* Fix randpool.py crash on machines with poor timer resolution.
(Reported by Mark Moraes and others.)
* If the GNU GMP library is available, two C extensions will be
compiled to speed up RSA and DSA operations. (Contributed by
Paul Swartz.)
* DES3 with a 24-byte key was broken; now fixed.
(Patch by Philippe Frycia.)
1.9alpha4
=========
* Fix compilation problem on Windows.
* HMAC.py fixed to work with pre-2.2 Pythons
* setup.py now dies if built with Python 1.x
1.9alpha3
=========
* Fix a ref-counting bug that caused core dumps.
(Reported by Piers Lauder and an anonymous SF poster.)
1.9alpha2
=========
* (Backwards incompatible) The old Crypto.Hash.HMAC module is
gone, replaced by a copy of hmac.py from Python 2.2's standard
library. It will display a warning on interpreter versions
older than 2.2.
* (Backwards incompatible) Restored the Crypto.Protocol package,
and modernized and tidied up the two modules in it,
AllOrNothing.py and Chaffing.py, renaming various methods
and changing the interface.
* (Backwards incompatible) Changed the function names in
Crypto.Util.RFC1751.
* Restored the Crypto.PublicKey package at user request. I
think I'll leave it in the package and warn about it in the
documentation. I hope that eventually I can point to
someone else's better public-key code, and at that point I
may insert warnings and begin the process of deprecating
this code.
* Fix use of a Python 2.2 C function, replacing it with a
2.1-compatible equivalent. (Bug report and patch by Andrew
Eland.)
* Fix endianness bugs that caused test case failures on Sparc,
PPC, and doubtless other platforms.
* Fixed compilation problem on FreeBSD and MacOS X.
* Expanded the test suite (requires Sancho, from
http://www.mems-exchange.org/software/sancho/)
* Added lots of docstrings, so 'pydoc Crypto' now produces
helpful output. (Open question: maybe *all* of the documentation
should be moved into docstrings?)
* Make test.py automatically add the build/* directory to sys.path.
* Removed 'inline' declaration from C functions. Some compilers
don't support it, and Python's pyconfig.h no longer tells you whether
it's supported or not. After this change, some ciphers got slower,
but others got faster.
* The C-level API has been changed to reduce the amount of
memory-to-memory copying. This makes the code neater, but
had ambiguous performance effects; again, some ciphers got slower
and others became faster. Probably this is due to my compiler
optimizing slightly worse or better as a result.
* Moved C source implementations into src/ from block/, hash/,
and stream/. Having Hash/ and hash/ directories causes problems
on case-insensitive filesystems such as Mac OS.
* Cleaned up the C code for the extensions.
1.9alpha1
=========
* Added Crypto.Cipher.AES.
* Added the CTR mode and the variable-sized CFB mode from the
NIST standard on feedback modes.
* Removed Diamond, HAVAL, MD5, Sapphire, SHA, and Skipjack. MD5
and SHA are included with Python; the others are all of marginal
usefulness in the real world.
* Renamed the module-level constants ECB, CFB, &c., to MODE_ECB,
MODE_CFB, as part of making the block encryption modules
compliant with PEP 272. (I'm not sure about this change;
if enough users complain about it, I might back it out.)
* Made the hashing modules compliant with PEP 247 (not backward
compatible -- the major changes are that the constructor is now
MD2.new and not MD2.MD2, and the size of the digest is now
given as 'digest_size', not 'digestsize'.
* The Crypto.PublicKey package is no longer installed; the
interfaces are all wrong, and I have no idea what the right
interfaces should be.
1.1alpha2
=========
* Most importantly, the distribution has been broken into two
parts: exportable, and export-controlled. The exportable part
contains all the hashing algorithms, signature-only public key
algorithms, chaffing & winnowing, random number generation, various
utility modules, and the documentation.
The export-controlled part contains public-key encryption
algorithms such as RSA and ElGamal, and bulk encryption algorithms
like DES, IDEA, or Skipjack. Getting this code still requires that
you go through an access control CGI script, and denies you access if
you're outside the US or Canada.
* Added the RIPEMD hashing algorithm. (Contributed by
Hirendra Hindocha.)
* Implemented the recently declassified Skipjack block
encryption algorithm. My implementation runs at 864 K/sec on a
PII/266, which isn't particularly fast, but you're probably better off
using another algorithm anyway. :)
* A simple XOR cipher has been added, mostly for use by the
chaffing/winnowing code. (Contributed by Barry Warsaw.)
* Added Protocol.Chaffing and Hash.HMAC.py. (Contributed by
Barry Warsaw.)
Protocol.Chaffing implements chaffing and winnowing, recently
proposed by R. Rivest, which hides a message (the wheat) by adding
many noise messages to it (the chaff). The chaff can be discarded by
the receiver through a message authentication code. The neat thing
about this is that it allows secret communication without actually
having an encryption algorithm, and therefore this falls within the
exportable subset.
* Tidied up randpool.py, and removed its use of a block
cipher; this makes it work with only the export-controlled subset
available.
* Various renamings and reorganizations, mostly internal.
1.0.2
=====
* Changed files to work with Python 1.5; everything has been
re-arranged into a hierarchical package. (Not backward compatible.)
The package organization is:
Crypto.
Hash.
MD2, MD4, MD5, SHA, HAVAL
Cipher.
ARC2, ARC4, Blowfish, CAST, DES, DES3, Diamond,
IDEA, RC5, Sapphire
PublicKey.
DSA, ElGamal, qNEW, RSA
Util.
number, randpool, RFC1751
Since this is backward-incompatible anyway, I also changed
module names from all lower-case to mixed-case: diamond -> Diamond,
rc5 -> RC5, etc. That had been an annoying inconsistency for a while.
* Added CAST5 module contributed by <wiml@hhhh.org>.
* Added qNEW digital signature algorithm (from the digisign.py
I advertised a while back). (If anyone would like to suggest new
algorithms that should be implemented, please do; I think I've got
everything that's really useful at the moment, but...)
* Support for keyword arguments has been added. This allowed
removing the obnoxious key handling for Diamond and RC5, where the
first few bytes of the key indicated the number of rounds to use, and
various other parameters. Now you need only do something like:
from Crypto.Cipher import RC5
obj = RC5.new(key, RC5.ECB, rounds=8)
(Not backward compatible.)
* Various function names have been changed, and parameter
names altered. None of these were part of the public interface, so it
shouldn't really matter much.
* Various bugs fixed, the test suite has been expanded, and
the build process simplified.
* Updated the documentation accordingly.
1.0.1
=====
* Changed files to work with Python 1.4 .
* The DES and DES3 modules now automatically correct the
parity of their keys.
* Added R. Rivest's DES test (see http://theory.lcs.mit.edu/~rivest/destest.txt)
1.0.0
=====
* REDOC III succumbed to differential cryptanalysis, and has
been removed.
* The crypt and rotor modules have been dropped; they're still
available in the standard Python distribution.
* The Ultra-Fast crypt() module has been placed in a separate
distribution.
* Various bugs fixed.

View File

@ -0,0 +1,27 @@
# epydoc configuration file for PyCrypto.
# See http://epydoc.sourceforge.net/configfile.html for sample configuration.
[epydoc]
modules: Crypto
docformat: restructuredtext
output: html
target: Doc/apidoc/
sourcecode: no
# Do not include private variables
private: no
# Include the complete set of inherited methods, but grouped in a special
# section
inheritance: grouped
name: PyCrypto API Documentation
url: http://www.pycrypto.org/
link: <a href="http://www.pycrypto.org/">PyCrypto.org</a>
# The documentation is usually built on a Linux machine; nt.py tries to
# import the winrandom module.
exclude-introspect: ^Crypto\.Random\.OSRNG\.nt|Crypto\.Util\.winrandom$
exclude-introspect: ^Crypto\.Util\.osentropy\.nt$
exclude: ^Crypto\.SelfTest

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,3 @@
00INDEX - This file
tsu-notify.mbox - Notification sent per U.S. export regulations
copy/ - Copyright info & public-domain dedications

View File

@ -0,0 +1,49 @@
PyCrypto Code Submission Requirements - Rev. C
Last updated: 2009-02-28
In an effort to further clarify PyCrypto's licensing terms, anyone submitting
code to PyCrypto must be able to certify the following (taken from the Linux
kernel's SubmittingPatches file):
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
In addition, the code's author must not be a national, citizen, or resident of
the United States of America.
In addition, the code must not be of U.S. origin.
In addition, all new code contributed to PyCrypto must be dedicated to the
public domain as follows:
The contents of this file are dedicated to the public domain. To the extent
that dedication to the public domain is not available, everyone is granted a
worldwide, perpetual, royalty-free, non-exclusive license to exercise all
rights associated with the contents of this file for any purpose whatsoever.
No rights are reserved.
=== EOF ===

View File

@ -0,0 +1,4 @@
00INDEX This file
LICENSE.orig Original (deprecated) license for the Python Cryptography Toolkit
LICENSE.libtom LICENSE file from LibTomCrypt
stmts/ Statements by contributors

View File

@ -0,0 +1,5 @@
LibTomCrypt is public domain. As should all quality software be.
Tom St Denis

View File

@ -0,0 +1,15 @@
===================================================================
Distribute and use freely; there are no restrictions on further
dissemination and usage except those imposed by the laws of your
country of residence. This software is provided "as is" without
warranty of fitness for use or suitability for any purpose, express
or implied. Use at your own risk or not at all.
===================================================================
Incorporating the code into commercial products is permitted; you do
not have to make source available or contribute your changes back
(though that would be nice).
--amk (www.amk.ca)

View File

@ -0,0 +1,253 @@
A. HISTORY OF THE SOFTWARE
==========================
Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC. Guido remains Python's
principal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.
In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
year, the PythonLabs team moved to Digital Creations (now Zope
Corporation, see http://www.zope.com). In 2001, the Python Software
Foundation (PSF, see http://www.python.org/psf/) was formed, a
non-profit organization created specifically to own Python-related
Intellectual Property. Zope Corporation is a sponsoring member of
the PSF.
All Python releases are Open Source (see http://www.opensource.org for
the Open Source Definition). Historically, most, but not all, Python
releases have also been GPL-compatible; the table below summarizes
the various releases.
Release Derived Year Owner GPL-
from compatible? (1)
0.9.0 thru 1.2 1991-1995 CWI yes
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
1.6 1.5.2 2000 CNRI no
2.0 1.6 2000 BeOpen.com no
1.6.1 1.6 2001 CNRI no
2.1 2.0+1.6.1 2001 PSF no
2.0.1 2.0+1.6.1 2001 PSF yes
2.1.1 2.1+2.0.1 2001 PSF yes
2.2 2.1.1 2001 PSF yes
2.1.2 2.1.1 2002 PSF yes
2.1.3 2.1.2 2002 PSF yes
2.2.1 2.2 2002 PSF yes
2.2.2 2.2.1 2002 PSF yes
2.2.3 2.2.2 2003 PSF yes
Footnotes:
(1) GPL-compatible doesn't mean that we're distributing Python under
the GPL. All Python licenses, unlike the GPL, let you distribute
a modified version without making your changes open source. The
GPL-compatible licenses make it possible to combine Python with
other software that is released under the GPL; the others don't.
Thanks to the many outside volunteers who have worked under Guido's
direction to make these releases possible.
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
===============================================================
PSF LICENSE AGREEMENT FOR PYTHON 2.2.3
--------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using Python 2.2.3 software in source or binary form and its
associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 2.2.3
alone or in any derivative version, provided, however, that PSF's
License Agreement and PSF's notice of copyright, i.e., "Copyright (c)
2001, 2002, 2003 Python Software Foundation; All Rights Reserved" are
retained in Python 2.2.3 alone or in any derivative version prepared
by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 2.2.3 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 2.2.3.
4. PSF is making Python 2.2.3 available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.2.3 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
2.2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.2.3,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python 2.2.3, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
-------------------------------------------
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization ("Licensee") accessing and otherwise using
this software in source or binary form and its associated
documentation ("the Software").
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an "AS IS"
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
---------------------------------------
1. This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an office at 1895 Preston White Drive,
Reston, VA 20191 ("CNRI"), and the Individual or Organization
("Licensee") accessing and otherwise using Python 1.6.1 software in
source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 1.6.1
alone or in any derivative version, provided, however, that CNRI's
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
1995-2001 Corporation for National Research Initiatives; All Rights
Reserved" are retained in Python 1.6.1 alone or in any derivative
version prepared by Licensee. Alternately, in lieu of CNRI's License
Agreement, Licensee may substitute the following text (omitting the
quotes): "Python 1.6.1 is made available subject to the terms and
conditions in CNRI's License Agreement. This Agreement together with
Python 1.6.1 may be located on the Internet using the following
unique, persistent identifier (known as a handle): 1895.22/1013. This
Agreement may also be obtained from a proxy server on the Internet
using the following URL: http://hdl.handle.net/1895.22/1013".
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 1.6.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. This License Agreement shall be governed by the federal
intellectual property law of the United States, including without
limitation the federal copyright law, and, to the extent such
U.S. federal law does not apply, by the law of the Commonwealth of
Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based
on Python 1.6.1 that incorporate non-separable material that was
previously distributed under the GNU General Public License (GPL), the
law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee. This
License Agreement does not grant permission to use CNRI trademarks or
trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.
8. By clicking on the "ACCEPT" button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
--------------------------------------------------
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@ -0,0 +1,156 @@
From dlitz@dlitz.net Sun Nov 23 00:17:22 2008
Date: Sun, 23 Nov 2008 00:17:22 -0500
From: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
To: "A. M. Kuchling" <amk@amk.ca>
Subject: PyCrypto license clarification
Message-ID: <20081123051722.GA29253@rivest.dlitz.net>
MIME-Version: 1.0
Content-Type: multipart/signed; micalg=pgp-sha1;
protocol="application/pgp-signature"; boundary="YiEDa0DAkWCtVeE4"
Content-Disposition: inline
X-Primary-Address: dlitz@dlitz.net
X-Homepage: http://www.dlitz.net/
X-OpenPGP: url=http://www.dlitz.net/go/gpgkey/;
id=19E11FE8B3CFF273ED174A24928CEC1339C25CF7 (only for key signing);
preference=unprotected
X-OpenPGP: url=http://www.dlitz.net/go/gpgkey/;
id=4B2AFD82FC7D9E3838D9179F1C11B877E7804B45 (2008);
preference=signencrypt
User-Agent: Mutt/1.5.16 (2007-06-11)
Status: RO
Content-Length: 3461
Lines: 78
--YiEDa0DAkWCtVeE4
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable
Hi Andrew,
People often ask me what license PyCrypto is covered by, if it's=20
GPL-compatible, etc. Right now, I'm not really sure what to tell them. =20
The text in the current LICENSE file (quoted below) is not entirely clear=
=20
on the point of whether distributing modified versions is allowed. (It=20
says "distribute and use", but not "modify".)
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Distribute and use freely; there are no restrictions on further
dissemination and usage except those imposed by the laws of your
country of residence. This software is provided "as is" without
warranty of fitness for use or suitability for any purpose, express
or implied. Use at your own risk or not at all.
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Incorporating the code into commercial products is permitted; you do
not have to make source available or contribute your changes back
(though that would be nice).
--amk (www.amk.ca)
For the next PyCrypto release, I'd like to take steps to move toward a=20
clearer licensing regime. I'm asking as many copyright holders as I can=20
find, starting with you, if I can release PyCrypto under something clearer=
=20
and more standard. Below, I have quoted a public domain dedication that=20
was recommended in _Intellectual Property and Open Source: A Practical=20
Guide to Protecting Code_, by Van Lindberg.
May I, on your behalf, dedicate to the public domain your considerable=20
contributions to PyCrypto, with the following notice?
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
The contents of this file are dedicated to the public domain. To the
extent that dedication to the public domain is not available, everyone
is granted a worldwide, perpetual, royalty-free, non-exclusive license
to exercise all rights associated with the contents of this file for
any purpose whatsoever. No rights are reserved.
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Regards,
- Dwayne
--=20
Dwayne C. Litzenberger <dlitz@dlitz.net>
Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
Annual key (2008) - 4B2A FD82 FC7D 9E38 38D9 179F 1C11 B877 E780 4B45
--YiEDa0DAkWCtVeE4
Content-Type: application/pgp-signature; name="signature.asc"
Content-Description: Digital signature
Content-Disposition: inline
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
iEYEARECAAYFAkko52IACgkQHBG4d+eAS0XPPQCfcyQ2DdAXKg9N7Z+jeSFFD5EZ
yloAn33a3ZjkteyJaTbzEqImOEW8JGpf
=aBEW
-----END PGP SIGNATURE-----
--YiEDa0DAkWCtVeE4--
From amk@amk.ca Sun Nov 23 07:51:59 2008
X-Maildir-Dup-Checked: Yes
Return-Path: <amk@amk.ca>
X-Original-To: dwon@rivest.dlitz.net
Delivered-To: dwon@rivest.dlitz.net
Received: from goedel.dlitz.net (unknown [10.159.255.6])
by rivest.dlitz.net (Postfix) with ESMTP id 5C2C75047D
for <dwon@rivest.dlitz.net>; Sun, 23 Nov 2008 07:51:59 -0500 (EST)
Received: from localhost (localhost [127.0.0.1])
by goedel.dlitz.net (Postfix) with QMQP id D632D10111
for <dwon@rivest.dlitz.net>; Sun, 23 Nov 2008 06:51:58 -0600 (CST)
Received: (vmailmgr-postfix 12026 invoked by uid 1003); 23 Nov 2008 06:51:58 -0600
Delivered-To: m-dlitz-dlitz@dlitz.net
Received-SPF: none (goedel.dlitz.net: domain of amk@amk.ca does not designate permitted sender hosts)
Received: from mail5.sea5.speakeasy.net (mail5.sea5.speakeasy.net [69.17.117.7])
by goedel.dlitz.net (Postfix) with ESMTP id 97DC710105
for <dlitz@dlitz.net>; Sun, 23 Nov 2008 06:51:58 -0600 (CST)
Received: (qmail 3992 invoked from network); 23 Nov 2008 12:51:52 -0000
Received: from dsl092-163-165.wdc2.dsl.speakeasy.net (HELO localhost) (akuchling@[66.92.163.165])
(envelope-sender <amk@amk.ca>)
by mail5.sea5.speakeasy.net (qmail-ldap-1.03) with AES256-SHA encrypted SMTP
for <dlitz@dlitz.net>; 23 Nov 2008 12:51:52 -0000
Date: Sun, 23 Nov 2008 07:51:34 -0500
From: "A.M. Kuchling" <amk@amk.ca>
To: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
Subject: Re: PyCrypto license clarification
Message-ID: <20081123125134.GA21239@amk.local>
Reply-To: amk@amk.ca
References: <20081123051722.GA29253@rivest.dlitz.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
In-Reply-To: <20081123051722.GA29253@rivest.dlitz.net>
User-Agent: Mutt/1.5.13 (2006-08-11)
Status: RO
Content-Length: 537
Lines: 15
> People often ask me what license PyCrypto is covered by, if it's
> GPL-compatible, etc. Right now, I'm not really sure what to tell them.
> The text in the current LICENSE file (quoted below) is not entirely clear
> on the point of whether distributing modified versions is allowed. (It
> says "distribute and use", but not "modify".)
The intention is that it be public domain.
> May I, on your behalf, dedicate to the public domain your considerable
> contributions to PyCrypto, with the following notice?
You may.
--amk

View File

@ -0,0 +1,135 @@
From dlitz@dlitz.net Sat Feb 28 21:45:09 2009
Date: Sat, 28 Feb 2009 21:45:09 -0500
From: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
To: Barry A Warsaw <barry@python.org>
Subject: PyCrypto license clarification
Message-ID: <20090301024509.GA13195@rivest.dlitz.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Disposition: inline
User-Agent: Mutt/1.5.16 (2007-06-11)
Status: RO
Content-Length: 2535
Hi Barry,
I am the new maintainer of the Python Cryptography Toolkit, and I am
working on a new release at http://www.pycrypto.org/.
People often ask me what license PyCrypto is covered by, if it's
GPL-compatible, etc. Right now, I'm not really sure what to tell them.
The text in the current LICENSE file (quoted below) is not entirely clear
on the point of whether distributing modified versions is allowed. (It
says "distribute and use", but not "modify".)
===================================================================
Distribute and use freely; there are no restrictions on further
dissemination and usage except those imposed by the laws of your
country of residence. This software is provided "as is" without
warranty of fitness for use or suitability for any purpose, express
or implied. Use at your own risk or not at all.
===================================================================
Incorporating the code into commercial products is permitted; you do
not have to make source available or contribute your changes back
(though that would be nice).
--amk (www.amk.ca)
For the next PyCrypto release, I would like to take steps to move toward a
clearer licensing regime. I am asking as many copyright holders as I can
find if I can release PyCrypto under something clearer and more standard.
Below, I have quoted a public domain dedication that was recommended in
_Intellectual Property and Open Source: A Practical Guide to Protecting
Code_, by Van Lindberg. I have already contacted A. M. Kuchling, Robey
Pointer, and Wim Lewis, and they have all approved the following dedication
for their contributions.
I understand that you have made contributions to PyCrypto. May I, on your
behalf, dedicate to the public domain all your contributions to PyCrypto,
with the following notice?
=======================================================================
The contents of this file are dedicated to the public domain. To the
extent that dedication to the public domain is not available, everyone
is granted a worldwide, perpetual, royalty-free, non-exclusive license
to exercise all rights associated with the contents of this file for
any purpose whatsoever. No rights are reserved.
=======================================================================
Regards,
- Dwayne
--
Dwayne C. Litzenberger <dlitz@dlitz.net>
Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
From barry@python.org Mon Mar 2 11:29:39 2009
X-Maildir-Dup-Checked: Yes
Return-Path: <barry@python.org>
X-Original-To: dwon@rivest.dlitz.net
Delivered-To: dwon@rivest.dlitz.net
Received: from goedel.dlitz.net (unknown [10.159.255.6])
by rivest.dlitz.net (Postfix) with ESMTP id 6E01AC6640B
for <dwon@rivest.dlitz.net>; Mon, 2 Mar 2009 11:29:39 -0500 (EST)
Received: from localhost (localhost [127.0.0.1])
by goedel.dlitz.net (Postfix) with QMQP id 0644E1007A
for <dwon@rivest.dlitz.net>; Mon, 2 Mar 2009 10:29:39 -0600 (CST)
Received: (vmailmgr-postfix 8668 invoked by uid 1003); 2 Mar 2009 10:29:39 -0600
Delivered-To: m-dlitz-dlitz@dlitz.net
Received-SPF: none (python.org: No applicable sender policy available) receiver=goedel.dlitz.net; identity=mfrom; envelope-from="barry@python.org"; helo=mail.wooz.org; client-ip=216.15.33.230
Received: from mail.wooz.org (216-15-33-230.c3-0.slvr-ubr2.lnh-slvr.md.static.cable.rcn.com [216.15.33.230])
by goedel.dlitz.net (Postfix) with ESMTP id CCEA110073
for <dlitz@dlitz.net>; Mon, 2 Mar 2009 10:29:38 -0600 (CST)
Received: from snowdog.wooz.org (snowdog.wooz.org [192.168.11.202])
by mail.wooz.org (Postfix) with ESMTPSA id ACE30E3C9F
for <dlitz@dlitz.net>; Mon, 2 Mar 2009 11:29:35 -0500 (EST)
Message-Id: <09BF1A39-B015-4820-97A3-8642490C8254@python.org>
From: Barry Warsaw <barry@python.org>
To: Dwayne C. Litzenberger <dlitz@dlitz.net>
In-Reply-To: <20090301024509.GA13195@rivest.dlitz.net>
Content-Type: text/plain; charset=US-ASCII; format=flowed; delsp=yes
Content-Transfer-Encoding: quoted-printable
Mime-Version: 1.0 (Apple Message framework v930.3)
Subject: Re: PyCrypto license clarification
Date: Mon, 2 Mar 2009 11:29:34 -0500
References: <20090301024509.GA13195@rivest.dlitz.net>
X-Pgp-Agent: GPGMail d55 (v55, Leopard)
X-Mailer: Apple Mail (2.930.3)
Status: RO
Content-Length: 869
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Feb 28, 2009, at 9:45 PM, Dwayne C. Litzenberger wrote:
> I am the new maintainer of the Python Cryptography Toolkit, and I am =20=
> working on a new release at http://www.pycrypto.org/.
Great! I'm glad to see someone taking up the mantle of this important =20=
Python library.
> I understand that you have made contributions to PyCrypto. May I, =20
> on your behalf, dedicate to the public domain all your contributions =20=
> to PyCrypto, with the following notice?
Absolutely yes.
Cheers,
Barry
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Darwin)
iQCVAwUBSawJbnEjvBPtnXfVAQLZjgP/ecG+JdZwNvPJRfsa6rhY6+MHLDHI6agk
evkJnSJQAcVHlZnVlVeR5IXgvDUMakZjU4SOV7MqkhsKA9lIet7PaD9VSYgn3ra5
gElwI2DQDoOy5GExXMm74gqrrb1PCCbCRmpaYNo+DZohwHkeFBjbwDRA3wItOrH7
SK4w9VBJtfY=3D
=3DQduY
-----END PGP SIGNATURE-----

View File

@ -0,0 +1,277 @@
From dlitz@dlitz.net Sat Feb 28 23:24:14 2009
Date: Sat, 28 Feb 2009 23:24:14 -0500
From: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
To: Jeethu Rao <jeethurao@gmail.com>
Subject: PyCrypto license clarification
Message-ID: <20090301042414.GA15122@rivest.dlitz.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Disposition: inline
User-Agent: Mutt/1.5.16 (2007-06-11)
Status: RO
Content-Length: 2513
Hi Jeethu,
I am the new maintainer of the Python Cryptography Toolkit, and I am
working on a new release at http://www.pycrypto.org/.
People often ask me what license PyCrypto is covered by, if it's
GPL-compatible, etc. Right now, I'm not really sure what to tell them.
The text in the current LICENSE file (quoted below) is not entirely clear
on the point of whether distributing modified versions is allowed. (It
says "distribute and use", but not "modify".)
===================================================================
Distribute and use freely; there are no restrictions on further
dissemination and usage except those imposed by the laws of your
country of residence. This software is provided "as is" without
warranty of fitness for use or suitability for any purpose, express
or implied. Use at your own risk or not at all.
===================================================================
Incorporating the code into commercial products is permitted; you do
not have to make source available or contribute your changes back
(though that would be nice).
--amk (www.amk.ca)
For the next PyCrypto release, I would like to take steps to move toward a
clearer licensing regime. I am asking as many copyright holders as I can
find if I can release PyCrypto under something clearer and more standard.
Below, I have quoted a public domain dedication that was recommended in
_Intellectual Property and Open Source: A Practical Guide to Protecting
Code_, by Van Lindberg. I have already contacted A. M. Kuchling, Robey
Pointer, and Wim Lewis, and they have all approved the following text for
their contributions.
I understand that you have made contributions to PyCrypto. May I, on your
behalf, dedicate to the public domain all your contributions to PyCrypto,
with the following notice?
=======================================================================
The contents of this file are dedicated to the public domain. To the
extent that dedication to the public domain is not available, everyone
is granted a worldwide, perpetual, royalty-free, non-exclusive license
to exercise all rights associated with the contents of this file for
any purpose whatsoever. No rights are reserved.
=======================================================================
Regards,
- Dwayne
--
Dwayne C. Litzenberger <dlitz@dlitz.net>
Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
From jeethurao@gmail.com Sun Mar 8 17:28:16 2009
X-Maildir-Dup-Checked: Yes
Return-Path: <jeethurao@gmail.com>
X-Original-To: dwon@rivest.dlitz.net
Delivered-To: dwon@rivest.dlitz.net
Received: from goedel.dlitz.net (unknown [10.159.255.6])
by rivest.dlitz.net (Postfix) with ESMTP id 0CC83515D9
for <dwon@rivest.dlitz.net>; Sun, 8 Mar 2009 17:28:16 -0400 (EDT)
Received: from localhost (localhost [127.0.0.1])
by goedel.dlitz.net (Postfix) with QMQP id 4E58F450CB
for <dwon@rivest.dlitz.net>; Sun, 8 Mar 2009 15:28:15 -0600 (CST)
Received: (vmailmgr-postfix 5011 invoked by uid 1003); 8 Mar 2009 15:28:15 -0600
Delivered-To: m-dlitz-dlitz@dlitz.net
Received-SPF: pass (gmail.com ... _spf.google.com: 209.85.198.249 is authorized to use 'jeethurao@gmail.com' in 'mfrom' identity (mechanism 'ip4:209.85.128.0/17' matched)) receiver=goedel.dlitz.net; identity=mfrom; envelope-from="jeethurao@gmail.com"; helo=rv-out-0708.google.com; client-ip=209.85.198.249
Received: from rv-out-0708.google.com (unknown [209.85.198.249])
by goedel.dlitz.net (Postfix) with ESMTP id 3C097449E7
for <dlitz@dlitz.net>; Sun, 8 Mar 2009 15:28:12 -0600 (CST)
Received: by rv-out-0708.google.com with SMTP id k29so1252333rvb.26
for <dlitz@dlitz.net>; Sun, 08 Mar 2009 14:27:56 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=gmail.com; s=gamma;
h=domainkey-signature:mime-version:received:in-reply-to:references
:date:message-id:subject:from:to:content-type;
bh=YWy9U32WCU/ksRqukHwaOZyJQBUs4Yvt5mI20U6mI/g=;
b=oMjI22lIxYiJKge2zNJW3rRiUi9LqFXmey5Wp0pLItuNF+X3duyfhopTuBAKw7MwVY
B5E6VQuGVEyzBbNsctyVgq6DhQiQtouCLZymSViobmuDmKn5DtUKoxpDk0xCxQmHYaas
L9/A6D3/J66kKrNBgX9mc0GPcZTviVFYkPR0Q=
DomainKey-Signature: a=rsa-sha1; c=nofws;
d=gmail.com; s=gamma;
h=mime-version:in-reply-to:references:date:message-id:subject:from:to
:content-type;
b=Ym7CStuDEfJKay1AJyWZkZmJA1lnTcwCG6akBHAXLld8ht6PFcmlsffzZG8hJCIVJ8
vljqcT+G6cywVTBw1pyGX7ECYzr0+vhGvgdpACGrs24zikHfpSSd5GFogzXaLVvGVH8p
bqSHpfWKKtEP4gAQkiNeIq1GNtR2j8U3fnRyg=
MIME-Version: 1.0
Received: by 10.141.176.13 with SMTP id d13mr2656028rvp.231.1236547674677;
Sun, 08 Mar 2009 14:27:54 -0700 (PDT)
In-Reply-To: <20090301042414.GA15122@rivest.dlitz.net>
References: <20090301042414.GA15122@rivest.dlitz.net>
Date: Mon, 9 Mar 2009 02:57:54 +0530
Message-ID: <e3c0ddba0903081427p3a7b1058g417dd8624df68d6d@mail.gmail.com>
Subject: Re: PyCrypto license clarification
From: Jeethu Rao <jeethurao@gmail.com>
To: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
Content-Type: multipart/alternative; boundary=000e0cd209d0e5a3d40464a23054
Status: RO
Content-Length: 7668
--000e0cd209d0e5a3d40464a23054
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit
Hi Dwayne,My contribution to pycrypto are very very minimal (The sha256
module, IIRC).
I'd be fine with the public domain license for PyCrypto.
Jeethu Rao
PS: Apologies for the delay in my response.
I don't really check this email address all that often,
please direct any further correspondence to jeethu@jeethurao.com
On Sun, Mar 1, 2009 at 9:54 AM, Dwayne C. Litzenberger <dlitz@dlitz.net>wrote:
> Hi Jeethu,
>
> I am the new maintainer of the Python Cryptography Toolkit, and I am
> working on a new release at http://www.pycrypto.org/.
>
> People often ask me what license PyCrypto is covered by, if it's
> GPL-compatible, etc. Right now, I'm not really sure what to tell them. The
> text in the current LICENSE file (quoted below) is not entirely clear on the
> point of whether distributing modified versions is allowed. (It says
> "distribute and use", but not "modify".)
>
> ===================================================================
> Distribute and use freely; there are no restrictions on further
> dissemination and usage except those imposed by the laws of your
> country of residence. This software is provided "as is" without
> warranty of fitness for use or suitability for any purpose, express
> or implied. Use at your own risk or not at all.
> ===================================================================
>
> Incorporating the code into commercial products is permitted; you do
> not have to make source available or contribute your changes back
> (though that would be nice).
>
> --amk (www.amk.ca)
>
> For the next PyCrypto release, I would like to take steps to move toward a
> clearer licensing regime. I am asking as many copyright holders as I can
> find if I can release PyCrypto under something clearer and more standard.
> Below, I have quoted a public domain dedication that was recommended in
> _Intellectual Property and Open Source: A Practical Guide to Protecting
> Code_, by Van Lindberg. I have already contacted A. M. Kuchling, Robey
> Pointer, and Wim Lewis, and they have all approved the following text for
> their contributions.
>
> I understand that you have made contributions to PyCrypto. May I, on your
> behalf, dedicate to the public domain all your contributions to PyCrypto,
> with the following notice?
>
> =======================================================================
> The contents of this file are dedicated to the public domain. To the
> extent that dedication to the public domain is not available, everyone
> is granted a worldwide, perpetual, royalty-free, non-exclusive license
> to exercise all rights associated with the contents of this file for
> any purpose whatsoever. No rights are reserved.
> =======================================================================
>
> Regards,
> - Dwayne
>
> --
> Dwayne C. Litzenberger <dlitz@dlitz.net>
> Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
>
--
Jeethu Rao
--000e0cd209d0e5a3d40464a23054
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Hi Dwayne,<div>My contribution to pycrypto are very very minimal (The sha25=
6 module, IIRC).</div><div>I&#39;d be fine with the public domain license f=
or PyCrypto.</div><div><br></div><div>Jeethu Rao</div><div>PS: Apologies fo=
r the delay in my response.=A0</div>
<div>I don&#39;t really check this email address all that often,</div><div>=
please direct any further correspondence to <a href=3D"mailto:jeethu@jeethu=
rao.com">jeethu@jeethurao.com</a><br><div><br><div class=3D"gmail_quote">On=
Sun, Mar 1, 2009 at 9:54 AM, Dwayne C. Litzenberger <span dir=3D"ltr">&lt;=
<a href=3D"mailto:dlitz@dlitz.net">dlitz@dlitz.net</a>&gt;</span> wrote:<br=
>
<blockquote class=3D"gmail_quote" style=3D"margin:0 0 0 .8ex;border-left:1p=
x #ccc solid;padding-left:1ex;">Hi Jeethu,<br>
<br>
I am the new maintainer of the Python Cryptography Toolkit, and I am workin=
g on a new release at <a href=3D"http://www.pycrypto.org/" target=3D"_blank=
">http://www.pycrypto.org/</a>.<br>
<br>
People often ask me what license PyCrypto is covered by, if it&#39;s GPL-co=
mpatible, etc. =A0Right now, I&#39;m not really sure what to tell them. =A0=
The text in the current LICENSE file (quoted below) is not entirely clear o=
n the point of whether distributing modified versions is allowed. =A0(It sa=
ys &quot;distribute and use&quot;, but not &quot;modify&quot;.)<br>
<br>
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D<br>
Distribute and use freely; there are no restrictions on further<br>
dissemination and usage except those imposed by the laws of your<br>
country of residence. =A0This software is provided &quot;as is&quot; withou=
t<br>
warranty of fitness for use or suitability for any purpose, express<br>
or implied. Use at your own risk or not at all.<br>
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D<br>
<br>
Incorporating the code into commercial products is permitted; you do<br>
not have to make source available or contribute your changes back<br>
(though that would be nice).<br>
<br>
--amk =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0(<a href=3D"http://www.amk.ca" target=3D=
"_blank">www.amk.ca</a>)<br>
<br>
For the next PyCrypto release, I would like to take steps to move toward a =
clearer licensing regime. =A0I am asking as many copyright holders as I can=
find if I can release PyCrypto under something clearer and more standard. =
=A0Below, I have quoted a public domain dedication that was recommended in =
_Intellectual Property and Open Source: A Practical Guide to Protecting Cod=
e_, by Van Lindberg. =A0I have already contacted A. M. Kuchling, Robey Poin=
ter, and Wim Lewis, and they have all approved the following text for their=
contributions.<br>
<br>
I understand that you have made contributions to PyCrypto. =A0May I, on you=
r behalf, dedicate to the public domain all your contributions to PyCrypto,=
with the following notice?<br>
<br>
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D<br>
The contents of this file are dedicated to the public domain. =A0To the<br>
extent that dedication to the public domain is not available, everyone<br>
is granted a worldwide, perpetual, royalty-free, non-exclusive license<br>
to exercise all rights associated with the contents of this file for<br>
any purpose whatsoever. =A0No rights are reserved.<br>
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D<br>
<br>
Regards,<br>
- Dwayne<br><font color=3D"#888888">
<br>
-- <br>
Dwayne C. Litzenberger &lt;<a href=3D"mailto:dlitz@dlitz.net" target=3D"_bl=
ank">dlitz@dlitz.net</a>&gt;<br>
=A0 =A0 =A0Key-signing key =A0 - 19E1 1FE8 B3CF F273 ED17 =A04A24 928C EC1=
3 39C2 5CF7<br>
</font></blockquote></div><br><br clear=3D"all"><br>-- <br>Jeethu Rao<br>
</div></div>
--000e0cd209d0e5a3d40464a23054--

View File

@ -0,0 +1,298 @@
From dlitz@dlitz.net Mon May 4 22:49:14 2009
Date: Mon, 4 May 2009 22:49:14 -0400
From: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
To: Joris Bontje <joris@bontje.nl>
Subject: PyCrypto license clarification
Message-ID: <20090505024914.GA9219@rivest.dlitz.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Disposition: inline
User-Agent: Mutt/1.5.16 (2007-06-11)
Status: RO
Content-Length: 2553
Hi Joris,
I am the new maintainer of the Python Cryptography Toolkit, and I am
working on a new release at http://www.pycrypto.org/.
People often ask me what license PyCrypto is covered by, if it's
GPL-compatible, etc. Right now, I'm not really sure what to tell them.
The text in the current LICENSE file (quoted below) is not entirely clear
on the point of whether distributing modified versions is allowed. (It
says "distribute and use", but not "modify".)
===================================================================
Distribute and use freely; there are no restrictions on further
dissemination and usage except those imposed by the laws of your
country of residence. This software is provided "as is" without
warranty of fitness for use or suitability for any purpose, express
or implied. Use at your own risk or not at all.
===================================================================
Incorporating the code into commercial products is permitted; you do
not have to make source available or contribute your changes back
(though that would be nice).
--amk (www.amk.ca)
For the next PyCrypto release, I would like to take steps to move toward a
clearer licensing regime. I am asking as many copyright holders as I can
find if I can release PyCrypto under something clearer and more standard.
Below, I have quoted a public domain dedication that was recommended in
_Intellectual Property and Open Source: A Practical Guide to Protecting
Code_, by Van Lindberg. I have already contacted A. M. Kuchling, Robey
Pointer, Barry Warsaw, Wim Lewis, Jeethu Rao, and Mark Moraes, and they
have all approved the following dedication for their contributions.
I understand that you have made contributions to PyCrypto. May I, on your
behalf, dedicate to the public domain all your contributions to PyCrypto,
with the following notice?
=======================================================================
The contents of this file are dedicated to the public domain. To the
extent that dedication to the public domain is not available, everyone
is granted a worldwide, perpetual, royalty-free, non-exclusive license
to exercise all rights associated with the contents of this file for
any purpose whatsoever. No rights are reserved.
=======================================================================
Regards,
- Dwayne
--
Dwayne C. Litzenberger <dlitz@dlitz.net>
Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
From joris@bontje.nl Tue May 5 03:08:32 2009
X-Maildir-Dup-Checked: Yes
Return-Path: <joris@bontje.nl>
X-Original-To: dwon@rivest.dlitz.net
Delivered-To: dwon@rivest.dlitz.net
Received: from goedel.dlitz.net (unknown [10.159.255.6])
by rivest.dlitz.net (Postfix) with ESMTP id 7AA4B9E5078
for <dwon@rivest.dlitz.net>; Tue, 5 May 2009 03:08:32 -0400 (EDT)
Received: from localhost (localhost [127.0.0.1])
by goedel.dlitz.net (Postfix) with QMQP id 2315B40583
for <dwon@rivest.dlitz.net>; Tue, 5 May 2009 01:08:32 -0600 (CST)
Received: (vmailmgr-postfix 16890 invoked by uid 1003); 5 May 2009 01:08:32 -0600
Delivered-To: m-dlitz-dlitz@dlitz.net
Received-SPF: none (bontje.nl: No applicable sender policy available) receiver=goedel.dlitz.net; identity=mfrom; envelope-from="joris@bontje.nl"; helo=smtp6.versatel.nl; client-ip=62.58.50.97
Received: from smtp6.versatel.nl (smtp6.versatel.nl [62.58.50.97])
by goedel.dlitz.net (Postfix) with ESMTP id 2D76A4052C
for <dlitz@dlitz.net>; Tue, 5 May 2009 01:08:30 -0600 (CST)
Received: (qmail 4224 invoked by uid 0); 5 May 2009 07:08:25 -0000
Received: from qmail06.zonnet.nl (HELO dell062.admin.zonnet.nl) ([10.170.1.123])
(envelope-sender <joris@bontje.nl>)
by 10.170.1.96 (qmail-ldap-1.03) with SMTP
for < >; 5 May 2009 07:08:25 -0000
Received: by dell062.admin.zonnet.nl (Postfix, from userid 33)
id 9BE9B15759B; Tue, 5 May 2009 09:08:25 +0200 (CEST)
Received: from firewall66.interaccess.nl (firewall66.interaccess.nl
[193.173.35.66]) by www.webmail.vuurwerk.nl (Horde MIME library) with HTTP;
Tue, 05 May 2009 09:08:25 +0200
Message-ID: <20090505090825.gsq1ps7hg08wwwok@www.webmail.vuurwerk.nl>
Date: Tue, 05 May 2009 09:08:25 +0200
From: joris@bontje.nl
To: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
Subject: Re: PyCrypto license clarification
References: <20090505024914.GA9219@rivest.dlitz.net>
In-Reply-To: <20090505024914.GA9219@rivest.dlitz.net>
MIME-Version: 1.0
Content-Type: text/plain;
charset=ISO-8859-1;
format="flowed"
Content-Disposition: inline
Content-Transfer-Encoding: 7bit
User-Agent: Internet Messaging Program (IMP) H3 (4.1.3)
Status: RO
X-Status: A
Content-Length: 3488
Hi Dwayne,
Thanks for taking over the PyCrypto library and putting in the required
effort to keep this going.
I was very excited to read that it is now one of the installed
libraries for Google AppsEngine!
You have my full permission to dedicate all my contributions to
PyCrypto to the public domain with your suggested notice:
=======================================================================
The contents of this file are dedicated to the public domain. To the
extent that dedication to the public domain is not available, everyone
is granted a worldwide, perpetual, royalty-free, non-exclusive license
to exercise all rights associated with the contents of this file for
any purpose whatsoever. No rights are reserved.
=======================================================================
Regards,
Joris
Citeren "Dwayne C. Litzenberger" <dlitz@dlitz.net>:
> Hi Joris,
>
> I am the new maintainer of the Python Cryptography Toolkit, and I am
> working on a new release at http://www.pycrypto.org/.
>
> People often ask me what license PyCrypto is covered by, if it's
> GPL-compatible, etc. Right now, I'm not really sure what to tell them.
> The text in the current LICENSE file (quoted below) is not entirely clear
> on the point of whether distributing modified versions is allowed. (It
> says "distribute and use", but not "modify".)
>
> ===================================================================
> Distribute and use freely; there are no restrictions on further
> dissemination and usage except those imposed by the laws of your
> country of residence. This software is provided "as is" without
> warranty of fitness for use or suitability for any purpose, express
> or implied. Use at your own risk or not at all.
> ===================================================================
>
> Incorporating the code into commercial products is permitted; you do
> not have to make source available or contribute your changes back
> (though that would be nice).
>
> --amk (www.amk.ca)
>
> For the next PyCrypto release, I would like to take steps to move toward a
> clearer licensing regime. I am asking as many copyright holders as I can
> find if I can release PyCrypto under something clearer and more standard.
> Below, I have quoted a public domain dedication that was recommended in
> _Intellectual Property and Open Source: A Practical Guide to Protecting
> Code_, by Van Lindberg. I have already contacted A. M. Kuchling, Robey
> Pointer, Barry Warsaw, Wim Lewis, Jeethu Rao, and Mark Moraes, and they
> have all approved the following dedication for their contributions.
>
> I understand that you have made contributions to PyCrypto. May I, on your
> behalf, dedicate to the public domain all your contributions to PyCrypto,
> with the following notice?
>
> =======================================================================
> The contents of this file are dedicated to the public domain. To the
> extent that dedication to the public domain is not available, everyone
> is granted a worldwide, perpetual, royalty-free, non-exclusive license
> to exercise all rights associated with the contents of this file for
> any purpose whatsoever. No rights are reserved.
> =======================================================================
>
> Regards,
> - Dwayne
>
> --
> Dwayne C. Litzenberger <dlitz@dlitz.net>
> Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
From dlitz@dlitz.net Tue May 5 17:53:47 2009
Date: Tue, 5 May 2009 17:53:47 -0400
From: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
To: joris@bontje.nl
Subject: Re: PyCrypto license clarification
Message-ID: <20090505215347.GB9933@rivest.dlitz.net>
References: <20090505024914.GA9219@rivest.dlitz.net> <20090505090825.gsq1ps7hg08wwwok@www.webmail.vuurwerk.nl>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Disposition: inline
In-Reply-To: <20090505090825.gsq1ps7hg08wwwok@www.webmail.vuurwerk.nl>
X-Primary-Address: dlitz@dlitz.net
X-Homepage: http://www.dlitz.net/
X-OpenPGP: url=http://www.dlitz.net/go/gpgkey/;
id=19E11FE8B3CFF273ED174A24928CEC1339C25CF7 (only for key signing);
preference=unprotected
X-OpenPGP: url=http://www.dlitz.net/go/gpgkey/;
id=4B2AFD82FC7D9E3838D9179F1C11B877E7804B45 (2008);
preference=signencrypt
User-Agent: Mutt/1.5.16 (2007-06-11)
Status: RO
Content-Length: 3863
Excellent! Thank you!
On Tue, May 05, 2009 at 09:08:25AM +0200, joris@bontje.nl wrote:
> Hi Dwayne,
>
> Thanks for taking over the PyCrypto library and putting in the required
> effort to keep this going.
> I was very excited to read that it is now one of the installed libraries
> for Google AppsEngine!
>
> You have my full permission to dedicate all my contributions to PyCrypto to
> the public domain with your suggested notice:
> =======================================================================
> The contents of this file are dedicated to the public domain. To the
> extent that dedication to the public domain is not available, everyone
> is granted a worldwide, perpetual, royalty-free, non-exclusive license
> to exercise all rights associated with the contents of this file for
> any purpose whatsoever. No rights are reserved.
> =======================================================================
>
>
> Regards,
> Joris
>
> Citeren "Dwayne C. Litzenberger" <dlitz@dlitz.net>:
>
>> Hi Joris,
>>
>> I am the new maintainer of the Python Cryptography Toolkit, and I am
>> working on a new release at http://www.pycrypto.org/.
>>
>> People often ask me what license PyCrypto is covered by, if it's
>> GPL-compatible, etc. Right now, I'm not really sure what to tell them.
>> The text in the current LICENSE file (quoted below) is not entirely clear
>> on the point of whether distributing modified versions is allowed. (It
>> says "distribute and use", but not "modify".)
>>
>> ===================================================================
>> Distribute and use freely; there are no restrictions on further
>> dissemination and usage except those imposed by the laws of your
>> country of residence. This software is provided "as is" without
>> warranty of fitness for use or suitability for any purpose, express
>> or implied. Use at your own risk or not at all.
>> ===================================================================
>>
>> Incorporating the code into commercial products is permitted; you do
>> not have to make source available or contribute your changes back
>> (though that would be nice).
>>
>> --amk (www.amk.ca)
>>
>> For the next PyCrypto release, I would like to take steps to move toward a
>> clearer licensing regime. I am asking as many copyright holders as I can
>> find if I can release PyCrypto under something clearer and more standard.
>> Below, I have quoted a public domain dedication that was recommended in
>> _Intellectual Property and Open Source: A Practical Guide to Protecting
>> Code_, by Van Lindberg. I have already contacted A. M. Kuchling, Robey
>> Pointer, Barry Warsaw, Wim Lewis, Jeethu Rao, and Mark Moraes, and they
>> have all approved the following dedication for their contributions.
>>
>> I understand that you have made contributions to PyCrypto. May I, on your
>> behalf, dedicate to the public domain all your contributions to PyCrypto,
>> with the following notice?
>>
>> =======================================================================
>> The contents of this file are dedicated to the public domain. To the
>> extent that dedication to the public domain is not available, everyone
>> is granted a worldwide, perpetual, royalty-free, non-exclusive license
>> to exercise all rights associated with the contents of this file for
>> any purpose whatsoever. No rights are reserved.
>> =======================================================================
>>
>> Regards,
>> - Dwayne
>>
>> --
>> Dwayne C. Litzenberger <dlitz@dlitz.net>
>> Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
>
>
--
Dwayne C. Litzenberger <dlitz@dlitz.net>
Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
Annual key (2008) - 4B2A FD82 FC7D 9E38 38D9 179F 1C11 B877 E780 4B45

View File

@ -0,0 +1,340 @@
From dlitz@dlitz.net Sat Apr 18 09:14:20 2009
Date: Sat, 18 Apr 2009 09:14:20 -0400
From: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
To: Mark Moraes <moraes@computer.org>
Subject: PyCrypto license clarification
Message-ID: <20090418131419.GA14494@rivest.dlitz.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Disposition: inline
User-Agent: Mutt/1.5.16 (2007-06-11)
Status: RO
Content-Length: 2635
Hi Mark,
I am the new maintainer of the Python Cryptography Toolkit, and I am
working on a new release at http://www.pycrypto.org/.
People often ask me what license PyCrypto is covered by, if it's
GPL-compatible, etc. Right now, I'm not really sure what to tell them.
The text in the current LICENSE file (quoted below) is not entirely clear
on the point of whether distributing modified versions is allowed. (It
says "distribute and use", but not "modify".)
===================================================================
Distribute and use freely; there are no restrictions on further
dissemination and usage except those imposed by the laws of your
country of residence. This software is provided "as is" without
warranty of fitness for use or suitability for any purpose, express
or implied. Use at your own risk or not at all.
===================================================================
Incorporating the code into commercial products is permitted; you do
not have to make source available or contribute your changes back
(though that would be nice).
--amk (www.amk.ca)
For the next PyCrypto release, I would like to take steps to move toward a
clearer licensing regime. I am asking as many copyright holders as I can
find if I can release PyCrypto under something clearer and more standard.
Below, I have quoted a public domain dedication that was recommended in
_Intellectual Property and Open Source: A Practical Guide to Protecting
Code_, by Van Lindberg. I have already contacted A. M. Kuchling, Robey
Pointer, Wim Lewis, Jeethu Rao, and Barry Warsaw, and they have all
approved the following dedication for their contributions.
I understand that you have made contributions to PyCrypto. May I, on your
behalf, dedicate to the public domain all your contributions to PyCrypto,
with the following notice?
=======================================================================
The contents of this file are dedicated to the public domain. To the
extent that dedication to the public domain is not available, everyone
is granted a worldwide, perpetual, royalty-free, non-exclusive license
to exercise all rights associated with the contents of this file for
any purpose whatsoever. No rights are reserved.
=======================================================================
Regards,
- Dwayne
--
Dwayne C. Litzenberger <dlitz@dlitz.net>
Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
From markmoraes@yahoo.com Mon Apr 20 19:25:37 2009
X-Maildir-Dup-Checked: Yes
Return-Path: <markmoraes@yahoo.com>
X-Original-To: dwon@rivest.dlitz.net
Delivered-To: dwon@rivest.dlitz.net
Received: from goedel.dlitz.net (unknown [10.159.255.6])
by rivest.dlitz.net (Postfix) with ESMTP id 5D9AE984FDD
for <dwon@rivest.dlitz.net>; Mon, 20 Apr 2009 19:25:37 -0400 (EDT)
Received: from localhost (localhost [127.0.0.1])
by goedel.dlitz.net (Postfix) with QMQP id DE41F4025F
for <dwon@rivest.dlitz.net>; Mon, 20 Apr 2009 17:25:36 -0600 (CST)
Received: (vmailmgr-postfix 7604 invoked by uid 1003); 20 Apr 2009 17:25:36 -0600
Delivered-To: m-dlitz-dlitz@dlitz.net
Received-SPF: none (yahoo.com: No applicable sender policy available) receiver=goedel.dlitz.net; identity=mfrom; envelope-from="markmoraes@yahoo.com"; helo=web32405.mail.mud.yahoo.com; client-ip=68.142.207.198
Received: from web32405.mail.mud.yahoo.com (web32405.mail.mud.yahoo.com [68.142.207.198])
by goedel.dlitz.net (Postfix) with SMTP id B5EAF401EE
for <dlitz@dlitz.net>; Mon, 20 Apr 2009 17:25:36 -0600 (CST)
Received: (qmail 34697 invoked by uid 60001); 20 Apr 2009 23:25:33 -0000
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=yahoo.com; s=s1024; t=1240269933; bh=OvxqbYnCg7R6tUN3YmlgFURM3CuHh1JeHyXhDzkaThU=; h=Message-ID:X-YMail-OSG:Received:X-Mailer:Date:From:Reply-To:Subject:To:MIME-Version:Content-Type; b=F2h2bFzpQxyKFZ8BhenniyupGw4Zvlekb9BSk91qKU+51W/TkSGBij5YZIhkLQdkQk0qLz5f4g8dT6bOME3sEY1j10hlx0K0u2UD0yoYTINBCmsdMQRoJ7ph9bmt+p/EJhRpe+FiV6aoLV0FONWiHfGDghPT1dulWXfVTqgB2aU=
DomainKey-Signature:a=rsa-sha1; q=dns; c=nofws;
s=s1024; d=yahoo.com;
h=Message-ID:X-YMail-OSG:Received:X-Mailer:Date:From:Reply-To:Subject:To:MIME-Version:Content-Type;
b=r6RShFF5VzQLg+9tcn1xKuo4Rs4IVvXF6fdqOpQrMyRCxeFooebhuTE35grGqlomOJLwM0+mZwRb6rGkDj763caOAlo8Ect/qlADW5izXfmVQaDchTbTqmpsJBmQnTQs9iZ+InrG+3UIwtUSGfX7fhEWmI9P/HBzxf9Wp4b3jeo=;
Message-ID: <551071.34569.qm@web32405.mail.mud.yahoo.com>
X-YMail-OSG: FrK8aWMVM1mFJtLpMGbUbCLjbUQC.i.JkIAKUHSFsFn7t9PbtewAewXJ2uhZGCOlGCX6oVnG3u.CgqzAffY4vZSnfTT8wnCkzZNZ_g6k.XUc3ipo_6e.92TXl4p8MxDGAf1tpNF5nXPwcQ7aREs7jGoWWVJYVytp50clsUFSHzf7Zbpa8P1Yoe_xSzf3OAgRSh5fCrbFCC8sHPCuwrL3YhasbtHmkWffteSS.x6gEcBaxf03oz4FeDb5mpJ54g11Xonq8h_TmzX9g84Bin9g_3fJ4WSXm6g6.tohLyfXcUxoz4j036wyWpTKPrWEzIUQaN83Sv_bj_Ghxw--
Received: from [69.124.140.74] by web32405.mail.mud.yahoo.com via HTTP; Mon, 20 Apr 2009 16:25:32 PDT
X-Mailer: YahooMailClassic/5.2.15 YahooMailWebService/0.7.289.1
Date: Mon, 20 Apr 2009 16:25:32 -0700 (PDT)
From: M Moraes <markmoraes@yahoo.com>
Reply-To: moraes@computer.org
Subject: Re: PyCrypto license clarification
To: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Status: RO
X-Status: A
Content-Length: 3222
Hi Dwayne.
Sure, the new license sounds fine for all my contributions to PyCrypto, and thanks for taking it on. My apologies for not responding to your previous e-mail.
Regards,
Mark.
--- On Sat, 4/18/09, Dwayne C. Litzenberger <dlitz@dlitz.net> wrote:
> From: Dwayne C. Litzenberger <dlitz@dlitz.net>
> Subject: PyCrypto license clarification
> To: "Mark Moraes" <moraes@computer.org>
> Date: Saturday, April 18, 2009, 9:14 AM
> Hi Mark,
>
> I am the new maintainer of the Python Cryptography Toolkit,
> and I am
> working on a new release at http://www.pycrypto.org/.
>
> People often ask me what license PyCrypto is covered by, if
> it's
> GPL-compatible, etc. Right now, I'm not really sure
> what to tell them.
> The text in the current LICENSE file (quoted below) is not
> entirely clear
> on the point of whether distributing modified versions is
> allowed. (It
> says "distribute and use", but not "modify".)
>
>
> ===================================================================
> Distribute and use freely; there are
> no restrictions on further
> dissemination and usage except those
> imposed by the laws of your
> country of residence. This
> software is provided "as is" without
> warranty of fitness for use or
> suitability for any purpose, express
> or implied. Use at your own risk or
> not at all.
>
> ===================================================================
>
> Incorporating the code into commercial
> products is permitted; you do
> not have to make source available or
> contribute your changes back
> (though that would be nice).
>
> --amk
>
>
> (www.amk.ca)
>
> For the next PyCrypto release, I would like to take steps
> to move toward a
> clearer licensing regime. I am asking as many
> copyright holders as I can
> find if I can release PyCrypto under something clearer and
> more standard.
> Below, I have quoted a public domain dedication that was
> recommended in
> _Intellectual Property and Open Source: A Practical Guide
> to Protecting
> Code_, by Van Lindberg. I have already contacted A.
> M. Kuchling, Robey
> Pointer, Wim Lewis, Jeethu Rao, and Barry Warsaw, and they
> have all
> approved the following dedication for their contributions.
>
> I understand that you have made contributions to
> PyCrypto. May I, on your
> behalf, dedicate to the public domain all your
> contributions to PyCrypto,
> with the following notice?
>
>
> =======================================================================
> The contents of this file are
> dedicated to the public domain. To the
> extent that dedication to the public
> domain is not available, everyone
> is granted a worldwide, perpetual,
> royalty-free, non-exclusive license
> to exercise all rights associated with
> the contents of this file for
> any purpose whatsoever. No
> rights are reserved.
>
> =======================================================================
>
> Regards,
> - Dwayne
>
> -- Dwayne C. Litzenberger <dlitz@dlitz.net>
> Key-signing key - 19E1
> 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
>
From dlitz@dlitz.net Mon Apr 20 20:01:37 2009
Date: Mon, 20 Apr 2009 20:01:37 -0400
From: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
To: moraes@computer.org
Subject: Re: PyCrypto license clarification
Message-ID: <20090421000137.GA29012@rivest.dlitz.net>
References: <551071.34569.qm@web32405.mail.mud.yahoo.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Disposition: inline
In-Reply-To: <551071.34569.qm@web32405.mail.mud.yahoo.com>
X-Primary-Address: dlitz@dlitz.net
X-Homepage: http://www.dlitz.net/
X-OpenPGP: url=http://www.dlitz.net/go/gpgkey/;
id=19E11FE8B3CFF273ED174A24928CEC1339C25CF7 (only for key signing);
preference=unprotected
X-OpenPGP: url=http://www.dlitz.net/go/gpgkey/;
id=4B2AFD82FC7D9E3838D9179F1C11B877E7804B45 (2008);
preference=signencrypt
User-Agent: Mutt/1.5.16 (2007-06-11)
Status: RO
Content-Length: 3677
Thanks a lot, and don't worry about not responding to previous emails. I
do that too much myself. :)
On Mon, Apr 20, 2009 at 04:25:32PM -0700, M Moraes wrote:
>
>Hi Dwayne.
>
>Sure, the new license sounds fine for all my contributions to PyCrypto, and thanks for taking it on. My apologies for not responding to your previous e-mail.
>
>Regards,
>Mark.
>
>--- On Sat, 4/18/09, Dwayne C. Litzenberger <dlitz@dlitz.net> wrote:
>
>> From: Dwayne C. Litzenberger <dlitz@dlitz.net>
>> Subject: PyCrypto license clarification
>> To: "Mark Moraes" <moraes@computer.org>
>> Date: Saturday, April 18, 2009, 9:14 AM
>> Hi Mark,
>>
>> I am the new maintainer of the Python Cryptography Toolkit,
>> and I am
>> working on a new release at http://www.pycrypto.org/.
>>
>> People often ask me what license PyCrypto is covered by, if
>> it's
>> GPL-compatible, etc. Right now, I'm not really sure
>> what to tell them.
>> The text in the current LICENSE file (quoted below) is not
>> entirely clear
>> on the point of whether distributing modified versions is
>> allowed. (It
>> says "distribute and use", but not "modify".)
>>
>>
>> ===================================================================
>> Distribute and use freely; there are
>> no restrictions on further
>> dissemination and usage except those
>> imposed by the laws of your
>> country of residence. This
>> software is provided "as is" without
>> warranty of fitness for use or
>> suitability for any purpose, express
>> or implied. Use at your own risk or
>> not at all.
>>
>> ===================================================================
>>
>> Incorporating the code into commercial
>> products is permitted; you do
>> not have to make source available or
>> contribute your changes back
>> (though that would be nice).
>>
>> --amk
>>
>>
>> (www.amk.ca)
>>
>> For the next PyCrypto release, I would like to take steps
>> to move toward a
>> clearer licensing regime. I am asking as many
>> copyright holders as I can
>> find if I can release PyCrypto under something clearer and
>> more standard.
>> Below, I have quoted a public domain dedication that was
>> recommended in
>> _Intellectual Property and Open Source: A Practical Guide
>> to Protecting
>> Code_, by Van Lindberg. I have already contacted A.
>> M. Kuchling, Robey
>> Pointer, Wim Lewis, Jeethu Rao, and Barry Warsaw, and they
>> have all
>> approved the following dedication for their contributions.
>>
>> I understand that you have made contributions to
>> PyCrypto. May I, on your
>> behalf, dedicate to the public domain all your
>> contributions to PyCrypto,
>> with the following notice?
>>
>>
>> =======================================================================
>> The contents of this file are
>> dedicated to the public domain. To the
>> extent that dedication to the public
>> domain is not available, everyone
>> is granted a worldwide, perpetual,
>> royalty-free, non-exclusive license
>> to exercise all rights associated with
>> the contents of this file for
>> any purpose whatsoever. No
>> rights are reserved.
>>
>> =======================================================================
>>
>> Regards,
>> - Dwayne
>>
>> -- Dwayne C. Litzenberger <dlitz@dlitz.net>
>> Key-signing key - 19E1
>> 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
>>
>
--
Dwayne C. Litzenberger <dlitz@dlitz.net>
Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
Annual key (2008) - 4B2A FD82 FC7D 9E38 38D9 179F 1C11 B877 E780 4B45

View File

@ -0,0 +1,211 @@
From dlitz@dlitz.net Sun Aug 2 21:48:25 2009
Date: Sun, 2 Aug 2009 21:48:25 -0400
From: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
To: Paul Swartz <paulswartz@gmail.com>
Subject: PyCrypto license clarification
Message-ID: <20090803014825.GA1326@rivest.dlitz.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Disposition: inline
User-Agent: Mutt/1.5.16 (2007-06-11)
Status: RO
Content-Length: 2631
Hi Paul,
I am the new maintainer of the Python Cryptography Toolkit, and I am
working on a new release at http://www.pycrypto.org/.
People often ask me what license PyCrypto is covered by, if it's
GPL-compatible, etc. Right now, I'm not really sure what to tell them.
The text in the current LICENSE file (quoted below) is not entirely clear
on the point of whether distributing modified versions is allowed. (It
says "distribute and use", but not "modify".)
===================================================================
Distribute and use freely; there are no restrictions on further
dissemination and usage except those imposed by the laws of your
country of residence. This software is provided "as is" without
warranty of fitness for use or suitability for any purpose, express
or implied. Use at your own risk or not at all.
===================================================================
Incorporating the code into commercial products is permitted; you do
not have to make source available or contribute your changes back
(though that would be nice).
--amk (www.amk.ca)
For the next PyCrypto release, I would like to take steps to move toward a
clearer licensing regime. I am asking as many copyright holders as I can
find if I can release PyCrypto under something clearer and more standard.
Below, I have quoted a public domain dedication that was recommended in
_Intellectual Property and Open Source: A Practical Guide to Protecting
Code_, by Van Lindberg. I have already contacted A. M. Kuchling, Robey
Pointer, Barry Warsaw, Wim Lewis, Jeethu Rao, Joris Bontje, and Mark
Moraes, and they have all approved the following dedication for their
contributions.
I understand that you have made contributions to PyCrypto, under nickname
"z3p" and/or other names. May I, on your behalf, dedicate to the public
domain all your contributions to PyCrypto, with the following notice?
=======================================================================
The contents of this file are dedicated to the public domain. To the
extent that dedication to the public domain is not available, everyone
is granted a worldwide, perpetual, royalty-free, non-exclusive license
to exercise all rights associated with the contents of this file for
any purpose whatsoever. No rights are reserved.
=======================================================================
Regards,
- Dwayne
--
Dwayne C. Litzenberger <dlitz@dlitz.net>
Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
From paulswartz@gmail.com Mon Aug 3 12:14:07 2009
X-Maildir-Dup-Checked: Yes
Return-Path: <paulswartz@gmail.com>
X-Original-To: dwon@rivest.dlitz.net
Delivered-To: dwon@rivest.dlitz.net
Received: from goedel.dlitz.net (unknown [10.159.255.6])
by rivest.dlitz.net (Postfix) with ESMTP id 30B9D984FC4
for <dwon@rivest.dlitz.net>; Mon, 3 Aug 2009 12:14:07 -0400 (EDT)
Received: from localhost (localhost [127.0.0.1])
by goedel.dlitz.net (Postfix) with QMQP id AD9AE81068
for <dwon@rivest.dlitz.net>; Mon, 3 Aug 2009 10:14:06 -0600 (CST)
Received: (vmailmgr-postfix 32055 invoked by uid 1003); 3 Aug 2009 10:14:06 -0600
Delivered-To: m-dlitz-dlitz@dlitz.net
Received-SPF: pass (gmail.com ... _spf.google.com: 72.14.220.159 is authorized to use 'paulswartz@gmail.com' in 'mfrom' identity (mechanism 'ip4:72.14.192.0/18' matched)) receiver=goedel.dlitz.net; identity=mfrom; envelope-from="paulswartz@gmail.com"; helo=fg-out-1718.google.com; client-ip=72.14.220.159
Received: from fg-out-1718.google.com (fg-out-1718.google.com [72.14.220.159])
by goedel.dlitz.net (Postfix) with ESMTP id 4E63881066
for <dlitz@dlitz.net>; Mon, 3 Aug 2009 10:14:05 -0600 (CST)
Received: by fg-out-1718.google.com with SMTP id d23so1076840fga.3
for <dlitz@dlitz.net>; Mon, 03 Aug 2009 09:14:04 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=gmail.com; s=gamma;
h=domainkey-signature:mime-version:received:in-reply-to:references
:from:date:message-id:subject:to:content-type
:content-transfer-encoding;
bh=A0RHBf0TnribKS5qOHJ3WYbkZ+b0cuPeuoKAvpApWcc=;
b=gyTqkRhKlHadFKIZCBWsRbnMNVDq1PWlJbyC0EvxPskaoHr3HAR96MWQNBePu/40Ac
Vn55qlIqTdom4e9zlUEE6MwZo9kqi/Qw0L/SLib0DlQeNqo/eHYqPmuVswltaYwNAyMJ
Y9++76rPGzqYdALsfvsmwv7Q3/bEmjVTr0tQE=
DomainKey-Signature: a=rsa-sha1; c=nofws;
d=gmail.com; s=gamma;
h=mime-version:in-reply-to:references:from:date:message-id:subject:to
:content-type:content-transfer-encoding;
b=jze7KSMkUGilfVCXKXaaXMi5NAtGdMQOtVZZfRNyGSy68xOd2sxefjyyig3EfT6Nv6
Q3opUMsT96Q6zjZND55w446kTh2uBTNz4d3NwIeEWJnG3xcliRQu/mXPFp8AzPI3CefL
1ornJLM1eQ2XyuZA73jem+SJtfdHUcSD1UhgI=
MIME-Version: 1.0
Received: by 10.239.157.147 with SMTP id q19mr601802hbc.61.1249316043185; Mon,
03 Aug 2009 09:14:03 -0700 (PDT)
In-Reply-To: <20090803014825.GA1326@rivest.dlitz.net>
References: <20090803014825.GA1326@rivest.dlitz.net>
From: Paul Swartz <paulswartz@gmail.com>
Date: Mon, 3 Aug 2009 12:13:43 -0400
Message-ID: <324cfb540908030913x71d331f0kb069052f74e5ae6b@mail.gmail.com>
Subject: Re: PyCrypto license clarification
To: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Status: RO
X-Status: A
Content-Length: 1450
On Sun, Aug 2, 2009 at 9:48 PM, Dwayne C. Litzenberger<dlitz@dlitz.net> wro=
te:
> Hi Paul,
>
> I am the new maintainer of the Python Cryptography Toolkit, and I am
> working on a new release at http://www.pycrypto.org/.
That's great!
> I understand that you have made contributions to PyCrypto, under nickname
> "z3p" and/or other names. =C2=A0May I, on your behalf, dedicate to the pu=
blic
> domain all your contributions to PyCrypto, with the following notice?
>
> =C2=A0=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
> =C2=A0The contents of this file are dedicated to the public domain. =C2=
=A0To the
> =C2=A0extent that dedication to the public domain is not available, every=
one
> =C2=A0is granted a worldwide, perpetual, royalty-free, non-exclusive lice=
nse
> =C2=A0to exercise all rights associated with the contents of this file fo=
r
> =C2=A0any purpose whatsoever. =C2=A0No rights are reserved.
> =C2=A0=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
Yes, that's fine. Good luck with the new release!
-p
--=20
Paul Swartz
paulswartz at gmail dot com
http://paulswartz.net/
AIM: z3penguin
From dlitz@dlitz.net Mon Aug 3 14:35:01 2009
Date: Mon, 3 Aug 2009 14:35:01 -0400
From: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
To: Paul Swartz <paulswartz@gmail.com>
Subject: Re: PyCrypto license clarification
Message-ID: <20090803183501.GA17472@rivest.dlitz.net>
References: <20090803014825.GA1326@rivest.dlitz.net> <324cfb540908030913x71d331f0kb069052f74e5ae6b@mail.gmail.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1; format=flowed
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
In-Reply-To: <324cfb540908030913x71d331f0kb069052f74e5ae6b@mail.gmail.com>
X-Primary-Address: dlitz@dlitz.net
X-Homepage: http://www.dlitz.net/
X-OpenPGP: url=http://www.dlitz.net/go/gpgkey/;
id=19E11FE8B3CFF273ED174A24928CEC1339C25CF7 (only for key signing);
preference=unprotected
X-OpenPGP: url=http://www.dlitz.net/go/gpgkey/;
id=4B2AFD82FC7D9E3838D9179F1C11B877E7804B45 (2008);
preference=signencrypt
User-Agent: Mutt/1.5.16 (2007-06-11)
Status: RO
Content-Length: 1250
On Mon, Aug 03, 2009 at 12:13:43PM -0400, Paul Swartz wrote:
>On Sun, Aug 2, 2009 at 9:48 PM, Dwayne C. Litzenberger<dlitz@dlitz.net> wrote:
>> Hi Paul,
>>
>> I am the new maintainer of the Python Cryptography Toolkit, and I am
>> working on a new release at http://www.pycrypto.org/.
>
>That's great!
>
>> I understand that you have made contributions to PyCrypto, under nickname
>> "z3p" and/or other names.  May I, on your behalf, dedicate to the public
>> domain all your contributions to PyCrypto, with the following notice?
>>
>>  =======================================================================
>>  The contents of this file are dedicated to the public domain.  To the
>>  extent that dedication to the public domain is not available, everyone
>>  is granted a worldwide, perpetual, royalty-free, non-exclusive license
>>  to exercise all rights associated with the contents of this file for
>>  any purpose whatsoever.  No rights are reserved.
>>  =======================================================================
>
>Yes, that's fine. Good luck with the new release!
Perfect! Thanks for the quick response!
--
Dwayne C. Litzenberger <dlitz@dlitz.net>
Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7

View File

@ -0,0 +1,53 @@
Date: Mon, 16 Feb 2009 12:58:00 -0800
From: Robey Pointer <robey@lag.net>
Subject: Re: PyCrypto license clarification
To: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
Received-SPF: pass (goedel.dlitz.net: domain of robey@lag.net designates 69.61.78.186 as permitted sender)
Message-Id: <F469A078-6305-4484-BEA8-F4EC38A4154F@lag.net>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On 23 Nov 2008, at 07:42, Dwayne C. Litzenberger wrote:
> For the next PyCrypto release, I would like to take steps to move
> toward a clearer licensing regime. I am asking as many copyright
> holders as I can find if I can release PyCrypto under something
> clearer and more standard. Below, I have quoted a public domain
> dedication that was recommended in _Intellectual Property and Open
> Source: A Practical Guide to Protecting Code_, by Van Lindberg. I
> have already contacted A. M. Kuchling, and he has approved the
> following dedication for his contributions.
>
> May I, on your behalf, dedicate to the public domain all your
> contributions to PyCrypto, with the following notice?
>
>
> =
> ======================================================================
> The contents of this file are dedicated to the public domain. To
> the
> extent that dedication to the public domain is not available,
> everyone
> is granted a worldwide, perpetual, royalty-free, non-exclusive
> license
> to exercise all rights associated with the contents of this file
> for
> any purpose whatsoever. No rights are reserved.
>
> =
> ======================================================================
>
In case I haven't replied to this yet: Yes, this is fine with me.
robey
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (Darwin)
iEYEARECAAYFAkmZ01gACgkQQQDkKvyJ6cOLvQCfQmYYuVODvIlyLg0hgCI9LAbQ
SH8AoLJgaq1lIi7/ZYDc+/Cd8VO0xLbr
=Mv6g
-----END PGP SIGNATURE-----

View File

@ -0,0 +1,45 @@
Date: Sun, 23 Nov 2008 15:54:35 -0800
From: Wim Lewis <wiml@hhhh.org>
Subject: Re: PyCrypto license clarification
To: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
Cc: Wim Lewis <wiml@hhhh.org>
Message-Id: <9D5C3135-7414-47D7-9D41-0AC6C3A84D97@hhhh.org>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On November 23, 2008, you wrote:
>Hi Wim,
>
>I am the new maintainer of the Python Cryptography Toolkit, and I am
>working on a new release at http://www.pycrypto.org/.
>
>I understand that you have made contributions to PyCrypto. May I, on
>your behalf, dedicate to the public domain all your contributions to
>PyCrypto, with the following notice?
>
> =======================================================================
> The contents of this file are dedicated to the public domain. To the
> extent that dedication to the public domain is not available, everyone
> is granted a worldwide, perpetual, royalty-free, non-exclusive license
> to exercise all rights associated with the contents of this file for
> any purpose whatsoever. No rights are reserved.
> =======================================================================
Certainly! I think the only code of mine in PyCrypto is the CAST-5 / CAST-128
implementation, which already has a public-domain notice at the top of
the file. But I am happy to have that, any any other code of mine that
might have wandered in there under an unclear open sourcish license,
distributed under the public-domain dedication you quote.
Wim.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (Darwin)
iQCVAwUBSSnnAl8UnN8n93LBAQLp/gQAhr7x8Av1mstc2kxEJDWTm26PTAZxMz4B
FektbDOzkxgc5580MGGeeX/MVn8aw+1BHg0YD85gsntlDzkcQtb+BR/xAvJ5zKyA
J/Mn/I+I6ekJQ3juh8IPHLAduOXM9Rtguas/yR+Doaq0xOPKoBx+/5+t1lLJtBcZ
wrPEa9Oui9s=
=zSY9
-----END PGP SIGNATURE-----

View File

@ -0,0 +1,130 @@
From dlitz@dlitz.net Wed Aug 27 20:54:38 EDT 2008
X-Maildir-Dup-Checked: Yes
Return-Path: <dlitz@dlitz.net>
X-Original-To: dwon@rivest.dlitz.net
Delivered-To: dwon@rivest.dlitz.net
Received: from goedel.dlitz.net (unknown [10.159.255.6])
by rivest.dlitz.net (Postfix) with ESMTP id ECFDFC6641D
for <dwon@rivest.dlitz.net>; Wed, 27 Aug 2008 20:45:06 -0400 (EDT)
Received: from localhost (localhost [127.0.0.1])
by goedel.dlitz.net (Postfix) with QMQP id 99A9D100AA
for <dwon@rivest.dlitz.net>; Wed, 27 Aug 2008 18:45:05 -0600 (CST)
Received: (vmailmgr-postfix 3270 invoked by uid 1003); 27 Aug 2008 18:45:05 -0600
Delivered-To: m-dlitz-dlitz@dlitz.net
Received-SPF: pass (goedel.dlitz.net: domain of dlitz@dlitz.net designates 193.201.42.13 as permitted sender)
Received: from m14.itconsult.net (m14.itconsult.net [193.201.42.13])
by goedel.dlitz.net (Postfix) with ESMTP id 1D3B510088
for <dlitz@dlitz.net>; Wed, 27 Aug 2008 18:45:04 -0600 (CST)
Received: from stamper.itconsult.co.uk (stamper.itconsult.co.uk
[193.201.42.31]) by m14.stamper.itconsult.co.uk (GMS
15.01.3664/NT8923.00.54dca388) with SMTP id jfxsjqaa for dlitz@dlitz.net;
Thu, 28 Aug 2008 01:45:02 +0100
To: crypt@bis.doc.gov,
enc@nsa.gov,
web_site@bis.doc.gov,
pycrypto@lists.dlitz.net,
PYTHON-CRYPTO@NIC.SURFNET.NL,
dlitz@dlitz.net
Received-SPF: Pass (m14.stamper.itconsult.co.uk: domain of dlitz@dlitz.net
designates 64.5.53.201 as permitted sender) identity=mailfrom;
client-ip=64.5.53.201; receiver=m14.stamper.itconsult.co.uk;
helo=goedel.dlitz.net; mechanism=-all; envelope-from=dlitz@dlitz.net;
Received: from goedel.dlitz.net (goedel.dlitz.net [64.5.53.201]) by
m14.stamper.itconsult.co.uk (GMS 15.01.3664/NT8923.00.54dca388) with ESMTP id
taxsjqaa for post@stamper.itconsult.co.uk; Thu, 28 Aug 2008 01:42:58 +0100
Received: from rivest.dlitz.net (rivest.dlitz.net [IPv6:2002:4c0a:9133:1104::1])
by goedel.dlitz.net (Postfix) with ESMTP id 667C7100B1
for <post@stamper.itconsult.co.uk>; Wed, 27 Aug 2008 18:42:56 -0600 (CST)
Received: by rivest.dlitz.net (Postfix, from userid 1000)
id B92F8C66420; Wed, 27 Aug 2008 20:42:55 -0400 (EDT)
Received: by rivest.dlitz.net (tmda-sendmail, from uid 1000);
Wed, 27 Aug 2008 20:42:54 -0400
Date: Wed, 27 Aug 2008 20:42:54 -0400
Cc: post@stamper.itconsult.co.uk
Subject: PyCrypto TSU NOTIFICATION
Message-ID: <20080828004254.GA31214@rivest.dlitz.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Disposition: inline
X-Primary-Address: dlitz@dlitz.net
X-Homepage: http://www.dlitz.net/
X-OpenPGP: url=http://www.dlitz.net/go/gpgkey/;
id=19E11FE8B3CFF273ED174A24928CEC1339C25CF7 (only for key signing);
preference=unprotected
X-OpenPGP: url=http://www.dlitz.net/go/gpgkey/;
id=4B2AFD82FC7D9E3838D9179F1C11B877E7804B45 (2008);
preference=signencrypt
User-Agent: Mutt/1.5.16 (2007-06-11)
X-Delivery-Agent: TMDA/1.1.9 (Jura)
From: "Dwayne C. Litzenberger" <dlitz@dlitz.net>
X-DNSBL: 0
Status: O
Content-Length: 2182
Lines: 65
-----BEGIN PGP SIGNED MESSAGE-----
########################################################
#
# This is a proof of posting certificate from
# stamper.itconsult.co.uk certifying that a user
# claiming to be:-
# dlitz@dlitz.net
# requested that this message be sent to:-
# crypt@bis.doc.gov
# enc@nsa.gov
# web_site@bis.doc.gov
# pycrypto@lists.dlitz.net
# PYTHON-CRYPTO@NIC.SURFNET.NL
# dlitz@dlitz.net
#
# This certificate was issued at 00:45 (GMT)
# on Thursday 28 August 2008 with reference 0520978
#
# CAUTION: while the message may well be from the sender
# indicated in the "From:" header, the sender
# has NOT been authenticated by this service
#
# For information about the Stamper service see
# http://www.itconsult.co.uk/stamper.htm
#
########################################################
SUBMISSION TYPE: TSU
SUBMITTED BY: Dwayne C. Litzenberger
SUBMITTED FOR: Dwayne C. Litzenberger
POINT OF CONTACT: Dwayne C. Litzenberger
PHONE and/or FAX: +1-613-693-1296
MANUFACTURER: n/a
PRODUCT NAME/MODEL #: The Python Cryptography Toolkit ("PyCrypto")
ECCN: 5D002
NOTIFICATION: http://www.pycrypto.org/
Note: I am a Canadian citizen posting software to my website located in
Canada. I am not certain whether PyCrypto contains enough US-origin
cryptography to be covered by U.S. export controls, but I am submitting
this anyway.
(Sorry for spamming the lists, but I want there to be a record of this.)
- --
Dwayne C. Litzenberger <dlitz@dlitz.net>
Key-signing key - 19E1 1FE8 B3CF F273 ED17 4A24 928C EC13 39C2 5CF7
Annual key (2008) - 4B2A FD82 FC7D 9E38 38D9 179F 1C11 B877 E780 4B45
-----BEGIN PGP SIGNATURE-----
Version: 2.6.3i
Charset: noconv
Comment: Stamper Reference Id: 0520978
iQEVAgUBSLX1DYGVnbVwth+BAQEcuwf9EWnXLqSO5bPzR9K9QnTPcsKbTljKjPxr
d+q0E7eE8VtnvvijUcTAR9o27yvzOPxdFT864MQA7OTSbPK39aGAgA4fgAgvYH9t
UNjJ/kv8QLz/aq2fi/HNjyrwnqFnUl0uqwpOrQGbz8Y+SGpVh1gKqy1Ju45L+doq
sxbzCOpjgRv2zDdNR/2SnFmDWQXv8dSeonwIHpQDft8/LVA/gHiTDmteQlOhJQ6o
XYhY+HbRjsD741/GSpOt9IlN5ln0UgshFoLIndnNSAvWf4aPyh5KCN7ho+/BC0v/
W/pqSSlPkwmbhlPHoOltTkNc0qKLAHXqMGJNhO8AkrYZOyJksb0HsA==
=3oIX
-----END PGP SIGNATURE-----

View File

@ -0,0 +1,7 @@
include MANIFEST.in
include ACKS ChangeLog COPYRIGHT Doc/* TODO
graft LEGAL
recursive-include src *.h *.c
include src/config.h.in
include *.py
include configure configure.ac

View File

@ -0,0 +1,19 @@
Metadata-Version: 1.1
Name: pycrypto
Version: 2.6.1
Summary: Cryptographic modules for Python.
Home-page: http://www.pycrypto.org/
Author: Dwayne C. Litzenberger
Author-email: dlitz@dlitz.net
License: UNKNOWN
Description: UNKNOWN
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: License :: Public Domain
Classifier: Intended Audience :: Developers
Classifier: Operating System :: Unix
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Topic :: Security :: Cryptography
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 3

View File

@ -0,0 +1,103 @@
Python Cryptography Toolkit (pycrypto)
======================================
This is a collection of both secure hash functions (such as SHA256 and
RIPEMD160), and various encryption algorithms (AES, DES, RSA, ElGamal,
etc.). The package is structured to make adding new modules easy.
This section is essentially complete, and the software interface will
almost certainly not change in an incompatible way in the future; all
that remains to be done is to fix any bugs that show up. If you
encounter a bug, please report it in the Launchpad bug tracker at
https://launchpad.net/products/pycrypto/+bugs
An example usage of the SHA256 module is:
>>> from Crypto.Hash import SHA256
>>> hash = SHA256.new()
>>> hash.update('message')
>>> hash.digest()
'\xabS\n\x13\xe4Y\x14\x98+y\xf9\xb7\xe3\xfb\xa9\x94\xcf\xd1\xf3\xfb"\xf7\x1c\xea\x1a\xfb\xf0+F\x0cm\x1d'
An example usage of an encryption algorithm (AES, in this case) is:
>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key456', AES.MODE_ECB)
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'o\x1aq_{P+\xd0\x07\xce\x89\xd1=M\x989'
>>> obj2 = AES.new('This is a key456', AES.MODE_ECB)
>>> obj2.decrypt(ciphertext)
'The answer is no'
One possible application of the modules is writing secure
administration tools. Another application is in writing daemons and
servers. Clients and servers can encrypt the data being exchanged and
mutually authenticate themselves; daemons can encrypt private data for
added security. Python also provides a pleasant framework for
prototyping and experimentation with cryptographic algorithms; thanks
to its arbitrary-length integers, public key algorithms are easily
implemented.
As of PyCrypto 2.1.0, PyCrypto provides an easy-to-use random number
generator:
>>> from Crypto import Random
>>> rndfile = Random.new()
>>> rndfile.read(16)
'\xf7.\x838{\x85\xa0\xd3>#}\xc6\xc2jJU'
A stronger version of Python's standard "random" module is also
provided:
>>> from Crypto.Random import random
>>> random.choice(['dogs', 'cats', 'bears'])
'bears'
Caveat: For the random number generator to work correctly, you must
call Random.atfork() in both the parent and child processes after
using os.fork()
Installation
============
PyCrypto is written and tested using Python version 2.1 through 3.2. Python
1.5.2 is not supported.
The modules are packaged using the Distutils, so you can simply run
"python setup.py build" to build the package, and "python setup.py
install" to install it.
If the setup.py script crashes with a DistutilsPlatformError
complaining that the file /usr/lib/python2.2/config/Makefile doesn't
exist, this means that the files needed for compiling new Python
modules aren't installed on your system. Red Hat users often run into
this because they don't have the python2-devel RPM installed. The fix
is to simply install the requisite RPM. On Debian/Ubuntu, you need the
python-dev package.
To verify that everything is in order, run "python setup.py test". It
will test all the cryptographic modules, skipping ones that aren't
available. If the test script reports an error on your machine,
please report the bug using the bug tracker (URL given above). If
possible, track down the bug and include a patch that fixes it,
provided that you are able to meet the eligibility requirements at
http://www.pycrypto.org/submission-requirements/.
It is possible to test a single sub-package or a single module only, for instance
when you investigate why certain tests fail and don't want to run the whole
suite each time. Use "python setup.py test --module=name", where 'name'
is either a sub-package (Cipher, PublicKey, etc) or a module (Cipher.DES,
PublicKey.RSA, etc).
To further cut test coverage, pass also the option "--skip-slow-tests".
To install the package under the site-packages directory of
your Python installation, run "python setup.py install".
If you have any comments, corrections, or improvements for this
package, please report them to our mailing list, accessible via the
PyCrypto website:
http://www.pycrypto.org/

View File

@ -0,0 +1,30 @@
- Clean up and stabilize the Crypto.PublicKey API. The previous attempt to
unify fundamentally different algorithms, such as RSA and DSA, should be
avoided, since it simply adds confusion.
- Add algorithms:
- Camellia
- SHA512
- Diffie-Hellmen key agreement
- Authenticated Diffie-Hellmen key agreement
- RSA PKCS#1 v1.5
- RSA PKCS#1 v2 (OAEP)
- Add a *complete* DSA implementation. (The current implementation doesn't do
the necessary hashing, for example.)
- Coverage testing
- Run lint on the C code
- Separate the exported API from the internal implementation details.
- Provide drop-in support for extensions/drivers like amkCrypto/mxCrypto.
There should be some way to register these drivers in your package, e.g. by
defining a certain subdirectory to be a place where pycrypto looks for these
drivers at startup time.
- Merge Crypto.Cipher.XOR and Crypto.Util.strxor somehow
- Document our experiences with RandomPool and why it was bad.

4925
Cryptography/pycrypto-2.6.1/configure vendored Executable file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,57 @@
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.67])
AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS])
AC_CONFIG_SRCDIR([src/pycrypto_compat.h])
AC_CONFIG_HEADERS([src/config.h])
# Checks for programs.
AC_PROG_CC
# Checks for libraries.
AC_ARG_WITH([gmp], AS_HELP_STRING([--without-gmp], [Build without gmp library (default: test)]))
AS_IF([test "x$with_gmp" != "xno"], [
AC_CHECK_LIB([gmp], [__gmpz_init])
])
AC_ARG_WITH([mpir], AS_HELP_STRING([--without-mpir], [Build without mpir library (default: test)]))
AS_IF([test "x$with_mpir" != "xno"], [
AC_CHECK_LIB([mpir], [__gmpz_init])
])
AC_CHECK_DECLS([mpz_powm], [], [], [
[#if HAVE_LIBGMP
# include <gmp.h>
#elif HAVE_LIBMPIR
# include <mpir.h>
#endif
]])
AC_CHECK_DECLS([mpz_powm_sec], [], [], [
[#if HAVE_LIBGMP
# include <gmp.h>
#elif HAVE_LIBMPIR
# include <mpir.h>
#endif
]])
# Checks for header files.
AC_CHECK_HEADERS([inttypes.h limits.h stddef.h stdint.h stdlib.h string.h wchar.h])
# Checks for typedefs, structures, and compiler characteristics.
AC_C_INLINE
AC_TYPE_INT16_T
AC_TYPE_INT32_T
AC_TYPE_INT64_T
AC_TYPE_INT8_T
AC_TYPE_SIZE_T
AC_TYPE_UINT16_T
AC_TYPE_UINT32_T
AC_TYPE_UINT64_T
AC_TYPE_UINT8_T
# Checks for library functions.
AC_FUNC_MALLOC
AC_CHECK_FUNCS([memmove memset])
AC_OUTPUT

View File

@ -0,0 +1,221 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pct-speedtest.py: Speed test for the Python Cryptography Toolkit
#
# Written in 2009 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# 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 AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
import time
import os
import sys
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, ARC2, ARC4, Blowfish, CAST, DES3, DES, XOR
from Crypto.Hash import MD2, MD4, MD5, SHA256, SHA
try:
from Crypto.Hash import RIPEMD
except ImportError: # Some builds of PyCrypto don't have the RIPEMD module
RIPEMD = None
class Benchmark:
def __init__(self):
self.__random_data = None
def random_keys(self, bytes):
"""Return random keys of the specified number of bytes.
If this function has been called before with the same number of bytes,
cached keys are used instead of randomly generating new ones.
"""
return self.random_blocks(bytes, 10**5) # 100k
def random_blocks(self, bytes_per_block, blocks):
bytes = bytes_per_block * blocks
data = self.random_data(bytes)
retval = []
for i in xrange(blocks):
p = i * bytes_per_block
retval.append(data[p:p+bytes_per_block])
return retval
def random_data(self, bytes):
if self.__random_data is None:
self.__random_data = self._random_bytes(bytes)
return self.__random_data
elif bytes == len(self.__random_data):
return self.__random_data
elif bytes < len(self.__random_data):
return self.__random_data[:bytes]
else:
self.__random_data += self._random_bytes(bytes - len(self.__random_data))
return self.__random_data
def _random_bytes(self, b):
return os.urandom(b)
def announce_start(self, test_name):
sys.stdout.write("%s: " % (test_name,))
sys.stdout.flush()
def announce_result(self, value, units):
sys.stdout.write("%.2f %s\n" % (value, units))
sys.stdout.flush()
def test_pubkey_setup(self, pubkey_name, module, key_bytes):
self.announce_start("%s pubkey setup" % (pubkey_name,))
keys = self.random_keys(key_bytes)[:5]
t0 = time.time()
for k in keys:
module.generate(key_bytes*8)
t = time.time()
pubkey_setups_per_second = len(keys) / (t - t0)
self.announce_result(pubkey_setups_per_second, "Keys/sec")
def test_key_setup(self, cipher_name, module, key_bytes, mode):
self.announce_start("%s key setup" % (cipher_name,))
# Generate random keys for use with the tests
keys = self.random_keys(key_bytes)
# Perform key setups
if mode is None:
t0 = time.time()
for k in keys:
module.new(k)
t = time.time()
else:
t0 = time.time()
for k in keys:
module.new(k, module.MODE_ECB)
t = time.time()
key_setups_per_second = len(keys) / (t - t0)
self.announce_result(key_setups_per_second/1000, "kKeys/sec")
def test_encryption(self, cipher_name, module, key_bytes, mode):
self.announce_start("%s encryption" % (cipher_name,))
# Generate random keys for use with the tests
rand = self.random_data(key_bytes + module.block_size)
key, iv = rand[:key_bytes], rand[key_bytes:]
blocks = self.random_blocks(16384, 1000)
if mode is None:
cipher = module.new(key)
else:
cipher = module.new(key, mode, iv)
# Perform encryption
t0 = time.time()
for b in blocks:
cipher.encrypt(b)
t = time.time()
encryption_speed = (len(blocks) * len(blocks[0])) / (t - t0)
self.announce_result(encryption_speed / 10**6, "MBps")
def test_hash_small(self, hash_name, module):
self.announce_start("%s (%d-byte inputs)" % (hash_name, module.digest_size))
blocks = self.random_blocks(module.digest_size, 10000)
# Initialize hashes
t0 = time.time()
for b in blocks:
module.new(b).digest()
t = time.time()
hashes_per_second = len(blocks) / (t - t0)
self.announce_result(hashes_per_second / 1000, "kHashes/sec")
def test_hash_large(self, hash_name, module):
self.announce_start("%s (single large input)" % (hash_name,))
blocks = self.random_blocks(16384, 10000)
# Perform hashing
t0 = time.time()
h = module.new()
for b in blocks:
h.update(b)
h.digest()
t = time.time()
hash_speed = len(blocks) * len(blocks[0]) / (t - t0)
self.announce_result(hash_speed / 10**6, "MBps")
def run(self):
pubkey_specs = [
("RSA(1024)", RSA, 1024/8),
("RSA(2048)", RSA, 2048/8),
("RSA(4096)", RSA, 4096/8),
]
block_specs = [
("DES", DES, 8),
("DES3", DES3, 24),
("AES128", AES, 16),
("AES192", AES, 24),
("AES256", AES, 32),
("Blowfish(256)", Blowfish, 32),
("CAST(40)", CAST, 5),
("CAST(80)", CAST, 10),
("CAST(128)", CAST, 16),
]
stream_specs = [
("ARC2(128)", ARC2, 16),
("ARC4(128)", ARC4, 16),
("XOR(24)", XOR, 3),
("XOR(256)", XOR, 32),
]
hash_specs = [
("MD2", MD2),
("MD4", MD4),
("MD5", MD5),
("SHA", SHA),
("SHA256", SHA256),
]
if RIPEMD is not None:
hash_specs += [("RIPEMD", RIPEMD)]
for pubkey_name, module, key_bytes in pubkey_specs:
self.test_pubkey_setup(pubkey_name, module, key_bytes)
for cipher_name, module, key_bytes in block_specs:
self.test_key_setup(cipher_name, module, key_bytes, module.MODE_CBC)
self.test_encryption("%s-CBC" % (cipher_name,), module, key_bytes, module.MODE_CBC)
self.test_encryption("%s-CFB-8" % (cipher_name,), module, key_bytes, module.MODE_CFB)
self.test_encryption("%s-OFB" % (cipher_name,), module, key_bytes, module.MODE_OFB)
self.test_encryption("%s-ECB" % (cipher_name,), module, key_bytes, module.MODE_ECB)
self.test_encryption("%s-OPENPGP" % (cipher_name,), module, key_bytes, module.MODE_OPENPGP)
for cipher_name, module, key_bytes in stream_specs:
self.test_key_setup(cipher_name, module, key_bytes, None)
self.test_encryption(cipher_name, module, key_bytes, None)
for hash_name, module in hash_specs:
self.test_hash_small(hash_name, module)
self.test_hash_large(hash_name, module)
if __name__ == '__main__':
Benchmark().run()
# vim:set ts=4 sw=4 sts=4 expandtab:

View File

@ -0,0 +1,473 @@
#! /usr/bin/env python
#
# setup.py : Distutils setup script
#
# Part of the Python Cryptography Toolkit
#
# ===================================================================
# Portions Copyright (c) 2001, 2002, 2003 Python Software Foundation;
# All Rights Reserved
#
# This file contains code from the Python 2.2 setup.py module (the
# "Original Code"), with modifications made after it was incorporated
# into PyCrypto (the "Modifications").
#
# To the best of our knowledge, the Python Software Foundation is the
# copyright holder of the Original Code, and has licensed it under the
# Python 2.2 license. See the file LEGAL/copy/LICENSE.python-2.2 for
# details.
#
# The Modifications to this file are dedicated to the public domain.
# To the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever. No rights are
# reserved.
#
# 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 AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
__revision__ = "$Id$"
from distutils import core
from distutils.ccompiler import new_compiler
from distutils.core import Extension, Command
from distutils.command.build import build
from distutils.command.build_ext import build_ext
import os, sys, re
import struct
if sys.version[0:1] == '1':
raise RuntimeError ("The Python Cryptography Toolkit requires "
"Python 2.x or 3.x to build.")
if sys.platform == 'win32':
HTONS_LIBS = ['ws2_32']
plat_ext = [
Extension("Crypto.Random.OSRNG.winrandom",
libraries = HTONS_LIBS + ['advapi32'],
include_dirs=['src/'],
sources=["src/winrand.c"])
]
else:
HTONS_LIBS = []
plat_ext = []
# For test development: Set this to 1 to build with gcov support.
# Use "gcov -p -o build/temp.*/src build/temp.*/src/*.gcda" to build the
# .gcov files
USE_GCOV = 0
try:
# Python 3
from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
# Python 2
from distutils.command.build_py import build_py
# List of pure Python modules that will be excluded from the binary packages.
# The list consists of (package, module_name) tuples
if sys.version_info[0] == 2:
EXCLUDE_PY = []
else:
EXCLUDE_PY = [
# We don't want Py3k to choke on the 2.x compat code
('Crypto.Util', 'py21compat'),
]
if sys.platform != "win32": # Avoid nt.py, as 2to3 can't fix it w/o winrandom
EXCLUDE_PY += [('Crypto.Random.OSRNG','nt')]
# Work around the print / print() issue with Python 2.x and 3.x. We only need
# to print at one point of the code, which makes this easy
def PrintErr(*args, **kwd):
fout = kwd.get("file", sys.stderr)
w = fout.write
if args:
w(str(args[0]))
sep = kwd.get("sep", " ")
for a in args[1:]:
w(sep)
w(str(a))
w(kwd.get("end", "\n"))
def endianness_macro():
s = struct.pack("@I", 0x33221100)
if s == "\x00\x11\x22\x33".encode(): # little endian
return ('PCT_LITTLE_ENDIAN', 1)
elif s == "\x33\x22\x11\x00".encode(): # big endian
return ('PCT_BIG_ENDIAN', 1)
raise AssertionError("Machine is neither little-endian nor big-endian")
class PCTBuildExt (build_ext):
def build_extensions(self):
# Detect which modules should be compiled
self.detect_modules()
# Tweak compiler options
if self.compiler.compiler_type in ('unix', 'cygwin', 'mingw32'):
# Tell GCC to compile using the C99 standard.
self.__add_compiler_option("-std=c99")
# ... but don't tell that to the aCC compiler on HP-UX
if self.compiler.compiler_so[0] == 'cc' and sys.platform.startswith('hp-ux'):
self.__remove_compiler_option("-std=c99")
# Make assert() statements always work
self.__remove_compiler_option("-DNDEBUG")
# Choose our own optimization options
for opt in ["-O", "-O0", "-O1", "-O2", "-O3", "-Os"]:
self.__remove_compiler_option(opt)
if self.debug:
# Basic optimization is still needed when debugging to compile
# the libtomcrypt code.
self.__add_compiler_option("-O")
else:
# Speed up execution by tweaking compiler options. This
# especially helps the DES modules.
self.__add_compiler_option("-O3")
self.__add_compiler_option("-fomit-frame-pointer")
# Don't include debug symbols unless debugging
self.__remove_compiler_option("-g")
# Don't include profiling information (incompatible with
# -fomit-frame-pointer)
self.__remove_compiler_option("-pg")
if USE_GCOV:
self.__add_compiler_option("-fprofile-arcs")
self.__add_compiler_option("-ftest-coverage")
self.compiler.libraries += ['gcov']
# Call the superclass's build_extensions method
build_ext.build_extensions(self)
def detect_modules (self):
# Read the config.h file (usually generated by autoconf)
if self.compiler.compiler_type == 'msvc':
# Add special include directory for MSVC (because MSVC is special)
self.compiler.include_dirs.insert(0, "src/inc-msvc/")
ac = self.__read_autoconf("src/inc-msvc/config.h")
else:
ac = self.__read_autoconf("src/config.h")
# Detect libgmp or libmpir and don't build _fastmath if both are missing.
if ac.get("HAVE_LIBGMP"):
# Default; no changes needed
pass
elif ac.get("HAVE_LIBMPIR"):
# Change library to libmpir if libgmp is missing
self.__change_extension_lib(["Crypto.PublicKey._fastmath"],
['mpir'])
# And if this is MSVC, we need to add a linker option
# to make a static libmpir link well into a dynamic _fastmath
if self.compiler.compiler_type == 'msvc':
self.__add_extension_link_option(["Crypto.PublicKey._fastmath"],
["/NODEFAULTLIB:LIBCMT"])
else:
# No MP library; use _slowmath.
PrintErr ("warning: GMP or MPIR library not found; Not building "+
"Crypto.PublicKey._fastmath.")
self.__remove_extensions(["Crypto.PublicKey._fastmath"])
def __add_extension_link_option(self, names, options):
"""Add linker options for the specified extension(s)"""
i = 0
while i < len(self.extensions):
if self.extensions[i].name in names:
self.extensions[i].extra_link_args = options
i += 1
def __change_extension_lib(self, names, libs):
"""Change the libraries to be used for the specified extension(s)"""
i = 0
while i < len(self.extensions):
if self.extensions[i].name in names:
self.extensions[i].libraries = libs
i += 1
def __remove_extensions(self, names):
"""Remove the specified extension(s) from the list of extensions
to build"""
i = 0
while i < len(self.extensions):
if self.extensions[i].name in names:
del self.extensions[i]
continue
i += 1
def __remove_compiler_option(self, option):
"""Remove the specified compiler option.
Return true if the option was found. Return false otherwise.
"""
found = 0
for attrname in ('compiler', 'compiler_so'):
compiler = getattr(self.compiler, attrname, None)
if compiler is not None:
while option in compiler:
compiler.remove(option)
found += 1
return found
def __add_compiler_option(self, option):
for attrname in ('compiler', 'compiler_so'):
compiler = getattr(self.compiler, attrname, None)
if compiler is not None:
compiler.append(option)
def __read_autoconf(self, filename):
rx_define = re.compile(r"""^#define (\S+) (?:(\d+)|(".*"))$""")
result = {}
f = open(filename, "r")
try:
config_lines = f.read().replace("\r\n", "\n").split("\n")
for line in config_lines:
m = rx_define.search(line)
if not m: continue
sym = m.group(1)
n = m.group(2)
s = m.group(3)
if n:
result[sym] = int(n)
elif s:
result[sym] = eval(s) # XXX - hack to unescape C-style string
else:
continue
finally:
f.close()
return result
def run(self):
for cmd_name in self.get_sub_commands():
self.run_command(cmd_name)
build_ext.run(self)
def has_configure(self):
compiler = new_compiler(compiler=self.compiler)
return compiler.compiler_type != 'msvc'
sub_commands = [ ('build_configure', has_configure) ] + build_ext.sub_commands
class PCTBuildConfigure(Command):
description = "Generate config.h using ./configure (autoconf)"
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
if not os.path.exists("config.status"):
if os.system("chmod 0755 configure") != 0:
raise RuntimeError("chmod error")
cmd = "sh configure" # we use "sh" here so that it'll work on mingw32 with standard python.org binaries
if self.verbose < 1:
cmd += " -q"
if os.system(cmd) != 0:
raise RuntimeError("autoconf error")
class PCTBuildPy(build_py):
def find_package_modules(self, package, package_dir, *args, **kwargs):
modules = build_py.find_package_modules(self, package, package_dir,
*args, **kwargs)
# Exclude certain modules
retval = []
for item in modules:
pkg, module = item[:2]
if (pkg, module) in EXCLUDE_PY:
continue
retval.append(item)
return retval
class TestCommand(Command):
description = "Run self-test"
# Long option name, short option name, description
user_options = [
('skip-slow-tests', None,
'Skip slow tests'),
('module=', 'm', 'Test a single module (e.g. Cipher, PublicKey)')
]
def initialize_options(self):
self.build_dir = None
self.skip_slow_tests = None
self.module = None
def finalize_options(self):
self.set_undefined_options('install', ('build_lib', 'build_dir'))
self.config = {'slow_tests': not self.skip_slow_tests}
def run(self):
# Run SelfTest
self.announce("running self-tests")
old_path = sys.path[:]
try:
sys.path.insert(0, self.build_dir)
from Crypto import SelfTest
moduleObj = None
if self.module:
if self.module.count('.')==0:
# Test a whole a sub-package
full_module = "Crypto.SelfTest." + self.module
module_name = self.module
else:
# Test only a module
# Assume only one dot is present
comps = self.module.split('.')
module_name = "test_" + comps[1]
full_module = "Crypto.SelfTest." + comps[0] + "." + module_name
# Import sub-package or module
moduleObj = __import__( full_module, globals(), locals(), module_name )
SelfTest.run(module=moduleObj, verbosity=self.verbose, stream=sys.stdout, config=self.config)
finally:
# Restore sys.path
sys.path[:] = old_path
# Run slower self-tests
self.announce("running extended self-tests")
kw = {'name':"pycrypto",
'version':"2.6.1", # See also: lib/Crypto/__init__.py
'description':"Cryptographic modules for Python.",
'author':"Dwayne C. Litzenberger",
'author_email':"dlitz@dlitz.net",
'url':"http://www.pycrypto.org/",
'cmdclass' : {'build_configure': PCTBuildConfigure, 'build_ext': PCTBuildExt, 'build_py': PCTBuildPy, 'test': TestCommand },
'packages' : ["Crypto", "Crypto.Hash", "Crypto.Cipher", "Crypto.Util",
"Crypto.Random",
"Crypto.Random.Fortuna",
"Crypto.Random.OSRNG",
"Crypto.SelfTest",
"Crypto.SelfTest.Cipher",
"Crypto.SelfTest.Hash",
"Crypto.SelfTest.Protocol",
"Crypto.SelfTest.PublicKey",
"Crypto.SelfTest.Random",
"Crypto.SelfTest.Random.Fortuna",
"Crypto.SelfTest.Random.OSRNG",
"Crypto.SelfTest.Util",
"Crypto.SelfTest.Signature",
"Crypto.Protocol",
"Crypto.PublicKey",
"Crypto.Signature"],
'package_dir' : { "Crypto": "lib/Crypto" },
'ext_modules': plat_ext + [
# _fastmath (uses GNU mp library)
Extension("Crypto.PublicKey._fastmath",
include_dirs=['src/','/usr/include/'],
libraries=['gmp'],
sources=["src/_fastmath.c"]),
# Hash functions
Extension("Crypto.Hash._MD2",
include_dirs=['src/'],
sources=["src/MD2.c"]),
Extension("Crypto.Hash._MD4",
include_dirs=['src/'],
sources=["src/MD4.c"]),
Extension("Crypto.Hash._SHA256",
include_dirs=['src/'],
sources=["src/SHA256.c"]),
Extension("Crypto.Hash._SHA224",
include_dirs=['src/'],
sources=["src/SHA224.c"]),
Extension("Crypto.Hash._SHA384",
include_dirs=['src/'],
sources=["src/SHA384.c"]),
Extension("Crypto.Hash._SHA512",
include_dirs=['src/'],
sources=["src/SHA512.c"]),
Extension("Crypto.Hash._RIPEMD160",
include_dirs=['src/'],
sources=["src/RIPEMD160.c"],
define_macros=[endianness_macro()]),
# Block encryption algorithms
Extension("Crypto.Cipher._AES",
include_dirs=['src/'],
sources=["src/AES.c"]),
Extension("Crypto.Cipher._ARC2",
include_dirs=['src/'],
sources=["src/ARC2.c"]),
Extension("Crypto.Cipher._Blowfish",
include_dirs=['src/'],
sources=["src/Blowfish.c"]),
Extension("Crypto.Cipher._CAST",
include_dirs=['src/'],
sources=["src/CAST.c"]),
Extension("Crypto.Cipher._DES",
include_dirs=['src/', 'src/libtom/'],
sources=["src/DES.c"]),
Extension("Crypto.Cipher._DES3",
include_dirs=['src/', 'src/libtom/'],
sources=["src/DES3.c"]),
# Stream ciphers
Extension("Crypto.Cipher._ARC4",
include_dirs=['src/'],
sources=["src/ARC4.c"]),
Extension("Crypto.Cipher._XOR",
include_dirs=['src/'],
sources=["src/XOR.c"]),
# Utility modules
Extension("Crypto.Util.strxor",
include_dirs=['src/'],
sources=['src/strxor.c']),
# Counter modules
Extension("Crypto.Util._counter",
include_dirs=['src/'],
sources=['src/_counter.c']),
]
}
# If we're running Python 2.3, add extra information
if hasattr(core, 'setup_keywords'):
if 'classifiers' in core.setup_keywords:
kw['classifiers'] = [
'Development Status :: 5 - Production/Stable',
'License :: Public Domain',
'Intended Audience :: Developers',
'Operating System :: Unix',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Security :: Cryptography',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
core.setup(**kw)
def touch(path):
import os, time
now = time.time()
try:
# assume it's there
os.utime(path, (now, now))
except os.error:
PrintErr("Failed to update timestamp of "+path)
# PY3K: Workaround for winrandom.pyd not existing during the first pass.
# It needs to be there for 2to3 to fix the import in nt.py
if (sys.platform == 'win32' and sys.version_info[0] == 3 and
'build' in sys.argv[1:]):
PrintErr("\nSecond pass to allow 2to3 to fix nt.py. No cause for alarm.\n")
touch("./lib/Crypto/Random/OSRNG/nt.py")
core.setup(**kw)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,220 @@
/*
* rc2.c : Source code for the RC2 block cipher
*
* Part of the Python Cryptography Toolkit
*
* ===================================================================
* This file appears to contain code from the ARC2 implementation
* "rc2.c" implementation (the "Original Code"), with modifications made
* after it was incorporated into PyCrypto (the "Modifications").
*
* To the best of our knowledge, the Original Code was placed into the
* public domain by its (anonymous) author:
*
* **********************************************************************
* * To commemorate the 1996 RSA Data Security Conference, the following *
* * code is released into the public domain by its author. Prost! *
* * *
* * This cipher uses 16-bit words and little-endian byte ordering. *
* * I wonder which processor it was optimized for? *
* * *
* * Thanks to CodeView, SoftIce, and D86 for helping bring this code to *
* * the public. *
* **********************************************************************
*
* The Modifications to this file are dedicated to the public domain.
* To the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever. No rights are
* reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#include <string.h>
#include "Python.h"
#define MODULE_NAME _ARC2
#define BLOCK_SIZE 8
#define KEY_SIZE 0
#define PCT_ARC2_MODULE /* Defined to get ARC2's additional keyword arguments */
typedef unsigned int U32;
typedef unsigned short U16;
typedef unsigned char U8;
typedef struct
{
U16 xkey[64];
int effective_keylen;
} block_state;
static void
block_encrypt(block_state *self, U8 *in, U8 *out)
{
U16 x76, x54, x32, x10;
int i;
x76 = (in[7] << 8) + in[6];
x54 = (in[5] << 8) + in[4];
x32 = (in[3] << 8) + in[2];
x10 = (in[1] << 8) + in[0];
for (i = 0; i < 16; i++)
{
x10 += (x32 & ~x76) + (x54 & x76) + self->xkey[4*i+0];
x10 = (x10 << 1) + (x10 >> 15 & 1);
x32 += (x54 & ~x10) + (x76 & x10) + self->xkey[4*i+1];
x32 = (x32 << 2) + (x32 >> 14 & 3);
x54 += (x76 & ~x32) + (x10 & x32) + self->xkey[4*i+2];
x54 = (x54 << 3) + (x54 >> 13 & 7);
x76 += (x10 & ~x54) + (x32 & x54) + self->xkey[4*i+3];
x76 = (x76 << 5) + (x76 >> 11 & 31);
if (i == 4 || i == 10) {
x10 += self->xkey[x76 & 63];
x32 += self->xkey[x10 & 63];
x54 += self->xkey[x32 & 63];
x76 += self->xkey[x54 & 63];
}
}
out[0] = (U8)x10;
out[1] = (U8)(x10 >> 8);
out[2] = (U8)x32;
out[3] = (U8)(x32 >> 8);
out[4] = (U8)x54;
out[5] = (U8)(x54 >> 8);
out[6] = (U8)x76;
out[7] = (U8)(x76 >> 8);
}
static void
block_decrypt(block_state *self, U8 *in, U8 *out)
{
U16 x76, x54, x32, x10;
int i;
x76 = (in[7] << 8) + in[6];
x54 = (in[5] << 8) + in[4];
x32 = (in[3] << 8) + in[2];
x10 = (in[1] << 8) + in[0];
i = 15;
do {
x76 &= 65535;
x76 = (x76 << 11) + (x76 >> 5);
x76 -= (x10 & ~x54) + (x32 & x54) + self->xkey[4*i+3];
x54 &= 65535;
x54 = (x54 << 13) + (x54 >> 3);
x54 -= (x76 & ~x32) + (x10 & x32) + self->xkey[4*i+2];
x32 &= 65535;
x32 = (x32 << 14) + (x32 >> 2);
x32 -= (x54 & ~x10) + (x76 & x10) + self->xkey[4*i+1];
x10 &= 65535;
x10 = (x10 << 15) + (x10 >> 1);
x10 -= (x32 & ~x76) + (x54 & x76) + self->xkey[4*i+0];
if (i == 5 || i == 11) {
x76 -= self->xkey[x54 & 63];
x54 -= self->xkey[x32 & 63];
x32 -= self->xkey[x10 & 63];
x10 -= self->xkey[x76 & 63];
}
} while (i--);
out[0] = (U8)x10;
out[1] = (U8)(x10 >> 8);
out[2] = (U8)x32;
out[3] = (U8)(x32 >> 8);
out[4] = (U8)x54;
out[5] = (U8)(x54 >> 8);
out[6] = (U8)x76;
out[7] = (U8)(x76 >> 8);
}
static void
block_init(block_state *self, U8 *key, int keylength)
{
U8 x;
U16 i;
/* 256-entry permutation table, probably derived somehow from pi */
static const U8 permute[256] = {
217,120,249,196, 25,221,181,237, 40,233,253,121, 74,160,216,157,
198,126, 55,131, 43,118, 83,142, 98, 76,100,136, 68,139,251,162,
23,154, 89,245,135,179, 79, 19, 97, 69,109,141, 9,129,125, 50,
189,143, 64,235,134,183,123, 11,240,149, 33, 34, 92,107, 78,130,
84,214,101,147,206, 96,178, 28,115, 86,192, 20,167,140,241,220,
18,117,202, 31, 59,190,228,209, 66, 61,212, 48,163, 60,182, 38,
111,191, 14,218, 70,105, 7, 87, 39,242, 29,155,188,148, 67, 3,
248, 17,199,246,144,239, 62,231, 6,195,213, 47,200,102, 30,215,
8,232,234,222,128, 82,238,247,132,170,114,172, 53, 77,106, 42,
150, 26,210,113, 90, 21, 73,116, 75,159,208, 94, 4, 24,164,236,
194,224, 65,110, 15, 81,203,204, 36,145,175, 80,161,244,112, 57,
153,124, 58,133, 35,184,180,122,252, 2, 54, 91, 37, 85,151, 49,
45, 93,250,152,227,138,146,174, 5,223, 41, 16,103,108,186,201,
211, 0,230,207,225,158,168, 44, 99, 22, 1, 63, 88,226,137,169,
13, 56, 52, 27,171, 51,255,176,187, 72, 12, 95,185,177,205, 46,
197,243,219, 71,229,165,156,119, 10,166, 32,104,254,127,193,173
};
if ((U32)keylength > sizeof(self->xkey)) {
PyErr_SetString(PyExc_ValueError,
"ARC2 key length must be less than 128 bytes");
return;
}
memcpy(self->xkey, key, keylength);
/* Phase 1: Expand input key to 128 bytes */
if (keylength < 128) {
i = 0;
x = ((U8 *)self->xkey)[keylength-1];
do {
x = permute[(x + ((U8 *)self->xkey)[i++]) & 255];
((U8 *)self->xkey)[keylength++] = x;
} while (keylength < 128);
}
/* Phase 2 - reduce effective key size to "effective_keylen" */
keylength = (self->effective_keylen+7) >> 3;
i = 128-keylength;
x = permute[((U8 *)self->xkey)[i] & (255 >>
(7 &
((self->effective_keylen %8 ) ? 8-(self->effective_keylen%8): 0))
)];
((U8 *)self->xkey)[i] = x;
while (i--) {
x = permute[ x ^ ((U8 *)self->xkey)[i+keylength] ];
((U8 *)self->xkey)[i] = x;
}
/* Phase 3 - copy to self->xkey in little-endian order */
i = 63;
do {
self->xkey[i] = ((U8 *)self->xkey)[2*i] +
(((U8 *)self->xkey)[2*i+1] << 8);
} while (i--);
}
#include "block_template.c"

View File

@ -0,0 +1,88 @@
/*
* arc4.c : Implementation for the Alleged-RC4 stream cipher
*
* Part of the Python Cryptography Toolkit
*
* Originally written by: A.M. Kuchling
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#define MODULE_NAME _ARC4
#define BLOCK_SIZE 1
#define KEY_SIZE 0
typedef struct
{
unsigned char state[256];
unsigned char x,y;
} stream_state;
/* Encryption and decryption are symmetric */
#define stream_decrypt stream_encrypt
static void stream_encrypt(stream_state *self, unsigned char *block,
int len)
{
register int i, x=self->x, y=self->y;
for (i=0; i<len; i++)
{
x = (x + 1) % 256;
y = (y + self->state[x]) % 256;
{
register int t; /* Exchange state[x] and state[y] */
t = self->state[x];
self->state[x] = self->state[y];
self->state[y] = t;
}
{
register int xorIndex; /* XOR the data with the stream data */
xorIndex=(self->state[x]+self->state[y]) % 256;
block[i] ^= self->state[xorIndex];
}
}
self->x=x;
self->y=y;
}
static void stream_init(stream_state *self, unsigned char *key, int keylen)
{
register int i, index1, index2;
for(i=0; i<256; i++) self->state[i]=i;
self->x=0; self->y=0;
index1=0; index2=0;
for(i=0; i<256; i++)
{
register int t;
index2 = ( key[index1] + self->state[i] + index2) % 256;
t = self->state[i];
self->state[i] = self->state[index2];
self->state[index2] = t;
index1 = (index1 + 1) % keylen;
}
}
#include "stream_template.c"

View File

@ -0,0 +1,258 @@
/*
*
* Blowfish-tables.h : Initial-value tables for Blowfish
*
* Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
*
* =======================================================================
* The contents of this file are dedicated to the public domain. To the extent
* that dedication to the public domain is not available, everyone is granted a
* worldwide, perpetual, royalty-free, non-exclusive license to exercise all
* rights associated with the contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* =======================================================================
*
* Country of origin: Canada
*/
#ifndef BLOWFISH_TABLES_H
#define BLOWFISH_TABLES_H
/* The hexadecimal digits of pi, less 3. */
static const uint32_t initial_P[18] = {
0x243f6a88u, 0x85a308d3u, 0x13198a2eu, 0x03707344u, 0xa4093822u,
0x299f31d0u, 0x082efa98u, 0xec4e6c89u, 0x452821e6u, 0x38d01377u,
0xbe5466cfu, 0x34e90c6cu, 0xc0ac29b7u, 0xc97c50ddu, 0x3f84d5b5u,
0xb5470917u, 0x9216d5d9u, 0x8979fb1bu
};
static const uint32_t initial_S1[256] = {
0xd1310ba6u, 0x98dfb5acu, 0x2ffd72dbu, 0xd01adfb7u, 0xb8e1afedu,
0x6a267e96u, 0xba7c9045u, 0xf12c7f99u, 0x24a19947u, 0xb3916cf7u,
0x0801f2e2u, 0x858efc16u, 0x636920d8u, 0x71574e69u, 0xa458fea3u,
0xf4933d7eu, 0x0d95748fu, 0x728eb658u, 0x718bcd58u, 0x82154aeeu,
0x7b54a41du, 0xc25a59b5u, 0x9c30d539u, 0x2af26013u, 0xc5d1b023u,
0x286085f0u, 0xca417918u, 0xb8db38efu, 0x8e79dcb0u, 0x603a180eu,
0x6c9e0e8bu, 0xb01e8a3eu, 0xd71577c1u, 0xbd314b27u, 0x78af2fdau,
0x55605c60u, 0xe65525f3u, 0xaa55ab94u, 0x57489862u, 0x63e81440u,
0x55ca396au, 0x2aab10b6u, 0xb4cc5c34u, 0x1141e8ceu, 0xa15486afu,
0x7c72e993u, 0xb3ee1411u, 0x636fbc2au, 0x2ba9c55du, 0x741831f6u,
0xce5c3e16u, 0x9b87931eu, 0xafd6ba33u, 0x6c24cf5cu, 0x7a325381u,
0x28958677u, 0x3b8f4898u, 0x6b4bb9afu, 0xc4bfe81bu, 0x66282193u,
0x61d809ccu, 0xfb21a991u, 0x487cac60u, 0x5dec8032u, 0xef845d5du,
0xe98575b1u, 0xdc262302u, 0xeb651b88u, 0x23893e81u, 0xd396acc5u,
0x0f6d6ff3u, 0x83f44239u, 0x2e0b4482u, 0xa4842004u, 0x69c8f04au,
0x9e1f9b5eu, 0x21c66842u, 0xf6e96c9au, 0x670c9c61u, 0xabd388f0u,
0x6a51a0d2u, 0xd8542f68u, 0x960fa728u, 0xab5133a3u, 0x6eef0b6cu,
0x137a3be4u, 0xba3bf050u, 0x7efb2a98u, 0xa1f1651du, 0x39af0176u,
0x66ca593eu, 0x82430e88u, 0x8cee8619u, 0x456f9fb4u, 0x7d84a5c3u,
0x3b8b5ebeu, 0xe06f75d8u, 0x85c12073u, 0x401a449fu, 0x56c16aa6u,
0x4ed3aa62u, 0x363f7706u, 0x1bfedf72u, 0x429b023du, 0x37d0d724u,
0xd00a1248u, 0xdb0fead3u, 0x49f1c09bu, 0x075372c9u, 0x80991b7bu,
0x25d479d8u, 0xf6e8def7u, 0xe3fe501au, 0xb6794c3bu, 0x976ce0bdu,
0x04c006bau, 0xc1a94fb6u, 0x409f60c4u, 0x5e5c9ec2u, 0x196a2463u,
0x68fb6fafu, 0x3e6c53b5u, 0x1339b2ebu, 0x3b52ec6fu, 0x6dfc511fu,
0x9b30952cu, 0xcc814544u, 0xaf5ebd09u, 0xbee3d004u, 0xde334afdu,
0x660f2807u, 0x192e4bb3u, 0xc0cba857u, 0x45c8740fu, 0xd20b5f39u,
0xb9d3fbdbu, 0x5579c0bdu, 0x1a60320au, 0xd6a100c6u, 0x402c7279u,
0x679f25feu, 0xfb1fa3ccu, 0x8ea5e9f8u, 0xdb3222f8u, 0x3c7516dfu,
0xfd616b15u, 0x2f501ec8u, 0xad0552abu, 0x323db5fau, 0xfd238760u,
0x53317b48u, 0x3e00df82u, 0x9e5c57bbu, 0xca6f8ca0u, 0x1a87562eu,
0xdf1769dbu, 0xd542a8f6u, 0x287effc3u, 0xac6732c6u, 0x8c4f5573u,
0x695b27b0u, 0xbbca58c8u, 0xe1ffa35du, 0xb8f011a0u, 0x10fa3d98u,
0xfd2183b8u, 0x4afcb56cu, 0x2dd1d35bu, 0x9a53e479u, 0xb6f84565u,
0xd28e49bcu, 0x4bfb9790u, 0xe1ddf2dau, 0xa4cb7e33u, 0x62fb1341u,
0xcee4c6e8u, 0xef20cadau, 0x36774c01u, 0xd07e9efeu, 0x2bf11fb4u,
0x95dbda4du, 0xae909198u, 0xeaad8e71u, 0x6b93d5a0u, 0xd08ed1d0u,
0xafc725e0u, 0x8e3c5b2fu, 0x8e7594b7u, 0x8ff6e2fbu, 0xf2122b64u,
0x8888b812u, 0x900df01cu, 0x4fad5ea0u, 0x688fc31cu, 0xd1cff191u,
0xb3a8c1adu, 0x2f2f2218u, 0xbe0e1777u, 0xea752dfeu, 0x8b021fa1u,
0xe5a0cc0fu, 0xb56f74e8u, 0x18acf3d6u, 0xce89e299u, 0xb4a84fe0u,
0xfd13e0b7u, 0x7cc43b81u, 0xd2ada8d9u, 0x165fa266u, 0x80957705u,
0x93cc7314u, 0x211a1477u, 0xe6ad2065u, 0x77b5fa86u, 0xc75442f5u,
0xfb9d35cfu, 0xebcdaf0cu, 0x7b3e89a0u, 0xd6411bd3u, 0xae1e7e49u,
0x00250e2du, 0x2071b35eu, 0x226800bbu, 0x57b8e0afu, 0x2464369bu,
0xf009b91eu, 0x5563911du, 0x59dfa6aau, 0x78c14389u, 0xd95a537fu,
0x207d5ba2u, 0x02e5b9c5u, 0x83260376u, 0x6295cfa9u, 0x11c81968u,
0x4e734a41u, 0xb3472dcau, 0x7b14a94au, 0x1b510052u, 0x9a532915u,
0xd60f573fu, 0xbc9bc6e4u, 0x2b60a476u, 0x81e67400u, 0x08ba6fb5u,
0x571be91fu, 0xf296ec6bu, 0x2a0dd915u, 0xb6636521u, 0xe7b9f9b6u,
0xff34052eu, 0xc5855664u, 0x53b02d5du, 0xa99f8fa1u, 0x08ba4799u,
0x6e85076au
};
static const uint32_t initial_S2[256] = {
0x4b7a70e9u, 0xb5b32944u, 0xdb75092eu, 0xc4192623u, 0xad6ea6b0u,
0x49a7df7du, 0x9cee60b8u, 0x8fedb266u, 0xecaa8c71u, 0x699a17ffu,
0x5664526cu, 0xc2b19ee1u, 0x193602a5u, 0x75094c29u, 0xa0591340u,
0xe4183a3eu, 0x3f54989au, 0x5b429d65u, 0x6b8fe4d6u, 0x99f73fd6u,
0xa1d29c07u, 0xefe830f5u, 0x4d2d38e6u, 0xf0255dc1u, 0x4cdd2086u,
0x8470eb26u, 0x6382e9c6u, 0x021ecc5eu, 0x09686b3fu, 0x3ebaefc9u,
0x3c971814u, 0x6b6a70a1u, 0x687f3584u, 0x52a0e286u, 0xb79c5305u,
0xaa500737u, 0x3e07841cu, 0x7fdeae5cu, 0x8e7d44ecu, 0x5716f2b8u,
0xb03ada37u, 0xf0500c0du, 0xf01c1f04u, 0x0200b3ffu, 0xae0cf51au,
0x3cb574b2u, 0x25837a58u, 0xdc0921bdu, 0xd19113f9u, 0x7ca92ff6u,
0x94324773u, 0x22f54701u, 0x3ae5e581u, 0x37c2dadcu, 0xc8b57634u,
0x9af3dda7u, 0xa9446146u, 0x0fd0030eu, 0xecc8c73eu, 0xa4751e41u,
0xe238cd99u, 0x3bea0e2fu, 0x3280bba1u, 0x183eb331u, 0x4e548b38u,
0x4f6db908u, 0x6f420d03u, 0xf60a04bfu, 0x2cb81290u, 0x24977c79u,
0x5679b072u, 0xbcaf89afu, 0xde9a771fu, 0xd9930810u, 0xb38bae12u,
0xdccf3f2eu, 0x5512721fu, 0x2e6b7124u, 0x501adde6u, 0x9f84cd87u,
0x7a584718u, 0x7408da17u, 0xbc9f9abcu, 0xe94b7d8cu, 0xec7aec3au,
0xdb851dfau, 0x63094366u, 0xc464c3d2u, 0xef1c1847u, 0x3215d908u,
0xdd433b37u, 0x24c2ba16u, 0x12a14d43u, 0x2a65c451u, 0x50940002u,
0x133ae4ddu, 0x71dff89eu, 0x10314e55u, 0x81ac77d6u, 0x5f11199bu,
0x043556f1u, 0xd7a3c76bu, 0x3c11183bu, 0x5924a509u, 0xf28fe6edu,
0x97f1fbfau, 0x9ebabf2cu, 0x1e153c6eu, 0x86e34570u, 0xeae96fb1u,
0x860e5e0au, 0x5a3e2ab3u, 0x771fe71cu, 0x4e3d06fau, 0x2965dcb9u,
0x99e71d0fu, 0x803e89d6u, 0x5266c825u, 0x2e4cc978u, 0x9c10b36au,
0xc6150ebau, 0x94e2ea78u, 0xa5fc3c53u, 0x1e0a2df4u, 0xf2f74ea7u,
0x361d2b3du, 0x1939260fu, 0x19c27960u, 0x5223a708u, 0xf71312b6u,
0xebadfe6eu, 0xeac31f66u, 0xe3bc4595u, 0xa67bc883u, 0xb17f37d1u,
0x018cff28u, 0xc332ddefu, 0xbe6c5aa5u, 0x65582185u, 0x68ab9802u,
0xeecea50fu, 0xdb2f953bu, 0x2aef7dadu, 0x5b6e2f84u, 0x1521b628u,
0x29076170u, 0xecdd4775u, 0x619f1510u, 0x13cca830u, 0xeb61bd96u,
0x0334fe1eu, 0xaa0363cfu, 0xb5735c90u, 0x4c70a239u, 0xd59e9e0bu,
0xcbaade14u, 0xeecc86bcu, 0x60622ca7u, 0x9cab5cabu, 0xb2f3846eu,
0x648b1eafu, 0x19bdf0cau, 0xa02369b9u, 0x655abb50u, 0x40685a32u,
0x3c2ab4b3u, 0x319ee9d5u, 0xc021b8f7u, 0x9b540b19u, 0x875fa099u,
0x95f7997eu, 0x623d7da8u, 0xf837889au, 0x97e32d77u, 0x11ed935fu,
0x16681281u, 0x0e358829u, 0xc7e61fd6u, 0x96dedfa1u, 0x7858ba99u,
0x57f584a5u, 0x1b227263u, 0x9b83c3ffu, 0x1ac24696u, 0xcdb30aebu,
0x532e3054u, 0x8fd948e4u, 0x6dbc3128u, 0x58ebf2efu, 0x34c6ffeau,
0xfe28ed61u, 0xee7c3c73u, 0x5d4a14d9u, 0xe864b7e3u, 0x42105d14u,
0x203e13e0u, 0x45eee2b6u, 0xa3aaabeau, 0xdb6c4f15u, 0xfacb4fd0u,
0xc742f442u, 0xef6abbb5u, 0x654f3b1du, 0x41cd2105u, 0xd81e799eu,
0x86854dc7u, 0xe44b476au, 0x3d816250u, 0xcf62a1f2u, 0x5b8d2646u,
0xfc8883a0u, 0xc1c7b6a3u, 0x7f1524c3u, 0x69cb7492u, 0x47848a0bu,
0x5692b285u, 0x095bbf00u, 0xad19489du, 0x1462b174u, 0x23820e00u,
0x58428d2au, 0x0c55f5eau, 0x1dadf43eu, 0x233f7061u, 0x3372f092u,
0x8d937e41u, 0xd65fecf1u, 0x6c223bdbu, 0x7cde3759u, 0xcbee7460u,
0x4085f2a7u, 0xce77326eu, 0xa6078084u, 0x19f8509eu, 0xe8efd855u,
0x61d99735u, 0xa969a7aau, 0xc50c06c2u, 0x5a04abfcu, 0x800bcadcu,
0x9e447a2eu, 0xc3453484u, 0xfdd56705u, 0x0e1e9ec9u, 0xdb73dbd3u,
0x105588cdu, 0x675fda79u, 0xe3674340u, 0xc5c43465u, 0x713e38d8u,
0x3d28f89eu, 0xf16dff20u, 0x153e21e7u, 0x8fb03d4au, 0xe6e39f2bu,
0xdb83adf7u
};
static const uint32_t initial_S3[256] = {
0xe93d5a68u, 0x948140f7u, 0xf64c261cu, 0x94692934u, 0x411520f7u,
0x7602d4f7u, 0xbcf46b2eu, 0xd4a20068u, 0xd4082471u, 0x3320f46au,
0x43b7d4b7u, 0x500061afu, 0x1e39f62eu, 0x97244546u, 0x14214f74u,
0xbf8b8840u, 0x4d95fc1du, 0x96b591afu, 0x70f4ddd3u, 0x66a02f45u,
0xbfbc09ecu, 0x03bd9785u, 0x7fac6dd0u, 0x31cb8504u, 0x96eb27b3u,
0x55fd3941u, 0xda2547e6u, 0xabca0a9au, 0x28507825u, 0x530429f4u,
0x0a2c86dau, 0xe9b66dfbu, 0x68dc1462u, 0xd7486900u, 0x680ec0a4u,
0x27a18deeu, 0x4f3ffea2u, 0xe887ad8cu, 0xb58ce006u, 0x7af4d6b6u,
0xaace1e7cu, 0xd3375fecu, 0xce78a399u, 0x406b2a42u, 0x20fe9e35u,
0xd9f385b9u, 0xee39d7abu, 0x3b124e8bu, 0x1dc9faf7u, 0x4b6d1856u,
0x26a36631u, 0xeae397b2u, 0x3a6efa74u, 0xdd5b4332u, 0x6841e7f7u,
0xca7820fbu, 0xfb0af54eu, 0xd8feb397u, 0x454056acu, 0xba489527u,
0x55533a3au, 0x20838d87u, 0xfe6ba9b7u, 0xd096954bu, 0x55a867bcu,
0xa1159a58u, 0xcca92963u, 0x99e1db33u, 0xa62a4a56u, 0x3f3125f9u,
0x5ef47e1cu, 0x9029317cu, 0xfdf8e802u, 0x04272f70u, 0x80bb155cu,
0x05282ce3u, 0x95c11548u, 0xe4c66d22u, 0x48c1133fu, 0xc70f86dcu,
0x07f9c9eeu, 0x41041f0fu, 0x404779a4u, 0x5d886e17u, 0x325f51ebu,
0xd59bc0d1u, 0xf2bcc18fu, 0x41113564u, 0x257b7834u, 0x602a9c60u,
0xdff8e8a3u, 0x1f636c1bu, 0x0e12b4c2u, 0x02e1329eu, 0xaf664fd1u,
0xcad18115u, 0x6b2395e0u, 0x333e92e1u, 0x3b240b62u, 0xeebeb922u,
0x85b2a20eu, 0xe6ba0d99u, 0xde720c8cu, 0x2da2f728u, 0xd0127845u,
0x95b794fdu, 0x647d0862u, 0xe7ccf5f0u, 0x5449a36fu, 0x877d48fau,
0xc39dfd27u, 0xf33e8d1eu, 0x0a476341u, 0x992eff74u, 0x3a6f6eabu,
0xf4f8fd37u, 0xa812dc60u, 0xa1ebddf8u, 0x991be14cu, 0xdb6e6b0du,
0xc67b5510u, 0x6d672c37u, 0x2765d43bu, 0xdcd0e804u, 0xf1290dc7u,
0xcc00ffa3u, 0xb5390f92u, 0x690fed0bu, 0x667b9ffbu, 0xcedb7d9cu,
0xa091cf0bu, 0xd9155ea3u, 0xbb132f88u, 0x515bad24u, 0x7b9479bfu,
0x763bd6ebu, 0x37392eb3u, 0xcc115979u, 0x8026e297u, 0xf42e312du,
0x6842ada7u, 0xc66a2b3bu, 0x12754cccu, 0x782ef11cu, 0x6a124237u,
0xb79251e7u, 0x06a1bbe6u, 0x4bfb6350u, 0x1a6b1018u, 0x11caedfau,
0x3d25bdd8u, 0xe2e1c3c9u, 0x44421659u, 0x0a121386u, 0xd90cec6eu,
0xd5abea2au, 0x64af674eu, 0xda86a85fu, 0xbebfe988u, 0x64e4c3feu,
0x9dbc8057u, 0xf0f7c086u, 0x60787bf8u, 0x6003604du, 0xd1fd8346u,
0xf6381fb0u, 0x7745ae04u, 0xd736fcccu, 0x83426b33u, 0xf01eab71u,
0xb0804187u, 0x3c005e5fu, 0x77a057beu, 0xbde8ae24u, 0x55464299u,
0xbf582e61u, 0x4e58f48fu, 0xf2ddfda2u, 0xf474ef38u, 0x8789bdc2u,
0x5366f9c3u, 0xc8b38e74u, 0xb475f255u, 0x46fcd9b9u, 0x7aeb2661u,
0x8b1ddf84u, 0x846a0e79u, 0x915f95e2u, 0x466e598eu, 0x20b45770u,
0x8cd55591u, 0xc902de4cu, 0xb90bace1u, 0xbb8205d0u, 0x11a86248u,
0x7574a99eu, 0xb77f19b6u, 0xe0a9dc09u, 0x662d09a1u, 0xc4324633u,
0xe85a1f02u, 0x09f0be8cu, 0x4a99a025u, 0x1d6efe10u, 0x1ab93d1du,
0x0ba5a4dfu, 0xa186f20fu, 0x2868f169u, 0xdcb7da83u, 0x573906feu,
0xa1e2ce9bu, 0x4fcd7f52u, 0x50115e01u, 0xa70683fau, 0xa002b5c4u,
0x0de6d027u, 0x9af88c27u, 0x773f8641u, 0xc3604c06u, 0x61a806b5u,
0xf0177a28u, 0xc0f586e0u, 0x006058aau, 0x30dc7d62u, 0x11e69ed7u,
0x2338ea63u, 0x53c2dd94u, 0xc2c21634u, 0xbbcbee56u, 0x90bcb6deu,
0xebfc7da1u, 0xce591d76u, 0x6f05e409u, 0x4b7c0188u, 0x39720a3du,
0x7c927c24u, 0x86e3725fu, 0x724d9db9u, 0x1ac15bb4u, 0xd39eb8fcu,
0xed545578u, 0x08fca5b5u, 0xd83d7cd3u, 0x4dad0fc4u, 0x1e50ef5eu,
0xb161e6f8u, 0xa28514d9u, 0x6c51133cu, 0x6fd5c7e7u, 0x56e14ec4u,
0x362abfceu, 0xddc6c837u, 0xd79a3234u, 0x92638212u, 0x670efa8eu,
0x406000e0u
};
static const uint32_t initial_S4[256] = {
0x3a39ce37u, 0xd3faf5cfu, 0xabc27737u, 0x5ac52d1bu, 0x5cb0679eu,
0x4fa33742u, 0xd3822740u, 0x99bc9bbeu, 0xd5118e9du, 0xbf0f7315u,
0xd62d1c7eu, 0xc700c47bu, 0xb78c1b6bu, 0x21a19045u, 0xb26eb1beu,
0x6a366eb4u, 0x5748ab2fu, 0xbc946e79u, 0xc6a376d2u, 0x6549c2c8u,
0x530ff8eeu, 0x468dde7du, 0xd5730a1du, 0x4cd04dc6u, 0x2939bbdbu,
0xa9ba4650u, 0xac9526e8u, 0xbe5ee304u, 0xa1fad5f0u, 0x6a2d519au,
0x63ef8ce2u, 0x9a86ee22u, 0xc089c2b8u, 0x43242ef6u, 0xa51e03aau,
0x9cf2d0a4u, 0x83c061bau, 0x9be96a4du, 0x8fe51550u, 0xba645bd6u,
0x2826a2f9u, 0xa73a3ae1u, 0x4ba99586u, 0xef5562e9u, 0xc72fefd3u,
0xf752f7dau, 0x3f046f69u, 0x77fa0a59u, 0x80e4a915u, 0x87b08601u,
0x9b09e6adu, 0x3b3ee593u, 0xe990fd5au, 0x9e34d797u, 0x2cf0b7d9u,
0x022b8b51u, 0x96d5ac3au, 0x017da67du, 0xd1cf3ed6u, 0x7c7d2d28u,
0x1f9f25cfu, 0xadf2b89bu, 0x5ad6b472u, 0x5a88f54cu, 0xe029ac71u,
0xe019a5e6u, 0x47b0acfdu, 0xed93fa9bu, 0xe8d3c48du, 0x283b57ccu,
0xf8d56629u, 0x79132e28u, 0x785f0191u, 0xed756055u, 0xf7960e44u,
0xe3d35e8cu, 0x15056dd4u, 0x88f46dbau, 0x03a16125u, 0x0564f0bdu,
0xc3eb9e15u, 0x3c9057a2u, 0x97271aecu, 0xa93a072au, 0x1b3f6d9bu,
0x1e6321f5u, 0xf59c66fbu, 0x26dcf319u, 0x7533d928u, 0xb155fdf5u,
0x03563482u, 0x8aba3cbbu, 0x28517711u, 0xc20ad9f8u, 0xabcc5167u,
0xccad925fu, 0x4de81751u, 0x3830dc8eu, 0x379d5862u, 0x9320f991u,
0xea7a90c2u, 0xfb3e7bceu, 0x5121ce64u, 0x774fbe32u, 0xa8b6e37eu,
0xc3293d46u, 0x48de5369u, 0x6413e680u, 0xa2ae0810u, 0xdd6db224u,
0x69852dfdu, 0x09072166u, 0xb39a460au, 0x6445c0ddu, 0x586cdecfu,
0x1c20c8aeu, 0x5bbef7ddu, 0x1b588d40u, 0xccd2017fu, 0x6bb4e3bbu,
0xdda26a7eu, 0x3a59ff45u, 0x3e350a44u, 0xbcb4cdd5u, 0x72eacea8u,
0xfa6484bbu, 0x8d6612aeu, 0xbf3c6f47u, 0xd29be463u, 0x542f5d9eu,
0xaec2771bu, 0xf64e6370u, 0x740e0d8du, 0xe75b1357u, 0xf8721671u,
0xaf537d5du, 0x4040cb08u, 0x4eb4e2ccu, 0x34d2466au, 0x0115af84u,
0xe1b00428u, 0x95983a1du, 0x06b89fb4u, 0xce6ea048u, 0x6f3f3b82u,
0x3520ab82u, 0x011a1d4bu, 0x277227f8u, 0x611560b1u, 0xe7933fdcu,
0xbb3a792bu, 0x344525bdu, 0xa08839e1u, 0x51ce794bu, 0x2f32c9b7u,
0xa01fbac9u, 0xe01cc87eu, 0xbcc7d1f6u, 0xcf0111c3u, 0xa1e8aac7u,
0x1a908749u, 0xd44fbd9au, 0xd0dadecbu, 0xd50ada38u, 0x0339c32au,
0xc6913667u, 0x8df9317cu, 0xe0b12b4fu, 0xf79e59b7u, 0x43f5bb3au,
0xf2d519ffu, 0x27d9459cu, 0xbf97222cu, 0x15e6fc2au, 0x0f91fc71u,
0x9b941525u, 0xfae59361u, 0xceb69cebu, 0xc2a86459u, 0x12baa8d1u,
0xb6c1075eu, 0xe3056a0cu, 0x10d25065u, 0xcb03a442u, 0xe0ec6e0eu,
0x1698db3bu, 0x4c98a0beu, 0x3278e964u, 0x9f1f9532u, 0xe0d392dfu,
0xd3a0342bu, 0x8971f21eu, 0x1b0a7441u, 0x4ba3348cu, 0xc5be7120u,
0xc37632d8u, 0xdf359f8du, 0x9b992f2eu, 0xe60b6f47u, 0x0fe3f11du,
0xe54cda54u, 0x1edad891u, 0xce6279cfu, 0xcd3e7e6fu, 0x1618b166u,
0xfd2c1d05u, 0x848fd2c5u, 0xf6fb2299u, 0xf523f357u, 0xa6327623u,
0x93a83531u, 0x56cccd02u, 0xacf08162u, 0x5a75ebb5u, 0x6e163697u,
0x88d273ccu, 0xde966292u, 0x81b949d0u, 0x4c50901bu, 0x71c65614u,
0xe6c6c7bdu, 0x327a140au, 0x45e1d006u, 0xc3f27b9au, 0xc9aa53fdu,
0x62a80f00u, 0xbb25bfe2u, 0x35bdd2f6u, 0x71126905u, 0xb2040222u,
0xb6cbcf7cu, 0xcd769c2bu, 0x53113ec0u, 0x1640e3d3u, 0x38abbd60u,
0x2547adf0u, 0xba38209cu, 0xf746ce76u, 0x77afa1c5u, 0x20756060u,
0x85cbfe4eu, 0x8ae88dd8u, 0x7aaaf9b0u, 0x4cf9aa7eu, 0x1948c25cu,
0x02fb8a8cu, 0x01c36ae4u, 0xd6ebe1f9u, 0x90d4f869u, 0xa65cdea0u,
0x3f09252du, 0xc208e69fu, 0xb74e6132u, 0xce77e25bu, 0x578fdfe3u,
0x3ac372e6u
};
#endif /* BLOWFISH_TABLES_H */
/* vim:set ts=4 sw=4 sts=4 expandtab: */

View File

@ -0,0 +1,245 @@
/*
*
* Blowfish.c : Blowfish implementation
*
* Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
*
* =======================================================================
* The contents of this file are dedicated to the public domain. To the extent
* that dedication to the public domain is not available, everyone is granted a
* worldwide, perpetual, royalty-free, non-exclusive license to exercise all
* rights associated with the contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* =======================================================================
*
* Country of origin: Canada
*
* The Blowfish algorithm is documented at
* http://www.schneier.com/paper-blowfish-fse.html
*/
#include "config.h"
#if HAVE_STDINT_H
# include <stdint.h>
#elif defined(__sun) || defined(__sun__)
# include <sys/inttypes.h>
#else
# error "stdint.h not found"
#endif
#include <assert.h>
#include <string.h>
#include "Python.h"
#include "Blowfish-tables.h"
#define MODULE_NAME _Blowfish
#define BLOCK_SIZE 8 /* 64-bit block size */
#define KEY_SIZE 0 /* variable key size */
#define BLOWFISH_MAGIC 0xf9d565deu
typedef struct {
uint32_t magic;
/* P permutation */
uint32_t P[18];
/* Subkeys (S-boxes) */
uint32_t S1[256];
uint32_t S2[256];
uint32_t S3[256];
uint32_t S4[256];
} Blowfish_state;
/* The Blowfish round function F. Everything is taken modulo 2**32 */
#define F(a, b, c, d) (((a) + (b)) ^ (c)) + (d)
static inline uint32_t bytes_to_word(const unsigned char *in)
{
/* big endian */
return (in[0] << 24) | (in[1] << 16) | (in[2] << 8) | in[3];
}
static inline void word_to_bytes(uint32_t w, unsigned char *out)
{
/* big endian */
out[0] = (w >> 24) & 0xff;
out[1] = (w >> 16) & 0xff;
out[2] = (w >> 8) & 0xff;
out[3] = w & 0xff;
}
static inline void inline_encrypt(Blowfish_state *self, uint32_t *pxL, uint32_t *pxR)
{
int i;
uint32_t xL = *pxL;
uint32_t xR = *pxR;
uint32_t tmp;
for (i = 0; i < 16; i++) {
xL ^= self->P[i];
/* a || b || c || d = xL (big endian) */
xR ^= F(self->S1[(xL >> 24) & 0xff], /* S1[a] */
self->S2[(xL >> 16) & 0xff], /* S2[b] */
self->S3[(xL >> 8) & 0xff], /* S3[c] */
self->S4[xL & 0xff]); /* S4[d] */
/* Swap xL, xR */
tmp = xL; xL = xR; xR = tmp;
}
/* Swap xL, xR */
tmp = xL; xL = xR; xR = tmp;
xR ^= self->P[16];
xL ^= self->P[17];
*pxL = xL;
*pxR = xR;
}
static inline void inline_decrypt(Blowfish_state *self, uint32_t *pxL, uint32_t *pxR)
{
int i;
uint32_t xL = *pxL;
uint32_t xR = *pxR;
uint32_t tmp;
xL ^= self->P[17];
xR ^= self->P[16];
/* Swap xL, xR */
tmp = xL; xL = xR; xR = tmp;
for (i = 15; i >= 0; i--) {
/* Swap xL, xR */
tmp = xL; xL = xR; xR = tmp;
/* a || b || c || d = xL (big endian) */
xR ^= F(self->S1[(xL >> 24) & 0xff], /* S1[a] */
self->S2[(xL >> 16) & 0xff], /* S2[b] */
self->S3[(xL >> 8) & 0xff], /* S3[c] */
self->S4[xL & 0xff]); /* S4[d] */
xL ^= self->P[i];
}
*pxL = xL;
*pxR = xR;
}
static void Blowfish_encrypt(Blowfish_state *self, const unsigned char *in, unsigned char *out)
{
uint32_t xL, xR;
/* Make sure the object is initialized */
assert(self->magic == BLOWFISH_MAGIC);
/* big endian */
xL = bytes_to_word(in);
xR = bytes_to_word(in+4);
inline_encrypt(self, &xL, &xR);
/* big endian */
word_to_bytes(xL, out);
word_to_bytes(xR, out+4);
}
static void Blowfish_decrypt(Blowfish_state *self, const unsigned char *in, unsigned char *out)
{
uint32_t xL, xR;
/* Make sure the object is initialized */
assert(self->magic == BLOWFISH_MAGIC);
/* big endian */
xL = bytes_to_word(in);
xR = bytes_to_word(in+4);
inline_decrypt(self, &xL, &xR);
/* big endian */
word_to_bytes(xL, out);
word_to_bytes(xR, out+4);
}
static void Blowfish_init(Blowfish_state *self, const unsigned char *key, int keylen)
{
uint32_t word;
int i;
uint32_t xL, xR;
self->magic = 0;
if (keylen < 1) {
PyErr_SetString(PyExc_ValueError, "Key cannot be empty");
return;
} else if (keylen > 56) {
PyErr_SetString(PyExc_ValueError, "Maximum key size is 448 bits");
return;
}
/* Initialize the P-array with the digits of Pi, and XOR it with the key */
word = 0;
for (i = 0; i < 18*4; i++) {
word = (word << 8) | key[i % keylen];
if ((i & 3) == 3) {
self->P[i >> 2] = initial_P[i >> 2] ^ word;
word = 0;
}
}
/* Initialize the S-boxes with more digits of Pi */
memcpy(self->S1, initial_S1, 256*sizeof(uint32_t));
memcpy(self->S2, initial_S2, 256*sizeof(uint32_t));
memcpy(self->S3, initial_S3, 256*sizeof(uint32_t));
memcpy(self->S4, initial_S4, 256*sizeof(uint32_t));
/* Stir the subkeys */
xL = xR = 0;
for (i = 0; i < 18; i += 2) {
inline_encrypt(self, &xL, &xR);
self->P[i] = xL;
self->P[i+1] = xR;
}
for (i = 0; i < 256; i += 2) {
inline_encrypt(self, &xL, &xR);
self->S1[i] = xL;
self->S1[i+1] = xR;
}
for (i = 0; i < 256; i += 2) {
inline_encrypt(self, &xL, &xR);
self->S2[i] = xL;
self->S2[i+1] = xR;
}
for (i = 0; i < 256; i += 2) {
inline_encrypt(self, &xL, &xR);
self->S3[i] = xL;
self->S3[i+1] = xR;
}
for (i = 0; i < 256; i += 2) {
inline_encrypt(self, &xL, &xR);
self->S4[i] = xL;
self->S4[i+1] = xR;
}
self->magic = BLOWFISH_MAGIC;
}
#define block_state Blowfish_state
#define block_init Blowfish_init
#define block_encrypt Blowfish_encrypt
#define block_decrypt Blowfish_decrypt
#include "block_template.c"
/* vim:set ts=4 sw=4 sts=4 expandtab: */

View File

@ -0,0 +1,453 @@
/*
cast.c -- implementation of CAST-128 (aka CAST5) as described in RFC2144
Written in 1997 by Wim Lewis <wiml@hhhh.org> based entirely on RFC2144.
Minor modifications made in 2002 by Andrew M. Kuchling <amk@amk.ca>.
===================================================================
The contents of this file are dedicated to the public domain. To
the extent that dedication to the public domain is not available,
everyone is granted a worldwide, perpetual, royalty-free,
non-exclusive license to exercise all rights associated with the
contents of this file for any purpose whatsoever.
No rights are reserved.
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 AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
===================================================================
Consult your local laws for possible restrictions on use, distribution, and
import/export. RFC2144 states that this algorithm "is available worldwide
on a royalty-free basis for commercial and non-commercial uses".
This code is a pretty straightforward transliteration of the RFC into C.
It has not been optimized much at all: byte-order-independent arithmetic
operations are used where order-dependent pointer ops or unions might be
faster; the code could be rearranged to give the optimizer a better
chance to speed things up; etc.
This code requires a vaguely ANSI-ish compiler.
compile -DTEST to include main() which performs the tests
specified in RFC2144
Tested with gcc 2.5.8 on i486, i586, i686, hp pa-risc, mc68040, sparc;
also with gcc 2.7.2 and (with minor changes) native Sun compiler on sparc
*/
#include "Python.h"
#define MODULE_NAME _CAST
#define BLOCK_SIZE 8
#define KEY_SIZE 0
/* adjust these according to your compiler/platform. On some machines
uint32 will have to be a long. It's OK if uint32 is more than 32 bits. */
typedef unsigned int uint32;
typedef unsigned char uint8;
/* this struct probably belongs in cast.h */
typedef struct {
/* masking and rotate keys */
uint32 Km[16];
uint8 Kr[16];
/* number of rounds (depends on original unpadded keylength) */
int rounds;
} block_state;
/* these are the eight 32*256 S-boxes */
#include "cast5.c"
/* fetch a uint32 from an array of uint8s (with a given offset) */
#define fetch(ptr, base) (((((( ptr[base]<< 8 ) | ptr[base+1] )<< 8 ) | ptr[base+2] )<< 8 ) | ptr[base+3])
/* this is the round function f(D, Km, Kr) */
static uint32 castfunc(uint32 D, uint32 Kmi, uint8 Kri, int type)
{
uint32 I, f;
short Ia, Ib, Ic, Id;
switch(type) {
case 0:
I = (Kmi + D) ;
break;
case 1:
I = (Kmi ^ D) ;
break;
default:
case 2:
I = (Kmi - D) ;
break;
}
I &= 0xFFFFFFFF;
I = ( I << Kri ) | ( I >> ( 32-Kri ) );
Ia = ( I >> 24 ) & 0xFF;
Ib = ( I >> 16 ) & 0xFF;
Ic = ( I >> 8 ) & 0xFF;
Id = ( I ) & 0xFF;
switch(type) {
case 0:
f = ((S1[Ia] ^ S2[Ib]) - S3[Ic]) + S4[Id];
break;
case 1:
f = ((S1[Ia] - S2[Ib]) + S3[Ic]) ^ S4[Id];
break;
default:
case 2:
f = ((S1[Ia] + S2[Ib]) ^ S3[Ic]) - S4[Id];
break;
}
return f;
}
/* encrypts/decrypts one block of data according to the key schedule
pointed to by `key'. Encrypts if decrypt=0, otherwise decrypts. */
static void castcrypt(block_state *key, uint8 *block, int decrypt)
{
uint32 L, R, tmp, f;
uint32 Kmi;
uint8 Kri;
short functype, round;
L = fetch(block, 0);
R = fetch(block, 4);
/* printf("L0 = %08x R0 = %08x\n", L, R); */
for(round = 0; round < key->rounds; round ++) {
if (!decrypt) {
Kmi = key->Km[round];
Kri = key->Kr[round];
functype = round % 3;
} else {
Kmi = key->Km[(key->rounds) - round - 1];
Kri = key->Kr[(key->rounds) - round - 1];
functype = (((key->rounds) - round - 1) % 3);
}
f = castfunc(R, Kmi, Kri, functype);
tmp = L;
L = R;
R = tmp ^ f;
/* printf("L%d = %08x R%d = %08x\n", round+1, L, round+1, R); */
}
block[0] = ( R & 0xFF000000 ) >> 24;
block[1] = ( R & 0x00FF0000 ) >> 16;
block[2] = ( R & 0x0000FF00 ) >> 8;
block[3] = ( R & 0x000000FF );
block[4] = ( L & 0xFF000000 ) >> 24;
block[5] = ( L & 0x00FF0000 ) >> 16;
block[6] = ( L & 0x0000FF00 ) >> 8;
block[7] = ( L & 0x000000FF );
}
/* fetch a uint8 from an array of uint32s */
#define b(a,n) (((a)[n/4] >> (24-((n&3)*8))) & 0xFF)
/* key schedule round functions */
#define XZRound(T, F, ki1, ki2, ki3, ki4, \
si11, si12, si13, si14, si15,\
si25,\
si35,\
si45 ) \
T[0] = F[ki1] ^ S5[si11 ] ^ S6[si12 ] ^ S7[si13 ] ^ S8[si14 ] ^ S7[si15];\
T[1] = F[ki2] ^ S5[b(T, 0)] ^ S6[b(T,2)] ^ S7[b(T, 1)] ^ S8[b(T,3)] ^ S8[si25];\
T[2] = F[ki3] ^ S5[b(T, 7)] ^ S6[b(T,6)] ^ S7[b(T, 5)] ^ S8[b(T,4)] ^ S5[si35];\
T[3] = F[ki4] ^ S5[b(T,10)] ^ S6[b(T,9)] ^ S7[b(T,11)] ^ S8[b(T,8)] ^ S6[si45];
#define zxround() XZRound(z, x, 0, 2, 3, 1, \
b(x,13), b(x,15), b(x,12), b(x,14),\
b(x, 8), b(x,10), b(x, 9), b(x,11))
#define xzround() XZRound(x, z, 2, 0, 1, 3, \
b(z,5), b(z,7), b(z,4), b(z,6), \
b(z,0), b(z,2), b(z,1), b(z,3))
#define Kround(T, base, F,\
i11, i12, i13, i14, i15,\
i21, i22, i23, i24, i25,\
i31, i32, i33, i34, i35,\
i41, i42, i43, i44, i45)\
T[base+0] = S5[b(F,i11)] ^ S6[b(F,i12)] ^ S7[b(F,i13)] ^ S8[b(F,i14)] ^ S5[b(F,i15)];\
T[base+1] = S5[b(F,i21)] ^ S6[b(F,i22)] ^ S7[b(F,i23)] ^ S8[b(F,i24)] ^ S6[b(F,i25)];\
T[base+2] = S5[b(F,i31)] ^ S6[b(F,i32)] ^ S7[b(F,i33)] ^ S8[b(F,i34)] ^ S7[b(F,i35)];\
T[base+3] = S5[b(F,i41)] ^ S6[b(F,i42)] ^ S7[b(F,i43)] ^ S8[b(F,i44)] ^ S8[b(F,i45)];
/* generates sixteen 32-bit subkeys based on a 4x32-bit input key;
modifies the input key *in as well. */
static void schedulekeys_half(uint32 *in, uint32 *keys)
{
uint32 x[4], z[4];
x[0] = in[0];
x[1] = in[1];
x[2] = in[2];
x[3] = in[3];
zxround();
Kround(keys, 0, z,
8, 9, 7, 6, 2,
10, 11, 5, 4, 6,
12, 13, 3, 2, 9,
14, 15, 1, 0, 12);
xzround();
Kround(keys, 4, x,
3, 2, 12, 13, 8,
1, 0, 14, 15, 13,
7, 6, 8, 9, 3,
5, 4, 10, 11, 7);
zxround();
Kround(keys, 8, z,
3, 2, 12, 13, 9,
1, 0, 14, 15, 12,
7, 6, 8, 9, 2,
5, 4, 10, 11, 6);
xzround();
Kround(keys, 12, x,
8, 9, 7, 6, 3,
10, 11, 5, 4, 7,
12, 13, 3, 2, 8,
14, 15, 1, 0, 13);
in[0] = x[0];
in[1] = x[1];
in[2] = x[2];
in[3] = x[3];
}
/* generates a key schedule from an input key */
static void castschedulekeys(block_state *schedule, uint8 *key, int keybytes)
{
uint32 x[4];
uint8 paddedkey[16];
uint32 Kr_wide[16];
int i;
for(i = 0; i < keybytes; i++)
paddedkey[i] = key[i];
for( ; i < 16 ; i++)
paddedkey[i] = 0;
if (keybytes <= 10)
schedule->rounds = 12;
else
schedule->rounds = 16;
x[0] = fetch(paddedkey, 0);
x[1] = fetch(paddedkey, 4);
x[2] = fetch(paddedkey, 8);
x[3] = fetch(paddedkey, 12);
schedulekeys_half(x, schedule->Km);
schedulekeys_half(x, Kr_wide);
for(i = 0; i < 16; i ++) {
/* The Kr[] subkeys are used for 32-bit circular shifts,
so we only need to keep them modulo 32 */
schedule->Kr[i] = (uint8)(Kr_wide[i] & 0x1F);
}
}
#ifdef TEST
/* This performs a variety of encryptions and verifies that the results
match those specified in RFC2144 appendix B. Also verifies that
decryption restores the original data. */
#include <stdio.h>
static block_state sched;
void encrypt(key, keylen, in, out)
uint8 *key;
int keylen;
uint8 *in, *out;
{
int i;
uint8 k[16];
castschedulekeys(&sched, key, keylen);
for(i = 0; i < 8; i++)
out[i] = in[i];
castcrypt(&sched, out, 0);
}
void tst(key, keylen, data, result)
uint8 *key;
int keylen;
uint8 *data, *result;
{
uint8 d[8];
int i;
encrypt(key, keylen, data, d);
for(i = 0; i < 8; i++)
if (d[i] != result[i])
break;
if (i == 8) {
printf("-- test ok (encrypt)\n");
} else {
for(i = 0; i < 8; i++)
printf(" %02x", d[i]);
printf(" (computed)\n");
for(i = 0; i < 8; i++)
printf(" %02x", result[i]);
printf(" (expected)\n");
}
/* uses key schedule already set up */
castcrypt(&sched, d, 1);
if (bcmp(d, data, 8))
printf(" test FAILED (decrypt)\n");
else
printf(" test ok (decrypt)\n");
}
uint8 key[16] = { 0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78,
0x23, 0x45, 0x67, 0x89, 0x34, 0x56, 0x78, 0x9A };
uint8 data[8] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };
/* expected results of encrypting the above with 128, 80, and 40
bits of key length */
uint8 out1[8] = { 0x23, 0x8B, 0x4F, 0xE5, 0x84, 0x7E, 0x44, 0xB2 };
uint8 out2[8] = { 0xEB, 0x6A, 0x71, 0x1A, 0x2C, 0x02, 0x27, 0x1B };
uint8 out3[8] = { 0x7A, 0xC8, 0x16, 0xD1, 0x6E, 0x9B, 0x30, 0x2E };
/* expected results of the "full maintenance test" */
uint8 afinal[16] = { 0xEE, 0xA9, 0xD0, 0xA2, 0x49, 0xFD, 0x3B, 0xA6,
0xB3, 0x43, 0x6F, 0xB8, 0x9D, 0x6D, 0xCA, 0x92 };
uint8 bfinal[16] = { 0xB2, 0xC9, 0x5E, 0xB0, 0x0C, 0x31, 0xAD, 0x71,
0x80, 0xAC, 0x05, 0xB8, 0xE8, 0x3D, 0x69, 0x6E };
main()
{
/* Appendix B.1 : Single Plaintext-Key-Ciphertext Sets */
tst(key, 16, data, out1);
tst(key, 10, data, out2);
tst(key, 5, data, out3);
/* Appendix B.2 : Full Maintenance Test */
{
uint8 abuf[16];
uint8 bbuf[16];
int i;
bcopy(key, abuf, 16);
bcopy(key, bbuf, 16);
printf("\nrunning full maintenance test...\n");
for(i = 0; i < 1000000; i++) {
castschedulekeys(&sched, bbuf, 16);
castcrypt(&sched, abuf, 0);
castcrypt(&sched, abuf+8, 0);
castschedulekeys(&sched, abuf, 16);
castcrypt(&sched, bbuf, 0);
castcrypt(&sched, bbuf+8, 0);
if (!(i % 10000)) {
fprintf(stdout, "\r%d%% ", i / 10000);
fflush(stdout);
}
}
printf("\r \r");
for(i = 0; i < 16; i ++)
if (abuf[i] != afinal[i] || bbuf[i] != bfinal[i])
break;
if(i == 16) {
printf("-- full maintenance test ok\n");
} else {
for(i = 0; i < 16; i++)
printf(" %02x", abuf[i]);
printf("\n");
for(i = 0; i < 16; i++)
printf(" %02x", bbuf[i]);
printf("\n");
}
printf("running maintenance test in reverse...\n");
for(i = 0; i < 1000000; i++) {
castschedulekeys(&sched, abuf, 16);
castcrypt(&sched, bbuf+8, 1);
castcrypt(&sched, bbuf, 1);
castschedulekeys(&sched, bbuf, 16);
castcrypt(&sched, abuf+8, 1);
castcrypt(&sched, abuf, 1);
if (!(i % 10000)) {
fprintf(stdout, "\r%d%% ", i / 10000);
fflush(stdout);
}
}
printf("\r \r");
if (bcmp(abuf, key, 16) || bcmp(bbuf, key, 16))
printf("-- reverse maintenance test FAILED\n");
else
printf("-- reverse maintenance test ok\n");
}
}
#endif
static void
block_init(block_state *self, unsigned char *key, int keylength)
{
/* presumably this will optimize out */
if (sizeof(uint32) < 4 || sizeof(uint8) != 1) {
PyErr_SetString(PyExc_SystemError,
"CAST module compiled with bad typedefs!");
}
/* make sure the key length is within bounds */
if (keylength < 5 || keylength > 16) {
PyErr_SetString(PyExc_ValueError, "CAST key must be "
"at least 5 bytes and no more than 16 bytes long");
return;
}
/* do the actual key schedule setup */
castschedulekeys(self, key, keylength);
}
static void
block_encrypt(block_state *self, unsigned char *in,
unsigned char *out)
{
memcpy(out, in, 8);
castcrypt(self, out, 0);
}
static void block_decrypt(block_state *self,
unsigned char *in,
unsigned char *out)
{
memcpy(out, in, 8);
castcrypt(self, out, 1);
}
#include "block_template.c"

View File

@ -0,0 +1,109 @@
/*
* DES.c: DES/3DES support for PyCrypto using LibTomCrypt
*
* Written in 2009 by Dwayne C. Litzenberger <dlitz@dlitz.net>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
* Country of origin: Canada
*/
/* Setting this will cause LibTomCrypt to return CRYPT_INVALID_ARG when its
* assert-like LTC_ARGCHK macro fails. */
#define ARGTYPE 4
/* Include the actial DES implementation */
#include "libtom/tomcrypt_des.c"
#undef DES /* this is needed because tomcrypt_custom.h defines DES to an empty string */
#include <assert.h>
#include "Python.h"
typedef struct {
symmetric_key sk;
} block_state;
static void ltcseterr(int rc)
{
/* error */
switch (rc) {
case CRYPT_INVALID_ARG:
PyErr_SetString(PyExc_AssertionError, "CRYPT_INVALID_ARG");
break;
case CRYPT_INVALID_KEYSIZE:
PyErr_SetString(PyExc_ValueError, "Invalid key size (must be either 16 or 24 bytes long)");
break;
case CRYPT_INVALID_ROUNDS:
PyErr_SetString(PyExc_ValueError, "Invalid number of rounds specified");
break;
default:
PyErr_Format(PyExc_RuntimeError,
"unexpected run-time error (LTC#%d)", rc);
}
}
static void block_init(block_state *self, unsigned char *key, int keylen)
{
int rc;
#ifdef PCT_DES3_MODULE
rc = des3_setup(key, keylen, 0, &self->sk);
#else
rc = des_setup(key, keylen, 0, &self->sk);
#endif
if (rc != CRYPT_OK) {
ltcseterr(rc);
}
}
static void block_encrypt(block_state *self, unsigned char *in, unsigned char *out)
{
int rc;
#ifdef PCT_DES3_MODULE
rc = des3_ecb_encrypt(in, out, &self->sk);
#else
rc = des_ecb_encrypt(in, out, &self->sk);
#endif
assert(rc == CRYPT_OK);
}
static void block_decrypt(block_state *self, unsigned char *in, unsigned char *out)
{
int rc;
#ifdef PCT_DES3_MODULE
rc = des3_ecb_decrypt(in, out, &self->sk);
#else
rc = des_ecb_decrypt(in, out, &self->sk);
#endif
assert(rc == CRYPT_OK);
}
#ifdef PCT_DES3_MODULE
# define MODULE_NAME _DES3 /* triple DES */
# define BLOCK_SIZE 8 /* 64-bit block size */
# define KEY_SIZE 0 /* variable key size (can be 128 or 192 bits (including parity) */
#else
# define MODULE_NAME _DES /* single DES */
# define BLOCK_SIZE 8 /* 64-bit block size */
# define KEY_SIZE 8 /* 64-bit keys (including parity) */
#endif
#include "block_template.c"

View File

@ -0,0 +1,26 @@
/*
* DES3.c: 3DES support for PyCrypto using LibTomCrypt
*
* Written in 2009 by Dwayne C. Litzenberger <dlitz@dlitz.net>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#define PCT_DES3_MODULE
#include "DES.c"

View File

@ -0,0 +1,147 @@
/*
* md2.c : MD2 hash algorithm.
*
* Part of the Python Cryptography Toolkit
*
* Originally written by: A.M. Kuchling
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#include <string.h>
#include "Python.h"
#include "pycrypto_compat.h"
#define MODULE_NAME _MD2
#define DIGEST_SIZE 16
#define BLOCK_SIZE 64
/**
* id-md2 OBJECT IDENTIFIER ::= {
* iso(1) member-body(2) us(840) rsadsi(113549)
* digestAlgorithm(2) 2
* }
*/
static const char md2_oid[] = { 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x02 };
#define DER_OID ((void*)&md2_oid)
#define DER_OID_SIZE (sizeof md2_oid)
typedef unsigned char U8;
typedef unsigned int U32;
typedef struct {
U8 C[16], X[48];
int count;
U8 buf[16];
} hash_state;
static void hash_init (hash_state *ptr)
{
memset(ptr->X, 0, 48);
memset(ptr->C, 0, 16);
ptr->count=0;
}
static U8 S[256] = {
41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6,
19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188,
76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24,
138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251,
245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63,
148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50,
39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165,
181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210,
150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157,
112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27,
96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197,
234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65,
129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123,
8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233,
203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228,
166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237,
31, 26, 219, 153, 141, 51, 159, 17, 131, 20
};
static void
hash_copy(hash_state *src, hash_state *dest)
{
dest->count=src->count;
memcpy(dest->buf, src->buf, dest->count);
memcpy(dest->X, src->X, 48);
memcpy(dest->C, src->C, 16);
}
static void hash_update (hash_state *self, const U8 *buf, U32 len)
{
U32 L;
while (len)
{
L=(16-self->count) < len ? (16-self->count) : len;
memcpy(self->buf+self->count, buf, L);
self->count+=L;
buf+=L;
len-=L;
if (self->count==16)
{
U8 t;
int i,j;
self->count=0;
memcpy(self->X+16, self->buf, 16);
t=self->C[15];
for(i=0; i<16; i++)
{
self->X[32+i]=self->X[16+i]^self->X[i];
t=self->C[i]^=S[self->buf[i]^t];
}
t=0;
for(i=0; i<18; i++)
{
for(j=0; j<48; j++)
t=self->X[j]^=S[t];
t=(t+i) & 0xFF;
}
}
}
}
static PyObject *
hash_digest (const hash_state *self)
{
U8 padding[16];
U32 padlen;
hash_state temp;
int i;
memcpy(&temp, self, sizeof(hash_state));
padlen= 16-self->count;
for(i=0; i<padlen; i++) padding[i]=padlen;
hash_update(&temp, padding, padlen);
hash_update(&temp, temp.C, 16);
return PyBytes_FromStringAndSize((char *) temp.X, 16);
}
#include "hash_template.c"

View File

@ -0,0 +1,221 @@
/*
* md4.c : MD4 hash algorithm.
*
* Part of the Python Cryptography Toolkit
*
* Originally written by: A.M. Kuchling
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#include <string.h>
#include "Python.h"
#include "pycrypto_compat.h"
#define MODULE_NAME _MD4
#define DIGEST_SIZE 16
#define BLOCK_SIZE 64
typedef unsigned int U32;
typedef unsigned char U8;
#define U32_MAX (U32)4294967295
typedef struct {
U32 A,B,C,D, count;
U32 len1, len2;
U8 buf[64];
} hash_state;
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
/* ROTATE_LEFT rotates x left n bits */
#define ROL(x, n) (((x) << n) | ((x) >> (32-n) ))
static void
hash_init (hash_state *ptr)
{
ptr->A=(U32)0x67452301;
ptr->B=(U32)0xefcdab89;
ptr->C=(U32)0x98badcfe;
ptr->D=(U32)0x10325476;
ptr->count=ptr->len1=ptr->len2=0;
}
static void
hash_copy(hash_state *src, hash_state *dest)
{
dest->len1=src->len1;
dest->len2=src->len2;
dest->A=src->A;
dest->B=src->B;
dest->C=src->C;
dest->D=src->D;
dest->count=src->count;
memcpy(dest->buf, src->buf, dest->count);
}
static void
hash_update (hash_state *self, const U8 *buf, U32 len)
{
U32 L;
if ((self->len1+(len<<3))<self->len1)
{
self->len2++;
}
self->len1+=len<< 3;
self->len2+=len>>29;
while (len>0)
{
L=(64-self->count) < len ? (64-self->count) : len;
memcpy(self->buf+self->count, buf, L);
self->count+=L;
buf+=L;
len-=L;
if (self->count==64)
{
U32 X[16], A, B, C, D;
int i,j;
self->count=0;
for(i=j=0; j<16; i+=4, j++)
X[j]=((U32)self->buf[i] + ((U32)self->buf[i+1]<<8) +
((U32)self->buf[i+2]<<16) + ((U32)self->buf[i+3]<<24));
A=self->A; B=self->B; C=self->C; D=self->D;
#define function(a,b,c,d,k,s) a=ROL(a+F(b,c,d)+X[k],s);
function(A,B,C,D, 0, 3);
function(D,A,B,C, 1, 7);
function(C,D,A,B, 2,11);
function(B,C,D,A, 3,19);
function(A,B,C,D, 4, 3);
function(D,A,B,C, 5, 7);
function(C,D,A,B, 6,11);
function(B,C,D,A, 7,19);
function(A,B,C,D, 8, 3);
function(D,A,B,C, 9, 7);
function(C,D,A,B,10,11);
function(B,C,D,A,11,19);
function(A,B,C,D,12, 3);
function(D,A,B,C,13, 7);
function(C,D,A,B,14,11);
function(B,C,D,A,15,19);
#undef function
#define function(a,b,c,d,k,s) a=ROL(a+G(b,c,d)+X[k]+(U32)0x5a827999,s);
function(A,B,C,D, 0, 3);
function(D,A,B,C, 4, 5);
function(C,D,A,B, 8, 9);
function(B,C,D,A,12,13);
function(A,B,C,D, 1, 3);
function(D,A,B,C, 5, 5);
function(C,D,A,B, 9, 9);
function(B,C,D,A,13,13);
function(A,B,C,D, 2, 3);
function(D,A,B,C, 6, 5);
function(C,D,A,B,10, 9);
function(B,C,D,A,14,13);
function(A,B,C,D, 3, 3);
function(D,A,B,C, 7, 5);
function(C,D,A,B,11, 9);
function(B,C,D,A,15,13);
#undef function
#define function(a,b,c,d,k,s) a=ROL(a+H(b,c,d)+X[k]+(U32)0x6ed9eba1,s);
function(A,B,C,D, 0, 3);
function(D,A,B,C, 8, 9);
function(C,D,A,B, 4,11);
function(B,C,D,A,12,15);
function(A,B,C,D, 2, 3);
function(D,A,B,C,10, 9);
function(C,D,A,B, 6,11);
function(B,C,D,A,14,15);
function(A,B,C,D, 1, 3);
function(D,A,B,C, 9, 9);
function(C,D,A,B, 5,11);
function(B,C,D,A,13,15);
function(A,B,C,D, 3, 3);
function(D,A,B,C,11, 9);
function(C,D,A,B, 7,11);
function(B,C,D,A,15,15);
self->A+=A; self->B+=B; self->C+=C; self->D+=D;
}
}
}
static PyObject *
hash_digest (const hash_state *self)
{
U8 digest[16];
static U8 s[8];
U32 padlen, oldlen1, oldlen2;
hash_state temp;
static U8 padding[64] = {
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
memcpy(&temp, self, sizeof(hash_state));
oldlen1=temp.len1; oldlen2=temp.len2; /* Save current length */
padlen= (56<=self->count) ? 56-self->count+64: 56-self->count;
hash_update(&temp, padding, padlen);
s[0]= oldlen1 & 255;
s[1]=(oldlen1 >> 8) & 255;
s[2]=(oldlen1 >> 16) & 255;
s[3]=(oldlen1 >> 24) & 255;
s[4]= oldlen2 & 255;
s[5]=(oldlen2 >> 8) & 255;
s[6]=(oldlen2 >> 16) & 255;
s[7]=(oldlen2 >> 24) & 255;
hash_update(&temp, s, 8);
digest[ 0]= temp.A & 255;
digest[ 1]=(temp.A >> 8) & 255;
digest[ 2]=(temp.A >> 16) & 255;
digest[ 3]=(temp.A >> 24) & 255;
digest[ 4]= temp.B & 255;
digest[ 5]=(temp.B >> 8) & 255;
digest[ 6]=(temp.B >> 16) & 255;
digest[ 7]=(temp.B >> 24) & 255;
digest[ 8]= temp.C & 255;
digest[ 9]=(temp.C >> 8) & 255;
digest[10]=(temp.C >> 16) & 255;
digest[11]=(temp.C >> 24) & 255;
digest[12]= temp.D & 255;
digest[13]=(temp.D >> 8) & 255;
digest[14]=(temp.D >> 16) & 255;
digest[15]=(temp.D >> 24) & 255;
return PyBytes_FromStringAndSize((char *) digest, 16);
}
#include "hash_template.c"

View File

@ -0,0 +1,427 @@
/*
*
* RIPEMD160.c : RIPEMD-160 implementation
*
* Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
* Country of origin: Canada
*
* This implementation (written in C) is based on an implementation the author
* wrote in Python.
*
* This implementation was written with reference to the RIPEMD-160
* specification, which is available at:
* http://homes.esat.kuleuven.be/~cosicart/pdf/AB-9601/
*
* It is also documented in the _Handbook of Applied Cryptography_, as
* Algorithm 9.55. It's on page 30 of the following PDF file:
* http://www.cacr.math.uwaterloo.ca/hac/about/chap9.pdf
*
* The RIPEMD-160 specification doesn't really tell us how to do padding, but
* since RIPEMD-160 is inspired by MD4, you can use the padding algorithm from
* RFC 1320.
*
* According to http://www.users.zetnet.co.uk/hopwood/crypto/scan/md.html:
* "RIPEMD-160 is big-bit-endian, little-byte-endian, and left-justified."
*/
#include "config.h"
#if HAVE_STDINT_H
# include <stdint.h>
#elif defined(__sun) || defined(__sun__)
# include <sys/inttypes.h>
#else
# error "stdint.h not found"
#endif
#include <assert.h>
#include <string.h>
#include "Python.h"
#include "pycrypto_compat.h"
#define RIPEMD160_DIGEST_SIZE 20
#define BLOCK_SIZE 64
#define RIPEMD160_MAGIC 0x9f19dd68u
typedef struct {
uint32_t magic;
uint32_t h[5]; /* The current hash state */
uint64_t length; /* Total number of _bits_ (not bytes) added to the
hash. This includes bits that have been buffered
but not not fed through the compression function yet. */
union {
uint32_t w[16];
uint8_t b[64];
} buf;
uint8_t bufpos; /* number of bytes currently in the buffer */
} ripemd160_state;
/* cyclic left-shift the 32-bit word n left by s bits */
#define ROL(s, n) (((n) << (s)) | ((n) >> (32-(s))))
/* Initial values for the chaining variables.
* This is just 0123456789ABCDEFFEDCBA9876543210F0E1D2C3 in little-endian. */
static const uint32_t initial_h[5] = { 0x67452301u, 0xEFCDAB89u, 0x98BADCFEu, 0x10325476u, 0xC3D2E1F0u };
/* Ordering of message words. Based on the permutations rho(i) and pi(i), defined as follows:
*
* rho(i) := { 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8 }[i] 0 <= i <= 15
*
* pi(i) := 9*i + 5 (mod 16)
*
* Line | Round 1 | Round 2 | Round 3 | Round 4 | Round 5
* -------+-----------+-----------+-----------+-----------+-----------
* left | id | rho | rho^2 | rho^3 | rho^4
* right | pi | rho pi | rho^2 pi | rho^3 pi | rho^4 pi
*/
/* Left line */
static const uint8_t RL[5][16] = {
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, /* Round 1: id */
{ 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8 }, /* Round 2: rho */
{ 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12 }, /* Round 3: rho^2 */
{ 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2 }, /* Round 4: rho^3 */
{ 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 } /* Round 5: rho^4 */
};
/* Right line */
static const uint8_t RR[5][16] = {
{ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12 }, /* Round 1: pi */
{ 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2 }, /* Round 2: rho pi */
{ 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13 }, /* Round 3: rho^2 pi */
{ 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14 }, /* Round 4: rho^3 pi */
{ 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 } /* Round 5: rho^4 pi */
};
/*
* Shifts - Since we don't actually re-order the message words according to
* the permutations above (we could, but it would be slower), these tables
* come with the permutations pre-applied.
*/
/* Shifts, left line */
static const uint8_t SL[5][16] = {
{ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8 }, /* Round 1 */
{ 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12 }, /* Round 2 */
{ 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5 }, /* Round 3 */
{ 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12 }, /* Round 4 */
{ 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 } /* Round 5 */
};
/* Shifts, right line */
static const uint8_t SR[5][16] = {
{ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6 }, /* Round 1 */
{ 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11 }, /* Round 2 */
{ 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5 }, /* Round 3 */
{ 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8 }, /* Round 4 */
{ 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 } /* Round 5 */
};
/* Boolean functions */
#define F1(x, y, z) ((x) ^ (y) ^ (z))
#define F2(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define F3(x, y, z) (((x) | ~(y)) ^ (z))
#define F4(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define F5(x, y, z) ((x) ^ ((y) | ~(z)))
/* Round constants, left line */
static const uint32_t KL[5] = {
0x00000000u, /* Round 1: 0 */
0x5A827999u, /* Round 2: floor(2**30 * sqrt(2)) */
0x6ED9EBA1u, /* Round 3: floor(2**30 * sqrt(3)) */
0x8F1BBCDCu, /* Round 4: floor(2**30 * sqrt(5)) */
0xA953FD4Eu /* Round 5: floor(2**30 * sqrt(7)) */
};
/* Round constants, right line */
static const uint32_t KR[5] = {
0x50A28BE6u, /* Round 1: floor(2**30 * cubert(2)) */
0x5C4DD124u, /* Round 2: floor(2**30 * cubert(3)) */
0x6D703EF3u, /* Round 3: floor(2**30 * cubert(5)) */
0x7A6D76E9u, /* Round 4: floor(2**30 * cubert(7)) */
0x00000000u /* Round 5: 0 */
};
static void ripemd160_init(ripemd160_state *self)
{
memcpy(self->h, initial_h, RIPEMD160_DIGEST_SIZE);
memset(&self->buf, 0, sizeof(self->buf));
self->length = 0;
self->bufpos = 0;
self->magic = RIPEMD160_MAGIC;
}
/* NB: This is not currently called in the hash object's destructor. */
static void ripemd160_wipe(ripemd160_state *self)
{
memset(self, 0, sizeof(ripemd160_state));
self->magic = 0;
}
static inline void byteswap32(uint32_t *v)
{
union { uint32_t w; uint8_t b[4]; } x, y;
x.w = *v;
y.b[0] = x.b[3];
y.b[1] = x.b[2];
y.b[2] = x.b[1];
y.b[3] = x.b[0];
*v = y.w;
/* Wipe temporary variables */
x.w = y.w = 0;
}
static inline void byteswap_digest(uint32_t *p)
{
unsigned int i;
for (i = 0; i < 4; i++) {
byteswap32(p++);
byteswap32(p++);
byteswap32(p++);
byteswap32(p++);
}
}
/* The RIPEMD160 compression function. Operates on self->buf */
static void ripemd160_compress(ripemd160_state *self)
{
uint8_t w, round;
uint32_t T;
uint32_t AL, BL, CL, DL, EL; /* left line */
uint32_t AR, BR, CR, DR, ER; /* right line */
/* Sanity check */
assert(self->magic == RIPEMD160_MAGIC);
assert(self->bufpos == 64);
if (self->magic != RIPEMD160_MAGIC || self->bufpos != 64) {
ripemd160_wipe(self);
return; /* error */
}
/* Byte-swap the buffer if we're on a big-endian machine */
#ifdef PCT_BIG_ENDIAN
byteswap_digest(self->buf.w);
#endif
/* Load the left and right lines with the initial state */
AL = AR = self->h[0];
BL = BR = self->h[1];
CL = CR = self->h[2];
DL = DR = self->h[3];
EL = ER = self->h[4];
/* Round 1 */
round = 0;
for (w = 0; w < 16; w++) { /* left line */
T = ROL(SL[round][w], AL + F1(BL, CL, DL) + self->buf.w[RL[round][w]] + KL[round]) + EL;
AL = EL; EL = DL; DL = ROL(10, CL); CL = BL; BL = T;
}
for (w = 0; w < 16; w++) { /* right line */
T = ROL(SR[round][w], AR + F5(BR, CR, DR) + self->buf.w[RR[round][w]] + KR[round]) + ER;
AR = ER; ER = DR; DR = ROL(10, CR); CR = BR; BR = T;
}
/* Round 2 */
round++;
for (w = 0; w < 16; w++) { /* left line */
T = ROL(SL[round][w], AL + F2(BL, CL, DL) + self->buf.w[RL[round][w]] + KL[round]) + EL;
AL = EL; EL = DL; DL = ROL(10, CL); CL = BL; BL = T;
}
for (w = 0; w < 16; w++) { /* right line */
T = ROL(SR[round][w], AR + F4(BR, CR, DR) + self->buf.w[RR[round][w]] + KR[round]) + ER;
AR = ER; ER = DR; DR = ROL(10, CR); CR = BR; BR = T;
}
/* Round 3 */
round++;
for (w = 0; w < 16; w++) { /* left line */
T = ROL(SL[round][w], AL + F3(BL, CL, DL) + self->buf.w[RL[round][w]] + KL[round]) + EL;
AL = EL; EL = DL; DL = ROL(10, CL); CL = BL; BL = T;
}
for (w = 0; w < 16; w++) { /* right line */
T = ROL(SR[round][w], AR + F3(BR, CR, DR) + self->buf.w[RR[round][w]] + KR[round]) + ER;
AR = ER; ER = DR; DR = ROL(10, CR); CR = BR; BR = T;
}
/* Round 4 */
round++;
for (w = 0; w < 16; w++) { /* left line */
T = ROL(SL[round][w], AL + F4(BL, CL, DL) + self->buf.w[RL[round][w]] + KL[round]) + EL;
AL = EL; EL = DL; DL = ROL(10, CL); CL = BL; BL = T;
}
for (w = 0; w < 16; w++) { /* right line */
T = ROL(SR[round][w], AR + F2(BR, CR, DR) + self->buf.w[RR[round][w]] + KR[round]) + ER;
AR = ER; ER = DR; DR = ROL(10, CR); CR = BR; BR = T;
}
/* Round 5 */
round++;
for (w = 0; w < 16; w++) { /* left line */
T = ROL(SL[round][w], AL + F5(BL, CL, DL) + self->buf.w[RL[round][w]] + KL[round]) + EL;
AL = EL; EL = DL; DL = ROL(10, CL); CL = BL; BL = T;
}
for (w = 0; w < 16; w++) { /* right line */
T = ROL(SR[round][w], AR + F1(BR, CR, DR) + self->buf.w[RR[round][w]] + KR[round]) + ER;
AR = ER; ER = DR; DR = ROL(10, CR); CR = BR; BR = T;
}
/* Final mixing stage */
T = self->h[1] + CL + DR;
self->h[1] = self->h[2] + DL + ER;
self->h[2] = self->h[3] + EL + AR;
self->h[3] = self->h[4] + AL + BR;
self->h[4] = self->h[0] + BL + CR;
self->h[0] = T;
/* Clear the buffer and wipe the temporary variables */
T = AL = BL = CL = DL = EL = AR = BR = CR = DR = ER = 0;
memset(&self->buf, 0, sizeof(self->buf));
self->bufpos = 0;
}
static void ripemd160_update(ripemd160_state *self, const unsigned char *p, int length)
{
unsigned int bytes_needed;
/* Some assertions */
assert(self->magic == RIPEMD160_MAGIC);
assert(p != NULL && length >= 0);
/* NDEBUG is probably defined, so check for invalid inputs explicitly. */
if (self->magic != RIPEMD160_MAGIC || p == NULL || length < 0) {
/* error */
ripemd160_wipe(self);
return;
}
/* We never leave a full buffer */
assert(self->bufpos < 64);
while (length > 0) {
/* Figure out how many bytes we need to fill the internal buffer. */
bytes_needed = 64 - self->bufpos;
if ((unsigned int) length >= bytes_needed) {
/* We have enough bytes, so copy them into the internal buffer and run
* the compression function. */
memcpy(&self->buf.b[self->bufpos], p, bytes_needed);
self->bufpos += bytes_needed;
self->length += bytes_needed << 3; /* length is in bits */
p += bytes_needed;
ripemd160_compress(self);
length -= bytes_needed;
continue;
}
/* We do not have enough bytes to fill the internal buffer.
* Copy what's there and return. */
memcpy(&self->buf.b[self->bufpos], p, length);
self->bufpos += length;
self->length += length << 3; /* length is in bits */
return;
}
}
static void ripemd160_copy(const ripemd160_state *source, ripemd160_state *dest)
{
memcpy(dest, source, sizeof(ripemd160_state));
}
static int ripemd160_digest(const ripemd160_state *self, unsigned char *out)
{
ripemd160_state tmp;
assert(self->magic == RIPEMD160_MAGIC);
assert(out != NULL);
if (self->magic != RIPEMD160_MAGIC || out == NULL) {
return 0;
}
ripemd160_copy(self, &tmp);
/* Append the padding */
tmp.buf.b[tmp.bufpos++] = 0x80;
if (tmp.bufpos > 56) {
tmp.bufpos = 64;
ripemd160_compress(&tmp);
}
/* Append the length */
tmp.buf.w[14] = (uint32_t) (tmp.length & 0xFFFFffffu);
tmp.buf.w[15] = (uint32_t) ((tmp.length >> 32) & 0xFFFFffffu);
#ifdef PCT_BIG_ENDIAN
byteswap32(&tmp.buf.w[14]);
byteswap32(&tmp.buf.w[15]);
#endif
tmp.bufpos = 64;
ripemd160_compress(&tmp);
/* Copy the final state into the output buffer */
#ifdef PCT_BIG_ENDIAN
byteswap_digest(tmp.h);
#endif
memcpy(out, &tmp.h, RIPEMD160_DIGEST_SIZE);
if (tmp.magic == RIPEMD160_MAGIC) {
/* success */
ripemd160_wipe(&tmp);
return 1;
} else {
/* error */
ripemd160_wipe(&tmp);
memset(out, 0, RIPEMD160_DIGEST_SIZE);
return 0;
}
}
/* Template definitions */
#define MODULE_NAME _RIPEMD160
#define DIGEST_SIZE RIPEMD160_DIGEST_SIZE
#define hash_state ripemd160_state
#define hash_init ripemd160_init
#define hash_update ripemd160_update
#define hash_copy ripemd160_copy
static PyObject *hash_digest(hash_state *self)
{
char buf[DIGEST_SIZE];
PyObject *retval;
if (ripemd160_digest(self, (unsigned char *) buf)) {
retval = PyBytes_FromStringAndSize(buf, DIGEST_SIZE);
} else {
PyErr_SetString(PyExc_RuntimeError, "Internal error occurred while executing ripemd160_digest");
retval = NULL;
}
memset(buf, 0, DIGEST_SIZE);
return retval;
}
#include "hash_template.c"
/* vim:set ts=4 sw=4 sts=4 expandtab: */

View File

@ -0,0 +1,74 @@
/*
* An implementation of the SHA-224 hash function.
*
* The Federal Information Processing Standards (FIPS) Specification
* can be found here (FIPS 180-3):
* http://csrc.nist.gov/publications/PubsFIPS.html
*
* Written in 2010 by Lorenz Quack <don@amberfisharts.com>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#define MODULE_NAME _SHA224
#define DIGEST_SIZE (224/8)
#define BLOCK_SIZE (512/8)
#define WORD_SIZE 4
#define SCHEDULE_SIZE 64
#include "hash_SHA2.h"
/* Initial Values H */
static const sha2_word_t H[8] = {
0xc1059ed8,
0x367cd507,
0x3070dd17,
0xf70e5939,
0xffc00b31,
0x68581511,
0x64f98fa7,
0xbefa4fa4
};
/* the Constants K */
static const sha2_word_t K[SCHEDULE_SIZE] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
/* SHA-224 specific functions */
#define Sigma0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
#define Sigma1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
#define Gamma0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3))
#define Gamma1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHR(x, 10))
#include "hash_SHA2_template.c"

View File

@ -0,0 +1,73 @@
/*
* An implementation of the SHA-256 hash function.
*
* The Federal Information Processing Standards (FIPS) Specification
* can be found here (FIPS 180-3):
* http://csrc.nist.gov/publications/PubsFIPS.html
*
* Written in 2010 by Lorenz Quack <don@amberfisharts.com>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#define MODULE_NAME _SHA256
#define DIGEST_SIZE (256/8)
#define BLOCK_SIZE (512/8)
#define WORD_SIZE 4
#define SCHEDULE_SIZE 64
#include "hash_SHA2.h"
/* Initial Values H */
static const sha2_word_t H[8] = {
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
};
/* the Constants K */
static const sha2_word_t K[SCHEDULE_SIZE] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
/* SHA-256 specific functions */
#define Sigma0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
#define Sigma1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
#define Gamma0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3))
#define Gamma1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHR(x, 10))
#include "hash_SHA2_template.c"

View File

@ -0,0 +1,80 @@
/*
* An implementation of the SHA-384 hash function.
*
* The Federal Information Processing Standards (FIPS) Specification
* can be found here (FIPS 180-3):
* http://csrc.nist.gov/publications/PubsFIPS.html
*
* Written in 2010 by Lorenz Quack <don@amberfisharts.com>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#define MODULE_NAME _SHA384
#define DIGEST_SIZE (384/8)
#define BLOCK_SIZE (1024/8)
#define WORD_SIZE 8
#define SCHEDULE_SIZE 80
#include "hash_SHA2.h"
/* Initial Values H */
static const sha2_word_t H[8] = {
0xcbbb9d5dc1059ed8,
0x629a292a367cd507,
0x9159015a3070dd17,
0x152fecd8f70e5939,
0x67332667ffc00b31,
0x8eb44a8768581511,
0xdb0c2e0d64f98fa7,
0x47b5481dbefa4fa4
};
/* the Constants K */
static const sha2_word_t K[SCHEDULE_SIZE] = {
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817
};
/* SHA-384 specific functions */
#define Sigma0(x) (ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39))
#define Sigma1(x) (ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41))
#define Gamma0(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHR(x, 7))
#define Gamma1(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHR(x, 6))
#include "hash_SHA2_template.c"

View File

@ -0,0 +1,80 @@
/*
* An implementation of the SHA-512 hash function.
*
* The Federal Information Processing Standards (FIPS) Specification
* can be found here (FIPS 180-3):
* http://csrc.nist.gov/publications/PubsFIPS.html
*
* Written in 2010 by Lorenz Quack <don@amberfisharts.com>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#define MODULE_NAME _SHA512
#define DIGEST_SIZE (512/8)
#define BLOCK_SIZE (1024/8)
#define WORD_SIZE 8
#define SCHEDULE_SIZE 80
#include "hash_SHA2.h"
/* Initial Values H */
static const sha2_word_t H[8] = {
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
0xa54ff53a5f1d36f1,
0x510e527fade682d1,
0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b,
0x5be0cd19137e2179
};
/* the Constants K */
static const sha2_word_t K[SCHEDULE_SIZE] = {
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817
};
/* SHA-512 specific functions */
#define Sigma0(x) (ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39))
#define Sigma1(x) (ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41))
#define Gamma0(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHR(x, 7))
#define Gamma1(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHR(x, 6))
#include "hash_SHA2_template.c"

View File

@ -0,0 +1,76 @@
/*
* xor.c : Source for the trivial cipher which XORs the message with the key.
* The key can be up to 32 bytes long.
*
* Part of the Python Cryptography Toolkit
*
* Contributed by Barry Warsaw and others.
*
* =======================================================================
* The contents of this file are dedicated to the public domain. To the
* extent that dedication to the public domain is not available, everyone
* is granted a worldwide, perpetual, royalty-free, non-exclusive license
* to exercise all rights associated with the contents of this file for
* any purpose whatsoever. No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* =======================================================================
*/
#include "Python.h"
#define MODULE_NAME _XOR
#define BLOCK_SIZE 1
#define KEY_SIZE 0
#define MAX_KEY_SIZE 32
typedef struct
{
unsigned char key[MAX_KEY_SIZE];
int keylen, last_pos;
} stream_state;
static void
stream_init(stream_state *self, unsigned char *key, int len)
{
int i;
if (len > MAX_KEY_SIZE)
{
PyErr_Format(PyExc_ValueError,
"XOR key must be no longer than %d bytes",
MAX_KEY_SIZE);
return;
}
self->keylen = len;
self->last_pos = 0;
for(i=0; i<len; i++)
{
self->key[i] = key[i];
}
}
/* Encryption and decryption are symmetric */
#define stream_decrypt stream_encrypt
static void stream_encrypt(stream_state *self, unsigned char *block,
int len)
{
int i, j = self->last_pos;
for(i=0; i<len; i++, j=(j+1) % self->keylen)
{
block[i] ^= self->key[j];
}
self->last_pos = j;
}
#include "stream_template.c"

View File

@ -0,0 +1,584 @@
/*
* _counter.c: Fast counter for use with CTR-mode ciphers
*
* Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*/
#include <assert.h>
#include <stddef.h>
#include <string.h>
#include "Python.h"
#include "pycrypto_compat.h"
#include "_counter.h"
#ifndef IS_PY3K
#define PyLong_FromLong PyInt_FromLong
#endif
/* NB: This can be called multiple times for a given object, via the __init__ method. Be careful. */
static int
CounterObject_init(PCT_CounterObject *self, PyObject *args, PyObject *kwargs)
{
#ifdef IS_PY3K
PyBytesObject *prefix=NULL, *suffix=NULL, *initval=NULL;
#else
PyStringObject *prefix=NULL, *suffix=NULL, *initval=NULL;
#endif
int allow_wraparound = 0;
int disable_shortcut = 0;
Py_ssize_t size;
static char *kwlist[] = {"prefix", "suffix", "initval", "allow_wraparound", "disable_shortcut", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "SSS|ii", kwlist, &prefix, &suffix, &initval, &allow_wraparound, &disable_shortcut))
return -1;
/* Check string size and set nbytes */
size = PyBytes_GET_SIZE(initval);
if (size < 1) {
PyErr_SetString(PyExc_ValueError, "initval length too small (must be >= 1 byte)");
return -1;
} else if (size > 0xffff) {
PyErr_SetString(PyExc_ValueError, "initval length too large (must be <= 65535 bytes)");
return -1;
}
self->nbytes = (uint16_t) size;
/* Check prefix length */
size = PyBytes_GET_SIZE(prefix);
assert(size >= 0);
if (size > 0xffff) {
PyErr_SetString(PyExc_ValueError, "prefix length too large (must be <= 65535 bytes)");
return -1;
}
/* Check suffix length */
size = PyBytes_GET_SIZE(suffix);
assert(size >= 0);
if (size > 0xffff) {
PyErr_SetString(PyExc_ValueError, "suffix length too large (must be <= 65535 bytes)");
return -1;
}
/* Set prefix, being careful to properly discard any old reference */
Py_CLEAR(self->prefix);
Py_INCREF(prefix);
self->prefix = prefix;
/* Set prefix, being careful to properly discard any old reference */
Py_CLEAR(self->suffix);
Py_INCREF(suffix);
self->suffix = suffix;
/* Free old buffer (if any) */
if (self->val) {
PyMem_Free(self->val);
self->val = self->p = NULL;
self->buf_size = 0;
}
/* Allocate new buffer */
/* buf_size won't overflow because the length of each string will always be <= 0xffff */
self->buf_size = PyBytes_GET_SIZE(prefix) + PyBytes_GET_SIZE(suffix) + self->nbytes;
self->val = self->p = PyMem_Malloc(self->buf_size);
if (self->val == NULL) {
self->buf_size = 0;
return -1;
}
self->p = self->val + PyBytes_GET_SIZE(prefix);
/* Sanity-check pointers */
assert(self->val <= self->p);
assert(self->p + self->nbytes <= self->val + self->buf_size);
assert(self->val + PyBytes_GET_SIZE(self->prefix) == self->p);
assert(PyBytes_GET_SIZE(self->prefix) + self->nbytes + PyBytes_GET_SIZE(self->suffix) == self->buf_size);
/* Copy the prefix, suffix, and initial value into the buffer. */
memcpy(self->val, PyBytes_AS_STRING(prefix), PyBytes_GET_SIZE(prefix));
memcpy(self->p, PyBytes_AS_STRING(initval), self->nbytes);
memcpy(self->p + self->nbytes, PyBytes_AS_STRING(suffix), PyBytes_GET_SIZE(suffix));
/* Set shortcut_disabled and allow_wraparound */
self->shortcut_disabled = disable_shortcut;
self->allow_wraparound = allow_wraparound;
/* Clear the carry flag */
self->carry = 0;
return 0;
}
static void
CounterObject_dealloc(PCT_CounterObject *self)
{
/* Free the buffer */
if (self->val) {
memset(self->val, 0, self->buf_size); /* wipe the buffer before freeing it */
PyMem_Free(self->val);
self->val = self->p = NULL;
self->buf_size = 0;
}
/* Deallocate the prefix and suffix, if they are present. */
Py_CLEAR(self->prefix);
Py_CLEAR(self->suffix);
/* Free this object */
PyObject_Del(self);
}
static inline PyObject *
_CounterObject_next_value(PCT_CounterObject *self, int little_endian)
{
unsigned int i;
int increment;
uint8_t *p;
PyObject *eight = NULL;
PyObject *ch = NULL;
PyObject *y = NULL;
PyObject *x = NULL;
if (self->carry && !self->allow_wraparound) {
PyErr_SetString(PyExc_OverflowError,
"counter wrapped without allow_wraparound");
goto err_out;
}
eight = PyLong_FromLong(8);
if (!eight)
goto err_out;
/* Make a new Python long integer */
x = PyLong_FromUnsignedLong(0);
if (!x)
goto err_out;
if (little_endian) {
/* little endian */
p = self->p + self->nbytes - 1;
increment = -1;
} else {
/* big endian */
p = self->p;
increment = 1;
}
for (i = 0; i < self->nbytes; i++, p += increment) {
/* Sanity check pointer */
assert(self->p <= p);
assert(p < self->p + self->nbytes);
/* ch = ord(p) */
Py_CLEAR(ch); /* delete old ch */
ch = PyLong_FromLong((long) *p);
if (!ch)
goto err_out;
/* y = x << 8 */
Py_CLEAR(y); /* delete old y */
y = PyNumber_Lshift(x, eight);
if (!y)
goto err_out;
/* x = y | ch */
Py_CLEAR(x); /* delete old x */
x = PyNumber_Or(y, ch);
}
Py_CLEAR(eight);
Py_CLEAR(ch);
Py_CLEAR(y);
return x;
err_out:
Py_CLEAR(eight);
Py_CLEAR(ch);
Py_CLEAR(y);
Py_CLEAR(x);
return NULL;
}
static PyObject *
CounterLEObject_next_value(PCT_CounterObject *self, PyObject *args)
{
return _CounterObject_next_value(self, 1);
}
static PyObject *
CounterBEObject_next_value(PCT_CounterObject *self, PyObject *args)
{
return _CounterObject_next_value(self, 0);
}
static void
CounterLEObject_increment(PCT_CounterObject *self)
{
unsigned int i, tmp, carry;
uint8_t *p;
assert(sizeof(i) >= sizeof(self->nbytes));
carry = 1;
p = self->p;
for (i = 0; i < self->nbytes; i++, p++) {
/* Sanity check pointer */
assert(self->p <= p);
assert(p < self->p + self->nbytes);
tmp = *p + carry;
carry = tmp >> 8; /* This will only ever be 0 or 1 */
*p = tmp & 0xff;
}
self->carry = carry;
}
static void
CounterBEObject_increment(PCT_CounterObject *self)
{
unsigned int i, tmp, carry;
uint8_t *p;
assert(sizeof(i) >= sizeof(self->nbytes));
carry = 1;
p = self->p + self->nbytes-1;
for (i = 0; i < self->nbytes; i++, p--) {
/* Sanity check pointer */
assert(self->p <= p);
assert(p < self->p + self->nbytes);
tmp = *p + carry;
carry = tmp >> 8; /* This will only ever be 0 or 1 */
*p = tmp & 0xff;
}
self->carry = carry;
}
static PyObject *
CounterObject_call(PCT_CounterObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *retval;
if (self->carry && !self->allow_wraparound) {
PyErr_SetString(PyExc_OverflowError,
"counter wrapped without allow_wraparound");
return NULL;
}
retval = (PyObject *)PyBytes_FromStringAndSize((const char *)self->val, self->buf_size);
self->inc_func(self);
return retval;
}
static PyMethodDef CounterLEObject_methods[] = {
{"next_value", (PyCFunction)CounterLEObject_next_value, METH_VARARGS,
"Get the numerical value of next value of the counter."},
{NULL} /* sentinel */
};
static PyMethodDef CounterBEObject_methods[] = {
{"next_value", (PyCFunction)CounterBEObject_next_value, METH_VARARGS,
"Get the numerical value of next value of the counter."},
{NULL} /* sentinel */
};
/* Python 2.1 doesn't allow us to assign methods or attributes to an object,
* so we hack it here. */
static PyObject *
#ifdef IS_PY3K
CounterLEObject_getattro(PyObject *s, PyObject *attr)
#else
CounterLEObject_getattr(PyObject *s, char *name)
#endif
{
PCT_CounterObject *self = (PCT_CounterObject *)s;
#ifdef IS_PY3K
if (!PyUnicode_Check(attr))
goto generic;
if (PyUnicode_CompareWithASCIIString(attr, "carry") == 0) {
#else
if (strcmp(name, "carry") == 0) {
#endif
return PyLong_FromLong((long)self->carry);
#ifdef IS_PY3K
} else if (!self->shortcut_disabled && PyUnicode_CompareWithASCIIString(attr, "__PCT_CTR_SHORTCUT__") == 0) {
#else
} else if (!self->shortcut_disabled && strcmp(name, "__PCT_CTR_SHORTCUT__") == 0) {
#endif
/* Shortcut hack - See block_template.c */
Py_INCREF(Py_True);
return Py_True;
}
#ifdef IS_PY3K
generic:
return PyObject_GenericGetAttr(s, attr);
#else
return Py_FindMethod(CounterLEObject_methods, (PyObject *)self, name);
#endif
}
static PyObject *
#ifdef IS_PY3K
CounterBEObject_getattro(PyObject *s, PyObject *attr)
#else
CounterBEObject_getattr(PyObject *s, char *name)
#endif
{
PCT_CounterObject *self = (PCT_CounterObject *)s;
#ifdef IS_PY3K
if (!PyUnicode_Check(attr))
goto generic;
if (PyUnicode_CompareWithASCIIString(attr, "carry") == 0) {
#else
if (strcmp(name, "carry") == 0) {
#endif
return PyLong_FromLong((long)self->carry);
#ifdef IS_PY3K
} else if (!self->shortcut_disabled && PyUnicode_CompareWithASCIIString(attr, "__PCT_CTR_SHORTCUT__") == 0) {
#else
} else if (!self->shortcut_disabled && strcmp(name, "__PCT_CTR_SHORTCUT__") == 0) {
#endif
/* Shortcut hack - See block_template.c */
Py_INCREF(Py_True);
return Py_True;
}
#ifdef IS_PY3K
generic:
return PyObject_GenericGetAttr(s, attr);
#else
return Py_FindMethod(CounterBEObject_methods, (PyObject *)self, name);
#endif
}
static PyTypeObject
my_CounterLEType = {
#ifdef IS_PY3K
PyVarObject_HEAD_INIT(NULL, 0) /* deferred type init for compilation on Windows, type will be filled in at runtime */
#else
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
#endif
"_counter.CounterLE", /* tp_name */
sizeof(PCT_CounterObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)CounterObject_dealloc, /* tp_dealloc */
0, /* tp_print */
#ifdef IS_PY3K
0, /* tp_getattr */
#else
CounterLEObject_getattr, /* tp_getattr */
#endif
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)CounterObject_call, /* tp_call */
0, /* tp_str */
#ifdef IS_PY3K
CounterLEObject_getattro, /* tp_getattro */
#else
0, /* tp_getattro */
#endif
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"Counter (little endian)", /* tp_doc */
#ifdef IS_PY3K
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
CounterLEObject_methods, /*tp_methods*/
#endif
};
static PyTypeObject
my_CounterBEType = {
#ifdef IS_PY3K
PyVarObject_HEAD_INIT(NULL, 0) /* deferred type init for compilation on Windows, type will be filled in at runtime */
#else
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
#endif
"_counter.CounterBE", /* tp_name */
sizeof(PCT_CounterObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)CounterObject_dealloc, /* tp_dealloc */
0, /* tp_print */
#ifdef IS_PY3K
0, /* tp_getattr */
#else
CounterBEObject_getattr, /* tp_getattr */
#endif
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)CounterObject_call, /* tp_call */
0, /* tp_str */
#ifdef IS_PY3K
CounterBEObject_getattro, /* tp_getattro */
#else
0, /* tp_getattro */
#endif
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"Counter (big endian)", /* tp_doc */
#ifdef IS_PY3K
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
CounterBEObject_methods, /*tp_methods*/
#endif
};
/*
* Python 2.1 doesn't seem to allow a C equivalent of the __init__ method, so
* we use the module-level functions newLE and newBE here.
*/
static PyObject *
CounterLE_new(PyObject *self, PyObject *args, PyObject *kwargs)
{
PCT_CounterObject *obj = NULL;
/* Create the new object */
obj = PyObject_New(PCT_CounterObject, &my_CounterLEType);
if (obj == NULL) {
return NULL;
}
/* Zero the custom portion of the structure */
memset(&obj->prefix, 0, sizeof(PCT_CounterObject) - offsetof(PCT_CounterObject, prefix));
/* Call the object's initializer. Delete the object if this fails. */
if (CounterObject_init(obj, args, kwargs) != 0) {
return NULL;
}
/* Set the inc_func pointer */
obj->inc_func = (void (*)(void *))CounterLEObject_increment;
/* Return the object */
return (PyObject *)obj;
}
static PyObject *
CounterBE_new(PyObject *self, PyObject *args, PyObject *kwargs)
{
PCT_CounterObject *obj = NULL;
/* Create the new object */
obj = PyObject_New(PCT_CounterObject, &my_CounterBEType);
if (obj == NULL) {
return NULL;
}
/* Zero the custom portion of the structure */
memset(&obj->prefix, 0, sizeof(PCT_CounterObject) - offsetof(PCT_CounterObject, prefix));
/* Call the object's initializer. Delete the object if this fails. */
if (CounterObject_init(obj, args, kwargs) != 0) {
return NULL;
}
/* Set the inc_func pointer */
obj->inc_func = (void (*)(void *))CounterBEObject_increment;
/* Return the object */
return (PyObject *)obj;
}
/*
* Module-level method table and module initialization function
*/
static PyMethodDef module_methods[] = {
{"_newLE", (PyCFunction) CounterLE_new, METH_VARARGS|METH_KEYWORDS, NULL},
{"_newBE", (PyCFunction) CounterBE_new, METH_VARARGS|METH_KEYWORDS, NULL},
{NULL, NULL, 0, NULL} /* end-of-list sentinel value */
};
#ifdef IS_PY3K
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_counter",
NULL,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
};
#endif
PyMODINIT_FUNC
#ifdef IS_PY3K
PyInit__counter(void)
#else
init_counter(void)
#endif
{
PyObject *m;
/* TODO - Is the error handling here correct? */
#ifdef IS_PY3K
/* PyType_Ready automatically fills in ob_type with &PyType_Type if it's not already set */
if (PyType_Ready(&my_CounterLEType) < 0)
return NULL;
if (PyType_Ready(&my_CounterBEType) < 0)
return NULL;
/* Initialize the module */
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
return m;
#else
m = Py_InitModule("_counter", module_methods);
if (m == NULL)
return;
my_CounterLEType.ob_type = &PyType_Type;
my_CounterBEType.ob_type = &PyType_Type;
#endif
}
/* vim:set ts=4 sw=4 sts=4 expandtab: */

View File

@ -0,0 +1,50 @@
/*
* _counter.h: Fast counter for use with CTR-mode ciphers
*
* Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*/
#ifndef PCT__COUNTER_H
#define PCT__COUNTER_H
#include "config.h"
#if HAVE_STDINT_H
# include <stdint.h>
#elif defined(__sun) || defined(__sun__)
# include <sys/inttypes.h>
#else
# error "stdint.h not found"
#endif
typedef struct {
PyObject_HEAD
PyBytesObject *prefix; /* Prefix (useful for a nonce) */
PyBytesObject *suffix; /* Suffix (useful for a nonce) */
uint8_t *val; /* Buffer for our output string */
uint32_t buf_size; /* Size of the buffer */
uint8_t *p; /* Pointer to the part of the buffer that we're allowed to update */
uint16_t nbytes; /* The number of bytes that from .p that are part of the counter */
void (*inc_func)(void *); /* Pointer to the counter increment function */
int shortcut_disabled; /* This gets set to a non-zero value when the shortcut mechanism is disabled */
int carry; /* This gets set by Counter*Object_increment when the counter wraps around */
int allow_wraparound; /* When this is false, we raise OverflowError on next_value() or __call__() when the counter wraps around */
} PCT_CounterObject;
#endif /* PCT__COUNTER_H */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,821 @@
/* -*- C -*- */
/*
* block_template.c : Generic framework for block encryption algorithms
*
* Written by Andrew Kuchling and others
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef _HAVE_STDC_HEADERS
#include <string.h>
#endif
#include "Python.h"
#include "pycrypto_compat.h"
#include "modsupport.h"
#include "_counter.h"
/* Cipher operation modes */
#define MODE_ECB 1
#define MODE_CBC 2
#define MODE_CFB 3
#define MODE_PGP 4
#define MODE_OFB 5
#define MODE_CTR 6
#define _STR(x) #x
#define _XSTR(x) _STR(x)
#define _PASTE(x,y) x##y
#define _PASTE2(x,y) _PASTE(x,y)
#ifdef IS_PY3K
#define _MODULE_NAME _PASTE2(PyInit_,MODULE_NAME)
#else
#define _MODULE_NAME _PASTE2(init,MODULE_NAME)
#endif
#define _MODULE_STRING _XSTR(MODULE_NAME)
typedef struct
{
PyObject_HEAD
int mode, count, segment_size;
unsigned char IV[BLOCK_SIZE], oldCipher[BLOCK_SIZE];
PyObject *counter;
int counter_shortcut;
block_state st;
} ALGobject;
/* Please see PEP3123 for a discussion of PyObject_HEAD and changes made in 3.x to make it conform to Standard C.
* These changes also dictate using Py_TYPE to check type, and PyVarObject_HEAD_INIT(NULL, 0) to initialize
*/
#ifdef IS_PY3K
static PyTypeObject ALGtype;
#define is_ALGobject(v) (Py_TYPE(v) == &ALGtype)
#else
staticforward PyTypeObject ALGtype;
#define is_ALGobject(v) ((v)->ob_type == &ALGtype)
#define PyLong_FromLong PyInt_FromLong /* For Python 2.x */
#endif
static ALGobject *
newALGobject(void)
{
ALGobject * new;
new = PyObject_New(ALGobject, &ALGtype);
new->mode = MODE_ECB;
new->counter = NULL;
new->counter_shortcut = 0;
return new;
}
static void
ALGdealloc(PyObject *ptr)
{
ALGobject *self = (ALGobject *)ptr;
/* Overwrite the contents of the object */
Py_XDECREF(self->counter);
self->counter = NULL;
memset(self->IV, 0, BLOCK_SIZE);
memset(self->oldCipher, 0, BLOCK_SIZE);
memset((char*)&(self->st), 0, sizeof(block_state));
self->mode = self->count = self->segment_size = 0;
PyObject_Del(ptr);
}
static char ALGnew__doc__[] =
"new(key, [mode], [IV]): Return a new " _MODULE_STRING " encryption object.";
static char *kwlist[] = {"key", "mode", "IV", "counter", "segment_size",
#ifdef PCT_ARC2_MODULE
"effective_keylen",
#endif
NULL};
static ALGobject *
ALGnew(PyObject *self, PyObject *args, PyObject *kwdict)
{
unsigned char *key, *IV;
ALGobject * new=NULL;
int keylen, IVlen=0, mode=MODE_ECB, segment_size=0;
PyObject *counter = NULL;
int counter_shortcut = 0;
#ifdef PCT_ARC2_MODULE
int effective_keylen = 1024; /* this is a weird default, but it's compatible with old versions of PyCrypto */
#endif
/* Set default values */
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s#|is#Oi"
#ifdef PCT_ARC2_MODULE
"i"
#endif
, kwlist,
&key, &keylen, &mode, &IV, &IVlen,
&counter, &segment_size
#ifdef PCT_ARC2_MODULE
, &effective_keylen
#endif
))
{
return NULL;
}
if (mode<MODE_ECB || mode>MODE_CTR)
{
PyErr_Format(PyExc_ValueError,
"Unknown cipher feedback mode %i",
mode);
return NULL;
}
if (mode == MODE_PGP) {
PyErr_Format(PyExc_ValueError,
"MODE_PGP is not supported anymore");
return NULL;
}
if (KEY_SIZE!=0 && keylen!=KEY_SIZE)
{
PyErr_Format(PyExc_ValueError,
"Key must be %i bytes long, not %i",
KEY_SIZE, keylen);
return NULL;
}
if (KEY_SIZE==0 && keylen==0)
{
PyErr_SetString(PyExc_ValueError,
"Key cannot be the null string");
return NULL;
}
if (IVlen != BLOCK_SIZE && mode != MODE_ECB && mode != MODE_CTR)
{
PyErr_Format(PyExc_ValueError,
"IV must be %i bytes long", BLOCK_SIZE);
return NULL;
}
/* Mode-specific checks */
if (mode == MODE_CFB) {
if (segment_size == 0) segment_size = 8;
if (segment_size < 1 || segment_size > BLOCK_SIZE*8 || ((segment_size & 7) != 0)) {
PyErr_Format(PyExc_ValueError,
"segment_size must be multiple of 8 (bits) "
"between 1 and %i", BLOCK_SIZE*8);
return NULL;
}
}
if (mode == MODE_CTR) {
if (counter == NULL) {
PyErr_SetString(PyExc_TypeError,
"'counter' keyword parameter is required with CTR mode");
return NULL;
#ifdef IS_PY3K
} else if (PyObject_HasAttr(counter, PyUnicode_FromString("__PCT_CTR_SHORTCUT__"))) {
#else
} else if (PyObject_HasAttrString(counter, "__PCT_CTR_SHORTCUT__")) {
#endif
counter_shortcut = 1;
} else if (!PyCallable_Check(counter)) {
PyErr_SetString(PyExc_ValueError,
"'counter' parameter must be a callable object");
return NULL;
}
} else {
if (counter != NULL) {
PyErr_SetString(PyExc_ValueError,
"'counter' parameter only useful with CTR mode");
return NULL;
}
}
/* Cipher-specific checks */
#ifdef PCT_ARC2_MODULE
if (effective_keylen<0 || effective_keylen>1024) {
PyErr_Format(PyExc_ValueError,
"RC2: effective_keylen must be between 0 and 1024, not %i",
effective_keylen);
return NULL;
}
#endif
/* Copy parameters into object */
new = newALGobject();
new->segment_size = segment_size;
new->counter = counter;
Py_XINCREF(counter);
new->counter_shortcut = counter_shortcut;
#ifdef PCT_ARC2_MODULE
new->st.effective_keylen = effective_keylen;
#endif
block_init(&(new->st), key, keylen);
if (PyErr_Occurred())
{
Py_DECREF(new);
return NULL;
}
memset(new->IV, 0, BLOCK_SIZE);
memset(new->oldCipher, 0, BLOCK_SIZE);
memcpy(new->IV, IV, IVlen);
new->mode = mode;
new->count=BLOCK_SIZE; /* stores how many bytes in new->oldCipher have been used */
return new;
}
static char ALG_Encrypt__doc__[] =
"Encrypt the provided string of binary data.";
static PyObject *
ALG_Encrypt(ALGobject *self, PyObject *args)
{
unsigned char *buffer, *str;
unsigned char temp[BLOCK_SIZE];
int i, j, len;
PyObject *result;
if (!PyArg_Parse(args, "s#", &str, &len))
return NULL;
if (len==0) /* Handle empty string */
{
return PyBytes_FromStringAndSize(NULL, 0);
}
if ( (len % BLOCK_SIZE) !=0 &&
(self->mode!=MODE_CFB) &&
(self->mode!=MODE_CTR))
{
PyErr_Format(PyExc_ValueError,
"Input strings must be "
"a multiple of %i in length",
BLOCK_SIZE);
return NULL;
}
if (self->mode == MODE_CFB &&
(len % (self->segment_size/8) !=0)) {
PyErr_Format(PyExc_ValueError,
"Input strings must be a multiple of "
"the segment size %i in length",
self->segment_size/8);
return NULL;
}
buffer=malloc(len);
if (buffer==NULL)
{
PyErr_SetString(PyExc_MemoryError,
"No memory available in "
_MODULE_STRING " encrypt");
return NULL;
}
Py_BEGIN_ALLOW_THREADS;
switch(self->mode)
{
case(MODE_ECB):
for(i=0; i<len; i+=BLOCK_SIZE)
{
block_encrypt(&(self->st), str+i, buffer+i);
}
break;
case(MODE_CBC):
for(i=0; i<len; i+=BLOCK_SIZE)
{
for(j=0; j<BLOCK_SIZE; j++)
{
temp[j]=str[i+j]^self->IV[j];
}
block_encrypt(&(self->st), temp, buffer+i);
memcpy(self->IV, buffer+i, BLOCK_SIZE);
}
break;
case(MODE_CFB):
for(i=0; i<len; i+=self->segment_size/8)
{
block_encrypt(&(self->st), self->IV, temp);
for (j=0; j<self->segment_size/8; j++) {
buffer[i+j] = str[i+j] ^ temp[j];
}
if (self->segment_size == BLOCK_SIZE * 8) {
/* s == b: segment size is identical to
the algorithm block size */
memcpy(self->IV, buffer + i, BLOCK_SIZE);
}
else if ((self->segment_size % 8) == 0) {
int sz = self->segment_size/8;
memmove(self->IV, self->IV + sz,
BLOCK_SIZE-sz);
memcpy(self->IV + BLOCK_SIZE - sz, buffer + i,
sz);
}
else {
/* segment_size is not a multiple of 8;
currently this can't happen */
}
}
break;
case(MODE_OFB):
for(i=0; i<len; i+=BLOCK_SIZE)
{
block_encrypt(&(self->st), self->IV, temp);
memcpy(self->IV, temp, BLOCK_SIZE);
for(j=0; j<BLOCK_SIZE; j++)
{
buffer[i+j] = str[i+j] ^ temp[j];
}
}
break;
case(MODE_CTR):
/* CTR mode is a stream cipher whose keystream is generated by encrypting unique counter values.
* - self->counter points to the Counter callable, which is
* responsible for generating keystream blocks
* - self->count indicates the current offset within the current keystream block
* - self->IV stores the current keystream block
* - str stores the input string
* - buffer stores the output string
* - len indicates the length if the input and output strings
* - i indicates the current offset within the input and output strings
* - (len-i) is the number of bytes remaining to encrypt
* - (BLOCK_SIZE-self->count) is the number of bytes remaining in the current keystream block
*/
i = 0;
while (i < len) {
/* If we don't need more than what remains of the current keystream block, then just XOR it in */
if (len-i <= BLOCK_SIZE-self->count) { /* remaining_bytes_to_encrypt <= remaining_bytes_in_IV */
/* XOR until the input is used up */
for(j=0; j<(len-i); j++) {
assert(i+j < len);
assert(self->count+j < BLOCK_SIZE);
buffer[i+j] = (self->IV[self->count+j] ^= str[i+j]);
}
self->count += len-i;
i = len;
continue;
}
/* Use up the current keystream block */
for(j=0; j<BLOCK_SIZE-self->count; j++) {
assert(i+j < len);
assert(self->count+j < BLOCK_SIZE);
buffer[i+j] = (self->IV[self->count+j] ^= str[i+j]);
}
i += BLOCK_SIZE-self->count;
self->count = BLOCK_SIZE;
/* Generate a new keystream block */
if (self->counter_shortcut) {
/* CTR mode shortcut: If we're using Util.Counter,
* bypass the normal Python function call mechanism
* and manipulate the counter directly. */
PCT_CounterObject *ctr = (PCT_CounterObject *)(self->counter);
if (ctr->carry && !ctr->allow_wraparound) {
Py_BLOCK_THREADS;
PyErr_SetString(PyExc_OverflowError,
"counter wrapped without allow_wraparound");
free(buffer);
return NULL;
}
if (ctr->buf_size != BLOCK_SIZE) {
Py_BLOCK_THREADS;
PyErr_Format(PyExc_TypeError,
"CTR counter function returned "
"string not of length %i",
BLOCK_SIZE);
free(buffer);
return NULL;
}
block_encrypt(&(self->st),
(unsigned char *)ctr->val,
self->IV);
ctr->inc_func(ctr);
} else {
PyObject *ctr;
Py_BLOCK_THREADS;
ctr = PyObject_CallObject(self->counter, NULL);
if (ctr == NULL) {
free(buffer);
return NULL;
}
if (!PyBytes_Check(ctr))
{
PyErr_SetString(PyExc_TypeError,
#ifdef IS_PY3K
"CTR counter function didn't return bytes");
#else
"CTR counter function didn't return a string");
#endif
Py_DECREF(ctr);
free(buffer);
return NULL;
}
if (PyBytes_Size(ctr) != BLOCK_SIZE) {
PyErr_Format(PyExc_TypeError,
"CTR counter function returned "
#ifdef IS_PY3K
"bytes not of length %i",
#else
"string not of length %i",
#endif
BLOCK_SIZE);
Py_DECREF(ctr);
free(buffer);
return NULL;
}
Py_UNBLOCK_THREADS;
block_encrypt(&(self->st), (unsigned char *)PyBytes_AsString(ctr),
self->IV);
Py_BLOCK_THREADS;
Py_DECREF(ctr);
Py_UNBLOCK_THREADS;
}
/* Move the pointer to the start of the keystream block */
self->count = 0;
}
break;
default:
Py_BLOCK_THREADS;
PyErr_Format(PyExc_SystemError,
"Unknown ciphertext feedback mode %i; "
"this shouldn't happen",
self->mode);
free(buffer);
return NULL;
}
Py_END_ALLOW_THREADS;
result=PyBytes_FromStringAndSize((char *) buffer, len);
free(buffer);
return(result);
}
static char ALG_Decrypt__doc__[] =
"decrypt(string): Decrypt the provided string of binary data.";
static PyObject *
ALG_Decrypt(ALGobject *self, PyObject *args)
{
unsigned char *buffer, *str;
unsigned char temp[BLOCK_SIZE];
int i, j, len;
PyObject *result;
/* CTR mode decryption is identical to encryption */
if (self->mode == MODE_CTR)
return ALG_Encrypt(self, args);
if (!PyArg_Parse(args, "s#", &str, &len))
return NULL;
if (len==0) /* Handle empty string */
{
return PyBytes_FromStringAndSize(NULL, 0);
}
if ( (len % BLOCK_SIZE) !=0 && (self->mode!=MODE_CFB))
{
PyErr_Format(PyExc_ValueError,
"Input strings must be "
"a multiple of %i in length",
BLOCK_SIZE);
return NULL;
}
if (self->mode == MODE_CFB &&
(len % (self->segment_size/8) !=0)) {
PyErr_Format(PyExc_ValueError,
"Input strings must be a multiple of "
"the segment size %i in length",
self->segment_size/8);
return NULL;
}
buffer=malloc(len);
if (buffer==NULL)
{
PyErr_SetString(PyExc_MemoryError,
"No memory available in " _MODULE_STRING
" decrypt");
return NULL;
}
Py_BEGIN_ALLOW_THREADS;
switch(self->mode)
{
case(MODE_ECB):
for(i=0; i<len; i+=BLOCK_SIZE)
{
block_decrypt(&(self->st), str+i, buffer+i);
}
break;
case(MODE_CBC):
for(i=0; i<len; i+=BLOCK_SIZE)
{
memcpy(self->oldCipher, self->IV, BLOCK_SIZE);
block_decrypt(&(self->st), str+i, temp);
for(j=0; j<BLOCK_SIZE; j++)
{
buffer[i+j]=temp[j]^self->IV[j];
self->IV[j]=str[i+j];
}
}
break;
case(MODE_CFB):
for(i=0; i<len; i+=self->segment_size/8)
{
block_encrypt(&(self->st), self->IV, temp);
for (j=0; j<self->segment_size/8; j++) {
buffer[i+j] = str[i+j]^temp[j];
}
if (self->segment_size == BLOCK_SIZE * 8) {
/* s == b: segment size is identical to
the algorithm block size */
memcpy(self->IV, str + i, BLOCK_SIZE);
}
else if ((self->segment_size % 8) == 0) {
int sz = self->segment_size/8;
memmove(self->IV, self->IV + sz,
BLOCK_SIZE-sz);
memcpy(self->IV + BLOCK_SIZE - sz, str + i,
sz);
}
else {
/* segment_size is not a multiple of 8;
currently this can't happen */
}
}
break;
case (MODE_OFB):
for(i=0; i<len; i+=BLOCK_SIZE)
{
block_encrypt(&(self->st), self->IV, temp);
memcpy(self->IV, temp, BLOCK_SIZE);
for(j=0; j<BLOCK_SIZE; j++)
{
buffer[i+j] = str[i+j] ^ self->IV[j];
}
}
break;
default:
Py_BLOCK_THREADS;
PyErr_Format(PyExc_SystemError,
"Unknown ciphertext feedback mode %i; "
"this shouldn't happen",
self->mode);
free(buffer);
return NULL;
}
Py_END_ALLOW_THREADS;
result=PyBytes_FromStringAndSize((char *) buffer, len);
free(buffer);
return(result);
}
/* ALG object methods */
static PyMethodDef ALGmethods[] =
{
#ifdef IS_PY3K
{"encrypt", (PyCFunction) ALG_Encrypt, METH_O, ALG_Encrypt__doc__},
{"decrypt", (PyCFunction) ALG_Decrypt, METH_O, ALG_Decrypt__doc__},
#else
{"encrypt", (PyCFunction) ALG_Encrypt, 0, ALG_Encrypt__doc__},
{"decrypt", (PyCFunction) ALG_Decrypt, 0, ALG_Decrypt__doc__},
#endif
{NULL, NULL} /* sentinel */
};
static int
ALGsetattr(PyObject *ptr, char *name, PyObject *v)
{
ALGobject *self=(ALGobject *)ptr;
if (strcmp(name, "IV") != 0)
{
PyErr_Format(PyExc_AttributeError,
"non-existent block cipher object attribute '%s'",
name);
return -1;
}
if (v==NULL)
{
PyErr_SetString(PyExc_AttributeError,
"Can't delete IV attribute of block cipher object");
return -1;
}
if (!PyBytes_Check(v))
{
PyErr_SetString(PyExc_TypeError,
#ifdef IS_PY3K
"IV attribute of block cipher object must be bytes");
#else
"IV attribute of block cipher object must be string");
#endif
return -1;
}
if (PyBytes_Size(v)!=BLOCK_SIZE)
{
PyErr_Format(PyExc_ValueError,
_MODULE_STRING " IV must be %i bytes long",
BLOCK_SIZE);
return -1;
}
memcpy(self->IV, PyBytes_AsString(v), BLOCK_SIZE);
return 0;
}
static PyObject *
#ifdef IS_PY3K
ALGgetattro(PyObject *s, PyObject *attr)
#else
ALGgetattr(PyObject *s, char *name)
#endif
{
ALGobject *self = (ALGobject*)s;
#ifdef IS_PY3K
if (!PyUnicode_Check(attr))
goto generic;
if (PyUnicode_CompareWithASCIIString(attr, "IV") == 0)
#else
if (strcmp(name, "IV") == 0)
#endif
{
return(PyBytes_FromStringAndSize((char *) self->IV, BLOCK_SIZE));
}
#ifdef IS_PY3K
if (PyUnicode_CompareWithASCIIString(attr, "mode") == 0)
#else
if (strcmp(name, "mode") == 0)
#endif
{
return(PyLong_FromLong((long)(self->mode)));
}
#ifdef IS_PY3K
if (PyUnicode_CompareWithASCIIString(attr, "block_size") == 0)
#else
if (strcmp(name, "block_size") == 0)
#endif
{
return PyLong_FromLong(BLOCK_SIZE);
}
#ifdef IS_PY3K
if (PyUnicode_CompareWithASCIIString(attr, "key_size") == 0)
#else
if (strcmp(name, "key_size") == 0)
#endif
{
return PyLong_FromLong(KEY_SIZE);
}
#ifdef IS_PY3K
generic:
return PyObject_GenericGetAttr(s, attr);
#else
return Py_FindMethod(ALGmethods, (PyObject *) self, name);
#endif
}
/* List of functions defined in the module */
static struct PyMethodDef modulemethods[] =
{
{"new", (PyCFunction) ALGnew, METH_VARARGS|METH_KEYWORDS, ALGnew__doc__},
{NULL, NULL} /* sentinel */
};
static PyTypeObject ALGtype =
{
#ifdef IS_PY3K
PyVarObject_HEAD_INIT(NULL, 0) /* deferred type init for compilation on Windows, type will be filled in at runtime */
#else
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
#endif
_MODULE_STRING, /*tp_name*/
sizeof(ALGobject), /*tp_size*/
0, /*tp_itemsize*/
/* methods */
(destructor) ALGdealloc, /*tp_dealloc*/
0, /*tp_print*/
#ifdef IS_PY3K
0, /*tp_getattr*/
#else
ALGgetattr, /*tp_getattr*/
#endif
ALGsetattr, /*tp_setattr*/
0, /*tp_compare*/
(reprfunc) 0, /*tp_repr*/
0, /*tp_as_number*/
#ifdef IS_PY3K
0, /*tp_as_sequence */
0, /*tp_as_mapping */
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
ALGgetattro, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
ALGmethods, /*tp_methods*/
#endif
};
#ifdef IS_PY3K
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"Crypto.Cipher." _MODULE_STRING,
NULL,
-1,
modulemethods,
NULL,
NULL,
NULL,
NULL
};
#endif
/* Initialization function for the module */
/* Deal with old API in Python 2.1 */
#if PYTHON_API_VERSION < 1011
#define PyModule_AddIntConstant(m,n,v) {PyObject *o=PyInt_FromLong(v); \
if (o!=NULL) \
{PyDict_SetItemString(PyModule_GetDict(m),n,o); Py_DECREF(o);}}
#endif
#ifdef IS_PY3K
PyMODINIT_FUNC
#else
void
#endif
_MODULE_NAME (void)
{
PyObject *m;
#ifdef IS_PY3K
/* PyType_Ready automatically fills in ob_type with &PyType_Type if it's not already set */
if (PyType_Ready(&ALGtype) < 0)
return NULL;
/* Create the module and add the functions */
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
#else
ALGtype.ob_type = &PyType_Type;
/* Create the module and add the functions */
m = Py_InitModule("Crypto.Cipher." _MODULE_STRING, modulemethods);
#endif
PyModule_AddIntConstant(m, "MODE_ECB", MODE_ECB);
PyModule_AddIntConstant(m, "MODE_CBC", MODE_CBC);
PyModule_AddIntConstant(m, "MODE_CFB", MODE_CFB);
PyModule_AddIntConstant(m, "MODE_PGP", MODE_PGP); /** Vestigial **/
PyModule_AddIntConstant(m, "MODE_OFB", MODE_OFB);
PyModule_AddIntConstant(m, "MODE_CTR", MODE_CTR);
PyModule_AddIntConstant(m, "block_size", BLOCK_SIZE);
PyModule_AddIntConstant(m, "key_size", KEY_SIZE);
/* Check for errors */
if (PyErr_Occurred())
Py_FatalError("can't initialize module " _MODULE_STRING);
#ifdef IS_PY3K
return m;
#endif
}
/* vim:set ts=4 sw=4 sts=0 noexpandtab: */

View File

@ -0,0 +1,437 @@
/*
These are the S-boxes for CAST5 as given in RFC 2144.
*/
static const uint32 S1[256] = {
0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f,
0x9c004dd3, 0x6003e540, 0xcf9fc949, 0xbfd4af27, 0x88bbbdb5,
0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d,
0x22d4ff8e, 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2,
0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, 0xa1c9e0d6,
0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b,
0x22568e3a, 0xa2d341d0, 0x66db40c8, 0xa784392f, 0x004dff2f,
0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,
0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0,
0x90ecf52e, 0x22b0c054, 0xbc8e5935, 0x4b6d2f7f, 0x50bb64a2,
0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411,
0x4bff345d, 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165,
0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, 0x882240f2,
0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319,
0xb949e354, 0xb04669fe, 0xb1b6ab8a, 0xc71358dd, 0x6385c545,
0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,
0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5,
0xf61b1891, 0xbb72275e, 0xaa508167, 0x38901091, 0xc6b505eb,
0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af,
0xaa56d291, 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9,
0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, 0x64459eab,
0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6,
0x3fab0950, 0x325ff6c2, 0x81383f05, 0x6963c5c8, 0x76cb5ad6,
0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,
0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241,
0x051ef495, 0xaa573b04, 0x4a805d8d, 0x548300d0, 0x00322a3c,
0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275,
0x915a0bf5, 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82,
0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, 0xcfa4bd3f,
0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98,
0xe31231b2, 0x2ad5ad6c, 0x954329de, 0xadbe4528, 0xd8710f69,
0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,
0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6,
0x032268d4, 0xc9600acc, 0xce387e6d, 0xbf6bb16c, 0x6a70fb78,
0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8,
0xb347cc96, 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a,
0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, 0x3f04442f,
0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d,
0x2ad37c96, 0x0175cb9d, 0xc69dff09, 0xc75b65f0, 0xd9db40d8,
0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,
0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af,
0x51c85f4d, 0x56907596, 0xa5bb15e6, 0x580304f0, 0xca042cf1,
0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09,
0xbc306ed9, 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0,
0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, 0xaf1fbda7,
0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7,
0x26470db8, 0xf881814c, 0x474d6ad7, 0x7c0c5e5c, 0xd1231959,
0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,
0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c,
0xe1e696ff, 0xb141ab08, 0x7cca89b9, 0x1a69e783, 0x02cc4843,
0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00,
0x5c8165bf };
static const uint32 S2[256] = {
0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a,
0xeec5207a, 0x55889c94, 0x72fc0651, 0xada7ef79, 0x4e1d7235,
0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d,
0xa1d6eff3, 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909,
0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, 0xd1da4181,
0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b,
0x25a1ff41, 0xe180f806, 0x1fc41080, 0x179bee7a, 0xd37ac6a9,
0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,
0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154,
0x0d554b63, 0x5d681121, 0xc866c359, 0x3d63cf73, 0xcee234c0,
0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084,
0xe4eb573b, 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d,
0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, 0x10843094,
0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74,
0xd9e0a227, 0x4ec73a34, 0xfc884f69, 0x3e4de8df, 0xef0e0088,
0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,
0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1,
0x27e19ba5, 0xd5a6c252, 0xe49754bd, 0xc5d655dd, 0xeb667064,
0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7,
0xe5d05860, 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755,
0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, 0xeccf01db,
0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6,
0x5ee22b95, 0x5f0e5304, 0x81ed6f61, 0x20e74364, 0xb45e1378,
0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,
0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402,
0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, 0xa20c3005, 0x8871df63,
0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835,
0x9f63293c, 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3,
0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, 0x73f98417,
0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741,
0x7cbad9a2, 0x2180036f, 0x50d99c08, 0xcb3f4861, 0xc26bd765,
0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,
0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb,
0x846a3bae, 0x8ff77888, 0xee5d60f6, 0x7af75673, 0x2fdd5cdb,
0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc,
0xd152de58, 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8,
0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, 0xb8da230c,
0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560,
0x61a3c9e8, 0xbca8f54d, 0xc72feffa, 0x22822e99, 0x82c570b4,
0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,
0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a,
0xf7e19798, 0x7619b72f, 0x8f1c9ba4, 0xdc8637a0, 0x16a7d3b1,
0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc,
0x520365d6, 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e,
0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, 0x5483697b,
0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9,
0x6c387e8a, 0x0ae6d249, 0xb284600c, 0xd835731d, 0xdcb1c647,
0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,
0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589,
0xa345415e, 0x5c038323, 0x3e5d3bb9, 0x43d79572, 0x7e6dd07c,
0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605,
0x4523ecf1 };
static const uint32 S3[256] = {
0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff,
0x369fe44b, 0x8c1fc644, 0xaececa90, 0xbeb1f9bf, 0xeefbcaea,
0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83,
0x927010d5, 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e,
0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, 0x553fb2c0,
0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd,
0x9255c5ed, 0x1257a240, 0x4e1a8302, 0xbae07fff, 0x528246e7,
0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,
0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1,
0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, 0x99b03dbf, 0xb5dbc64b,
0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28,
0xccc36f71, 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f,
0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, 0xa747d2d0,
0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4,
0x0a0fb402, 0x0f7fef82, 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49,
0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,
0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403,
0xe83ec305, 0x4f91751a, 0x925669c2, 0x23efe941, 0xa903f12e,
0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb,
0x02778176, 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e,
0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, 0xef303cab,
0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88,
0x7d29dc96, 0x2756d3dc, 0x8b907cee, 0xb51fd240, 0xe7c07ce3,
0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,
0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9,
0xbda8229c, 0x127dadaa, 0x438a074e, 0x1f97c090, 0x081bdb8a,
0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec,
0x64380e51, 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4,
0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, 0x4b39fffa,
0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa,
0x27627545, 0x825cf47a, 0x61bd8ba0, 0xd11e42d1, 0xcead04f4,
0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,
0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb,
0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, 0x1f081fab, 0x108618ae,
0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d,
0x2c3f8cc5, 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67,
0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, 0x3a609437,
0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c,
0x02717ef6, 0x4feb5536, 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0,
0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,
0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33,
0xabcc4f33, 0x7688c55d, 0x7b00a6b0, 0x947b0001, 0x570075d2,
0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b,
0xee971b69, 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767,
0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, 0x67214cb8,
0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d,
0x606e6dc6, 0x60543a49, 0x5727c148, 0x2be98a1d, 0x8ab41738,
0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,
0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31,
0x9c305a00, 0x52bce688, 0x1b03588a, 0xf7baefd5, 0x4142ed9c,
0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c,
0xee353783 };
static const uint32 S4[256] = {
0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb,
0x64ad8c57, 0x85510443, 0xfa020ed1, 0x7e287aff, 0xe60fb663,
0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63,
0x241e4adf, 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220,
0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, 0xee4d111a,
0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe,
0x081b08ca, 0x05170121, 0x80530100, 0xe83e5efe, 0xac9af4f8,
0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,
0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400,
0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, 0x2649abdf, 0xaea0c7f5,
0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03,
0xf80eb2bb, 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746,
0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, 0x4d351805,
0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91,
0x9f46222f, 0x3991467d, 0xa5bf6d8e, 0x1143c44f, 0x43958302,
0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,
0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25,
0x79098b02, 0xe4eabb81, 0x28123b23, 0x69dead38, 0x1574ca16,
0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8,
0x09114003, 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340,
0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, 0xe756bdff,
0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391,
0x6b65811c, 0x5e146119, 0x6e85cb75, 0xbe07c002, 0xc2325577,
0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,
0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a,
0xeca1d7c7, 0x041afa32, 0x1d16625a, 0x6701902c, 0x9b757a54,
0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48,
0x56e55a79, 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5,
0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, 0xb7747f9d,
0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035,
0x213d42f6, 0x2c1c7c26, 0x61c2f50f, 0x6552daf9, 0xd2c231f8,
0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,
0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86,
0x311170a7, 0x3e9b640c, 0xcc3e10d7, 0xd5cad3b6, 0x0caec388,
0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f,
0xc1de8417, 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3,
0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, 0x6f7de532,
0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5,
0x001d7b95, 0x82e5e7d2, 0x109873f6, 0x00613096, 0xc32d9521,
0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,
0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7,
0x0ce454a9, 0xd60acd86, 0x015f1919, 0x77079103, 0xdea03af6,
0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651,
0xb8a5c3ef, 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf,
0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, 0x39e4460c,
0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e,
0x492fc295, 0x9266beab, 0xb5676e69, 0x9bd3ddda, 0xdf7e052f,
0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,
0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979,
0x932bcdf6, 0xb657c34d, 0x4edfd282, 0x7ae5290c, 0x3cb9536b,
0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1,
0x0aef7ed2 };
static const uint32 S5[256] = {
0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff,
0x1dd358f5, 0x44dd9d44, 0x1731167f, 0x08fbf1fa, 0xe7f511cc,
0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a,
0x69befd7a, 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180,
0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, 0x5f480a01,
0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb,
0x8dba1cfe, 0x41a99b02, 0x1a550a04, 0xba8f65cb, 0x7251f4e7,
0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,
0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88,
0x8709e6b0, 0xd7e07156, 0x4e29fea7, 0x6366e52d, 0x02d1c000,
0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02,
0xd642a0c9, 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec,
0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, 0x5c1ff900,
0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976,
0x90c79505, 0xb0a8a774, 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27,
0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,
0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980,
0x524755f4, 0x03b63cc9, 0x0cc844b2, 0xbcf3f0aa, 0x87ac36e9,
0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da,
0x01c94910, 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284,
0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, 0x136e05db,
0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf,
0xb6f589de, 0xec2941da, 0x26e46695, 0xb7566419, 0xf654efc5,
0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,
0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd,
0x9e0885f9, 0x68cb3e47, 0x086c010f, 0xa21de820, 0xd18b69de,
0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d,
0xb0d70eba, 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4,
0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, 0x580a249f,
0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715,
0x646c6bd7, 0x44904db3, 0x66b4f0a3, 0xc0f1648a, 0x697ed5af,
0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,
0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8,
0xc1092910, 0x8bc95fc6, 0x7d869cf4, 0x134f616f, 0x2e77118d,
0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010,
0xaf462ba2, 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487,
0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, 0x445f7382,
0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3,
0x20936079, 0x459b80a5, 0xbe60e2db, 0xa9c23101, 0xeba5315c,
0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,
0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e,
0x75922283, 0x784d6b17, 0x58ebb16e, 0x44094f85, 0x3f481d87,
0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a,
0x2b092801, 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0,
0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, 0x6cf6e479,
0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3,
0xa09c7f70, 0x5346aba0, 0x5ce96c28, 0xe176eda3, 0x6bac307f,
0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,
0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a,
0xeeb9491d, 0x34010718, 0xbb30cab8, 0xe822fe15, 0x88570983,
0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08,
0xefe9e7d4 };
static const uint32 S6[256] = {
0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7,
0x016843b4, 0xeced5cbc, 0x325553ac, 0xbf9f0960, 0xdfa1e2ed,
0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732,
0x8989b138, 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e,
0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, 0xa3149619,
0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f,
0xa888614a, 0x2900af98, 0x01665991, 0xe1992863, 0xc8f30c60,
0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,
0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c,
0x4c7f4448, 0xdab5d440, 0x6dba0ec3, 0x083919a7, 0x9fbaeed9,
0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a,
0xba7dd9cd, 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d,
0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, 0x284caf89,
0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906,
0xefe8c36e, 0xf890cdd9, 0x80226dae, 0xc340a4a3, 0xdf7e9c09,
0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,
0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc,
0xcf222ebf, 0x25ac6f48, 0xa9a99387, 0x53bddb65, 0xe76ffbe7,
0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d,
0xc8087dfc, 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0,
0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, 0x5f04456d,
0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5,
0xe2220abe, 0xd2916ebf, 0x4ec75b95, 0x24f2c3c0, 0x42d15d99,
0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,
0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af,
0x692573e4, 0xe9a9d848, 0xf3160289, 0x3a62ef1d, 0xa787e238,
0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407,
0x592af950, 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa,
0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, 0x89dff0bb,
0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585,
0xdc049441, 0xc8098f9b, 0x7dede786, 0xc39a3373, 0x42410005,
0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,
0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a,
0x1f8fb214, 0xd372cf08, 0xcc3c4a13, 0x8cf63166, 0x061c87be,
0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb,
0x3fc06976, 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459,
0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, 0x3007cd3e,
0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241,
0x8809286c, 0xf592d891, 0x08a930f6, 0x957ef305, 0xb7fbffbd,
0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,
0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123,
0x257f0c3d, 0x9348af49, 0x361400bc, 0xe8816f4a, 0x3814f200,
0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a,
0x54f4a084, 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab,
0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, 0x653d7e6a,
0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76,
0x0404a8c8, 0xb8e5a121, 0xb81a928a, 0x60ed5869, 0x97c55b96,
0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,
0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1,
0xf544edeb, 0xb0e93524, 0xbebb8fbd, 0xa2d762cf, 0x49c92f54,
0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd,
0xd675cf2f };
static const uint32 S7[256] = {
0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f,
0xab9bc912, 0xde6008a1, 0x2028da1f, 0x0227bce7, 0x4d642916,
0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2,
0xb28707de, 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd,
0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, 0x4d495001,
0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4,
0x1286becf, 0xb6eacb19, 0x2660c200, 0x7565bde4, 0x64241f7a,
0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,
0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a,
0xeb12ff82, 0xe3486911, 0xd34d7516, 0x4e7b3aff, 0x5f43671b,
0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0,
0xcb3a6c88, 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e,
0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, 0x0a961288,
0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745,
0xcf19df58, 0xbec3f756, 0xc06eba30, 0x07211b24, 0x45c28829,
0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,
0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f,
0xaff60ff4, 0xea2c4e6d, 0x16e39264, 0x92544a8b, 0x009b4fc3,
0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9,
0xbe838688, 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d,
0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, 0xda6d0c74,
0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f,
0xeed82b29, 0x1d382fe3, 0x0c4fb99a, 0xbb325778, 0x3ec6d97b,
0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,
0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32,
0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, 0xe7225308, 0x8b75cf77,
0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0,
0x5dda0033, 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a,
0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, 0x2711fd60,
0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476,
0x488dcf25, 0x36c9d566, 0x28e74e41, 0xc2610aca, 0x3d49a9cf,
0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,
0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887,
0x2b9f4fd5, 0x625aba82, 0x6a017962, 0x2ec01b9c, 0x15488aa9,
0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9,
0x3453dc1e, 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07,
0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, 0x66626c1c,
0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae,
0x9ea294fb, 0x52cf564c, 0x9883fe66, 0x2ec40581, 0x763953c3,
0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,
0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f,
0x3d321c5d, 0xc3f5e194, 0x4b269301, 0xc79f022f, 0x3c997e7e,
0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f,
0xc61e45be, 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567,
0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, 0x1814386b,
0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390,
0x5479f8e6, 0x1cb8d647, 0x97fd61a9, 0xea7759f4, 0x2d57539d,
0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,
0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc,
0x3d40f021, 0xc3c0bdae, 0x4958c24c, 0x518f36b2, 0x84b1d370,
0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b,
0x954b8aa3 };
static const uint32 S8[256] = {
0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7,
0xe6c1121b, 0x0e241600, 0x052ce8b5, 0x11a9cfb0, 0xe5952f11,
0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a,
0x37ddddfc, 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940,
0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, 0x0b15a15d,
0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7,
0x72df191b, 0x7580330d, 0x94074251, 0x5c7dcdfa, 0xabbe6d63,
0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,
0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022,
0xce949ad4, 0xb84769ad, 0x965bd862, 0x82f3d055, 0x66fb9767,
0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e,
0x647a78fc, 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6,
0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, 0xbbd35049,
0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548,
0x58cb7e07, 0x3b74ef2e, 0x522fffb1, 0xd24708cc, 0x1c7e27cd,
0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,
0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd,
0xc18910b1, 0xe11dbf7b, 0x06cd1af8, 0x7170c608, 0x2d5e3354,
0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34,
0x77d51b42, 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564,
0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, 0xe6459788,
0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b,
0x24259fd7, 0xf8bef472, 0x835ffcb8, 0x6df4c1f2, 0x96f5b195,
0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,
0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187,
0xea7a6e98, 0x7cd16efc, 0x1436876c, 0xf1544107, 0xbedeee14,
0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d,
0x151682eb, 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f,
0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, 0xb6f2cf3b,
0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5,
0xbae7dfdc, 0x42cbda70, 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6,
0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,
0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4,
0xc5c8b37e, 0x0d809ea2, 0x398feb7c, 0x132a4f94, 0x43b7950e,
0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289,
0xacf3ebc3, 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4,
0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, 0xe87b40e4,
0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694,
0x38d7e5b2, 0x57720101, 0x730edebc, 0x5b643113, 0x94917e4f,
0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,
0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f,
0xad1163ed, 0xea7b5965, 0x1a00726e, 0x11403092, 0x00da6d77,
0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8,
0xcee7d28a, 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37,
0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, 0xaa12e4f2,
0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b,
0x67cdb156, 0x350d8384, 0x5938fa0f, 0x42399ef3, 0x36997b07,
0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,
0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82,
0x0d2059d1, 0xa466bb1e, 0xf8da0a82, 0x04f19130, 0xba6e4ec0,
0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283,
0xea8bf59e };

View File

@ -0,0 +1,141 @@
/* src/config.h.in. Generated from configure.ac by autoheader. */
/* Define to 1 if you have the declaration of `mpz_powm', and to 0 if you
don't. */
#undef HAVE_DECL_MPZ_POWM
/* Define to 1 if you have the declaration of `mpz_powm_sec', and to 0 if you
don't. */
#undef HAVE_DECL_MPZ_POWM_SEC
/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H
/* Define to 1 if you have the `gmp' library (-lgmp). */
#undef HAVE_LIBGMP
/* Define to 1 if you have the `mpir' library (-lmpir). */
#undef HAVE_LIBMPIR
/* Define to 1 if you have the <limits.h> header file. */
#undef HAVE_LIMITS_H
/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
to 0 otherwise. */
#undef HAVE_MALLOC
/* Define to 1 if you have the `memmove' function. */
#undef HAVE_MEMMOVE
/* Define to 1 if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H
/* Define to 1 if you have the `memset' function. */
#undef HAVE_MEMSET
/* Define to 1 if you have the <stddef.h> header file. */
#undef HAVE_STDDEF_H
/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H
/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/types.h> header file. */
#undef HAVE_SYS_TYPES_H
/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H
/* Define to 1 if you have the <wchar.h> header file. */
#undef HAVE_WCHAR_H
/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT
/* Define to the full name of this package. */
#undef PACKAGE_NAME
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the home page for this package. */
#undef PACKAGE_URL
/* Define to the version of this package. */
#undef PACKAGE_VERSION
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
/* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
#undef _UINT32_T
/* Define for Solaris 2.5.1 so the uint64_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
#undef _UINT64_T
/* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
#undef _UINT8_T
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
#undef inline
#endif
/* Define to the type of a signed integer type of width exactly 16 bits if
such a type exists and the standard includes do not define it. */
#undef int16_t
/* Define to the type of a signed integer type of width exactly 32 bits if
such a type exists and the standard includes do not define it. */
#undef int32_t
/* Define to the type of a signed integer type of width exactly 64 bits if
such a type exists and the standard includes do not define it. */
#undef int64_t
/* Define to the type of a signed integer type of width exactly 8 bits if such
a type exists and the standard includes do not define it. */
#undef int8_t
/* Define to rpl_malloc if the replacement function should be used. */
#undef malloc
/* Define to `unsigned int' if <sys/types.h> does not define. */
#undef size_t
/* Define to the type of an unsigned integer type of width exactly 16 bits if
such a type exists and the standard includes do not define it. */
#undef uint16_t
/* Define to the type of an unsigned integer type of width exactly 32 bits if
such a type exists and the standard includes do not define it. */
#undef uint32_t
/* Define to the type of an unsigned integer type of width exactly 64 bits if
such a type exists and the standard includes do not define it. */
#undef uint64_t
/* Define to the type of an unsigned integer type of width exactly 8 bits if
such a type exists and the standard includes do not define it. */
#undef uint8_t

View File

@ -0,0 +1,104 @@
/*
* An generic header for the SHA-2 hash family.
*
* Written in 2010 by Lorenz Quack <don@amberfisharts.com>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#ifndef __HASH_SHA2_H
#define __HASH_SHA2_H
/* check if implementation set the correct macros */
#ifndef MODULE_NAME
#error SHA2 Implementation must define MODULE_NAME before including this header
#endif
#ifndef DIGEST_SIZE
#error SHA2 Implementation must define DIGEST_SIZE before including this header
#else
#define DIGEST_SIZE_BITS (DIGEST_SIZE*8)
#endif
#ifndef BLOCK_SIZE
#error SHA2 Implementation must define BLOCK_SIZE before including this header
#else
#define BLOCK_SIZE_BITS (BLOCK_SIZE*8)
#endif
#ifndef WORD_SIZE
#error SHA2 Implementation must define WORD_SIZE before including this header
#else
#if ((WORD_SIZE != 4) && (WORD_SIZE != 8))
#error WORD_SIZE must be either 4 or 8
#else
#define WORD_SIZE_BITS (WORD_SIZE*8)
#endif
#endif
#ifndef SCHEDULE_SIZE
#error SHA2 Implementation must define SCHEDULE_SIZE before including this header
#endif
/* define some helper macros */
#define PADDING_SIZE (2 * WORD_SIZE)
#define LAST_BLOCK_SIZE (BLOCK_SIZE - PADDING_SIZE)
/* define generic SHA-2 family functions */
#define Ch(x,y,z) ((x & y) ^ (~x & z))
#define Maj(x,y,z) ((x & y) ^ (x & z) ^ (y & z))
#define ROTR(x, n) (((x)>>((n)&(WORD_SIZE_BITS-1)))|((x)<<(WORD_SIZE_BITS-((n)&(WORD_SIZE_BITS-1)))))
#define SHR(x, n) ((x)>>(n))
/* determine fixed size types */
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
#include <stdint.h>
typedef uint8_t U8;
typedef uint32_t U32;
typedef uint64_t U64;
#elif defined(_MSC_VER)
typedef unsigned char U8;
typedef unsigned __int64 U64;
typedef unsigned int U32;
#elif defined(__sun) || defined(__sun__)
#include <sys/inttypes.h>
typedef uint8_t U8;
typedef uint32_t U32;
typedef uint64_t U64;
#endif
/* typedef a sha2_word_t type of appropriate size */
#if (WORD_SIZE_BITS == 64)
typedef U64 sha2_word_t;
#elif (WORD_SIZE_BITS == 32)
typedef U32 sha2_word_t;
#else
#error According to the FIPS Standard WORD_SIZE_BITS must be either 32 or 64
#endif
/* define the hash_state structure */
typedef struct{
sha2_word_t state[8];
int curlen;
sha2_word_t length_upper, length_lower;
unsigned char buf[BLOCK_SIZE];
} hash_state;
#endif /* __HASH_SHA2_H */

View File

@ -0,0 +1,199 @@
/*
* An generic implementation of the SHA-2 hash family, this is endian neutral
* so should work just about anywhere.
*
* This code works much like the MD5 code provided by RSA. You sha_init()
* a "sha_state" then sha_process() the bytes you want and sha_done() to get
* the output.
*
* Originally written by Tom St Denis -- http://tomstdenis.home.dhs.org
* Adapted for PyCrypto by Jeethu Rao, Taylor Boon, and others.
* Turned into a generic template by Lorenz Quack <don@amberfisharts.com>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*
*/
#include "Python.h"
#include "pycrypto_compat.h"
/* compress one block */
static void sha_compress(hash_state * hs)
{
sha2_word_t S[8], W[SCHEDULE_SIZE], T1, T2;
int i;
/* copy state into S */
for (i = 0; i < 8; i++)
S[i] = hs->state[i];
/* copy the state into W[0..15] */
for (i = 0; i < 16; i++){
W[i] = (
(((sha2_word_t) hs->buf[(WORD_SIZE*i)+0]) << (WORD_SIZE_BITS- 8)) |
(((sha2_word_t) hs->buf[(WORD_SIZE*i)+1]) << (WORD_SIZE_BITS-16)) |
(((sha2_word_t) hs->buf[(WORD_SIZE*i)+2]) << (WORD_SIZE_BITS-24)) |
(((sha2_word_t) hs->buf[(WORD_SIZE*i)+3]) << (WORD_SIZE_BITS-32))
#if (WORD_SIZE_BITS == 64)
|
(((sha2_word_t) hs->buf[(WORD_SIZE*i)+4]) << (WORD_SIZE_BITS-40)) |
(((sha2_word_t) hs->buf[(WORD_SIZE*i)+5]) << (WORD_SIZE_BITS-48)) |
(((sha2_word_t) hs->buf[(WORD_SIZE*i)+6]) << (WORD_SIZE_BITS-56)) |
(((sha2_word_t) hs->buf[(WORD_SIZE*i)+7]))
#endif
);
}
/* fill W[16..SCHEDULE_SIZE] */
for (i = 16; i < SCHEDULE_SIZE; i++)
W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
/* Compress */
for (i = 0; i < SCHEDULE_SIZE; i++) {
T1 = S[7] + Sigma1(S[4]) + Ch(S[4], S[5], S[6]) + K[i] + W[i];
T2 = Sigma0(S[0]) + Maj(S[0], S[1], S[2]);
S[7] = S[6];
S[6] = S[5];
S[5] = S[4];
S[4] = S[3] + T1;
S[3] = S[2];
S[2] = S[1];
S[1] = S[0];
S[0] = T1 + T2;
}
/* feedback */
for (i = 0; i < 8; i++)
hs->state[i] += S[i];
}
/* adds *inc* to the length of the hash_state *hs*
* return 1 on success
* return 0 if the length overflows
*/
int add_length(hash_state *hs, sha2_word_t inc) {
sha2_word_t overflow_detector;
overflow_detector = hs->length_lower;
hs->length_lower += inc;
if (overflow_detector > hs->length_lower) {
overflow_detector = hs->length_upper;
hs->length_upper++;
if (hs->length_upper > hs->length_upper)
return 0;
}
return 1;
}
/* init the SHA state */
static void sha_init(hash_state * hs)
{
int i;
hs->curlen = hs->length_upper = hs->length_lower = 0;
for (i = 0; i < 8; ++i)
hs->state[i] = H[i];
}
static void sha_process(hash_state * hs, unsigned char *buf, int len)
{
while (len--) {
/* copy byte */
hs->buf[hs->curlen++] = *buf++;
/* is a block full? */
if (hs->curlen == BLOCK_SIZE) {
sha_compress(hs);
add_length(hs, BLOCK_SIZE_BITS);
hs->curlen = 0;
}
}
}
static void sha_done(hash_state * hs, unsigned char *hash)
{
int i;
/* increase the length of the message */
add_length(hs, hs->curlen * 8);
/* append the '1' bit */
hs->buf[hs->curlen++] = 0x80;
/* if the length is currently above LAST_BLOCK_SIZE bytes we append
* zeros then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (hs->curlen > LAST_BLOCK_SIZE) {
for (; hs->curlen < BLOCK_SIZE;)
hs->buf[hs->curlen++] = 0;
sha_compress(hs);
hs->curlen = 0;
}
/* pad upto LAST_BLOCK_SIZE bytes of zeroes */
for (; hs->curlen < LAST_BLOCK_SIZE;)
hs->buf[hs->curlen++] = 0;
/* append length */
for (i = 0; i < WORD_SIZE; i++)
hs->buf[i + LAST_BLOCK_SIZE] =
(hs->length_upper >> ((WORD_SIZE - 1 - i) * 8)) & 0xFF;
for (i = 0; i < WORD_SIZE; i++)
hs->buf[i + LAST_BLOCK_SIZE + WORD_SIZE] =
(hs->length_lower >> ((WORD_SIZE - 1 - i) * 8)) & 0xFF;
sha_compress(hs);
/* copy output */
for (i = 0; i < DIGEST_SIZE; i++)
hash[i] = (hs->state[i / WORD_SIZE] >>
((WORD_SIZE - 1 - (i % WORD_SIZE)) * 8)) & 0xFF;
}
// Done
static void hash_init (hash_state *ptr)
{
sha_init(ptr);
}
// Done
static void
hash_update (hash_state *self, const U8 *buf, int len)
{
sha_process(self,(unsigned char *)buf, len);
}
// Done
static void
hash_copy(hash_state *src, hash_state *dest)
{
memcpy(dest,src,sizeof(hash_state));
}
// Done
static PyObject *
hash_digest (const hash_state *self)
{
unsigned char digest[DIGEST_SIZE];
hash_state temp;
hash_copy((hash_state*)self,&temp);
sha_done(&temp,digest);
return PyBytes_FromStringAndSize((char *)digest, DIGEST_SIZE);
}
#include "hash_template.c"

View File

@ -0,0 +1,366 @@
/*
* hash_template.c : Generic framework for hash function extension modules
*
* Written by Andrew Kuchling and others
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*/
/* Basic object type */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef _HAVE_STDC_HEADERS
#include <string.h>
#endif
#include "Python.h"
#include "pycrypto_compat.h"
#define _STR(x) #x
#define _XSTR(x) _STR(x)
#define _PASTE(x,y) x##y
#define _PASTE2(x,y) _PASTE(x,y)
#ifdef IS_PY3K
#define _MODULE_NAME _PASTE2(PyInit_,MODULE_NAME)
#else
#define _MODULE_NAME _PASTE2(init,MODULE_NAME)
#endif
#define _MODULE_STRING _XSTR(MODULE_NAME)
typedef struct {
PyObject_HEAD
hash_state st;
} ALGobject;
/* Please see PEP3123 for a discussion of PyObject_HEAD and changes made in 3.x to make it conform to Standard C.
* These changes also dictate using Py_TYPE to check type, and PyVarObject_HEAD_INIT(NULL, 0) to initialize
*/
#ifdef IS_PY3K
static PyTypeObject ALGtype;
#define is_ALGobject(v) (Py_TYPE(v) == &ALGtype)
#else
staticforward PyTypeObject ALGtype;
#define is_ALGobject(v) ((v)->ob_type == &ALGtype)
#define PyLong_FromLong PyInt_FromLong /* For Python 2.x */
#endif
static ALGobject *
newALGobject(void)
{
ALGobject *new;
new = PyObject_New(ALGobject, &ALGtype);
return new;
}
/* Internal methods for a hashing object */
static void
ALG_dealloc(PyObject *ptr)
{
ALGobject *self = (ALGobject *)ptr;
/* Overwrite the contents of the object */
memset((char*)&(self->st), 0, sizeof(hash_state));
PyObject_Del(ptr);
}
/* External methods for a hashing object */
static char ALG_copy__doc__[] =
"copy(): Return a copy of the hashing object.";
static PyObject *
ALG_copy(ALGobject *self, PyObject *args)
{
ALGobject *newobj;
if (!PyArg_ParseTuple(args, "")) {
return NULL;
}
if ( (newobj = newALGobject())==NULL)
return NULL;
hash_copy(&(self->st), &(newobj->st));
return((PyObject *)newobj);
}
static char ALG_digest__doc__[] =
"digest(): Return the digest value as a string of binary data.";
static PyObject *
ALG_digest(ALGobject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return NULL;
return (PyObject *)hash_digest(&(self->st));
}
static char ALG_hexdigest__doc__[] =
"hexdigest(): Return the digest value as a string of hexadecimal digits.";
static PyObject *
ALG_hexdigest(ALGobject *self, PyObject *args)
{
PyObject *value, *retval;
unsigned char *raw_digest, *hex_digest;
int i, j, size;
if (!PyArg_ParseTuple(args, ""))
return NULL;
/* Get the raw (binary) digest value */
value = (PyObject *)hash_digest(&(self->st));
size = PyBytes_Size(value);
raw_digest = (unsigned char *) PyBytes_AsString(value);
/* Create a new string */
retval = PyBytes_FromStringAndSize(NULL, size * 2 );
hex_digest = (unsigned char *) PyBytes_AsString(retval);
/* Make hex version of the digest */
for(i=j=0; i<size; i++)
{
char c;
c = raw_digest[i] / 16; c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
c = raw_digest[i] % 16; c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
}
#ifdef IS_PY3K
/* Create a text string return value */
retval = PyUnicode_FromEncodedObject(retval,"latin-1","strict");
#endif
Py_DECREF(value);
return retval;
}
static char ALG_update__doc__[] =
"update(string): Update this hashing object's state with the provided string.";
static PyObject *
ALG_update(ALGobject *self, PyObject *args)
{
unsigned char *cp;
int len;
if (!PyArg_ParseTuple(args, "s#", &cp, &len))
return NULL;
Py_BEGIN_ALLOW_THREADS;
hash_update(&(self->st), cp, len);
Py_END_ALLOW_THREADS;
Py_INCREF(Py_None);
return Py_None;
}
/** Forward declaration for this module's new() method **/
static char ALG_new__doc__[] =
"new([string]): Return a new " _MODULE_STRING
" hashing object. An optional string "
"argument may be provided; if present, this string will be "
"automatically hashed into the initial state of the object.";
static PyObject *ALG_new(PyObject*, PyObject*);
static PyMethodDef ALG_methods[] = {
{"copy", (PyCFunction)ALG_copy, METH_VARARGS, ALG_copy__doc__},
{"digest", (PyCFunction)ALG_digest, METH_VARARGS, ALG_digest__doc__},
{"hexdigest", (PyCFunction)ALG_hexdigest, METH_VARARGS, ALG_hexdigest__doc__},
{"update", (PyCFunction)ALG_update, METH_VARARGS, ALG_update__doc__},
{"new", (PyCFunction)ALG_new, METH_VARARGS, ALG_new__doc__},
{NULL, NULL} /* sentinel */
};
static PyObject *
#ifdef IS_PY3K
ALG_getattro(PyObject *self, PyObject *attr)
#else
ALG_getattr(PyObject *self, char *name)
#endif
{
#ifdef IS_PY3K
if (!PyUnicode_Check(attr))
goto generic;
if (PyUnicode_CompareWithASCIIString(attr, "digest_size")==0)
return PyLong_FromLong(DIGEST_SIZE);
#else
if (strcmp(name, "digest_size")==0)
return PyInt_FromLong(DIGEST_SIZE);
#endif
#ifdef IS_PY3K
generic:
return PyObject_GenericGetAttr(self, attr);
#else
return Py_FindMethod(ALG_methods, self, name);
#endif
}
static PyTypeObject ALGtype = {
#ifdef IS_PY3K
PyVarObject_HEAD_INIT(NULL, 0) /* deferred type init for compilation on Windows, type will be filled in at runtime */
#else
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
#endif
_MODULE_STRING, /*tp_name*/
sizeof(ALGobject), /*tp_size*/
0, /*tp_itemsize*/
/* methods */
(destructor) ALG_dealloc, /*tp_dealloc*/
0, /*tp_print*/
#ifdef IS_PY3K
0, /*tp_getattr*/
#else
ALG_getattr, /*tp_getattr*/
#endif
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
#ifdef IS_PY3K
0, /*tp_as_sequence */
0, /*tp_as_mapping */
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
ALG_getattro, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
ALG_methods, /*tp_methods*/
#endif
};
/* The single module-level function: new() */
/** This method belong to both the module and the hash object **/
static PyObject *
ALG_new(PyObject *self, PyObject *args)
{
ALGobject *new;
unsigned char *cp = NULL;
int len;
if ((new = newALGobject()) == NULL)
return NULL;
if (!PyArg_ParseTuple(args, "|s#",
&cp, &len)) {
Py_DECREF(new);
return NULL;
}
hash_init(&(new->st));
if (PyErr_Occurred()) {
Py_DECREF(new);
return NULL;
}
if (cp) {
Py_BEGIN_ALLOW_THREADS;
hash_update(&(new->st), cp, len);
Py_END_ALLOW_THREADS;
}
return (PyObject *)new;
}
/* List of functions exported by this module */
static struct PyMethodDef ALG_functions[] = {
{"new", (PyCFunction)ALG_new, METH_VARARGS, ALG_new__doc__},
{NULL, NULL} /* Sentinel */
};
#ifdef IS_PY3K
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"Crypto.Hash." _MODULE_STRING,
NULL,
-1,
ALG_functions,
NULL,
NULL,
NULL,
NULL
};
#endif
/* Initialize this module. */
/* Deal with old API in Python 2.1 */
#if PYTHON_API_VERSION < 1011
#define PyModule_AddIntConstant(m,n,v) {PyObject *o=PyInt_FromLong(v); \
if (o!=NULL) \
{PyDict_SetItemString(PyModule_GetDict(m),n,o); Py_DECREF(o);}}
#endif
#ifdef IS_PY3K
PyMODINIT_FUNC
#else
void
#endif
_MODULE_NAME (void)
{
PyObject *m;
#ifdef IS_PY3K
/* PyType_Ready automatically fills in ob_type with &PyType_Type if it's not already set */
if (PyType_Ready(&ALGtype) < 0)
return NULL;
/* Create the module and add the functions */
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
#else
ALGtype.ob_type = &PyType_Type;
m = Py_InitModule("Crypto.Hash." _MODULE_STRING, ALG_functions);
#endif
/* Add some symbolic constants to the module */
PyModule_AddIntConstant(m, "digest_size", DIGEST_SIZE);
PyModule_AddIntConstant(m, "block_size", BLOCK_SIZE);
/* Check for errors */
if (PyErr_Occurred())
Py_FatalError("can't initialize module "
_MODULE_STRING);
#ifdef IS_PY3K
return m;
#endif
}

View File

@ -0,0 +1,16 @@
/* Define to 1 if you have the declaration of `mpz_powm', and to 0 if you
don't. */
#undef HAVE_DECL_MPZ_POWM
/* Define to 1 if you have the declaration of `mpz_powm_sec', and to 0 if you
don't. */
#undef HAVE_DECL_MPZ_POWM_SEC
/* Define to 1 if you have the `gmp' library (-lgmp). */
#undef HAVE_LIBGMP
/* Define to 1 if you have the `mpir' library (-lmpir). */
#undef HAVE_LIBMPIR
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1

View File

@ -0,0 +1,42 @@
/*
* inc-msvc/stdint.h: Partial stdint.h for MSVC compiler
*
* Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*/
#ifndef PYCRYPTO_MSVC_STDINT_H
#define PYCRYPTO_MSVC_STDINT_H
typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
typedef signed __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#ifndef inline
# define inline __inline
#endif /* inline */
#endif /* PYCRYPTO_MSVC_STDINT_H */
/* vim:set ts=4 sw=4 sts=4 expandtab: */

View File

@ -0,0 +1,87 @@
#ifndef TOMCRYPT_H_
#define TOMCRYPT_H_
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include <limits.h>
/* use configuration data */
#include <tomcrypt_custom.h>
#ifdef __cplusplus
extern "C" {
#endif
/* version */
#define CRYPT 0x0116
#define SCRYPT "1.16"
/* max size of either a cipher/hash block or symmetric key [largest of the two] */
#define MAXBLOCKSIZE 128
/* descriptor table size */
#define TAB_SIZE 32
/* error codes [will be expanded in future releases] */
enum {
CRYPT_OK=0, /* Result OK */
CRYPT_ERROR, /* Generic Error */
CRYPT_NOP, /* Not a failure but no operation was performed */
CRYPT_INVALID_KEYSIZE, /* Invalid key size given */
CRYPT_INVALID_ROUNDS, /* Invalid number of rounds */
CRYPT_FAIL_TESTVECTOR, /* Algorithm failed test vectors */
CRYPT_BUFFER_OVERFLOW, /* Not enough space for output */
CRYPT_INVALID_PACKET, /* Invalid input packet given */
CRYPT_INVALID_PRNGSIZE, /* Invalid number of bits for a PRNG */
CRYPT_ERROR_READPRNG, /* Could not read enough from PRNG */
CRYPT_INVALID_CIPHER, /* Invalid cipher specified */
CRYPT_INVALID_HASH, /* Invalid hash specified */
CRYPT_INVALID_PRNG, /* Invalid PRNG specified */
CRYPT_MEM, /* Out of memory */
CRYPT_PK_TYPE_MISMATCH, /* Not equivalent types of PK keys */
CRYPT_PK_NOT_PRIVATE, /* Requires a private PK key */
CRYPT_INVALID_ARG, /* Generic invalid argument */
CRYPT_FILE_NOTFOUND, /* File Not Found */
CRYPT_PK_INVALID_TYPE, /* Invalid type of PK key */
CRYPT_PK_INVALID_SYSTEM,/* Invalid PK system specified */
CRYPT_PK_DUP, /* Duplicate key already in key ring */
CRYPT_PK_NOT_FOUND, /* Key not found in keyring */
CRYPT_PK_INVALID_SIZE, /* Invalid size input for PK parameters */
CRYPT_INVALID_PRIME_SIZE,/* Invalid size of prime requested */
CRYPT_PK_INVALID_PADDING /* Invalid padding on input */
};
#include <tomcrypt_cfg.h>
#include <tomcrypt_macros.h>
#include <tomcrypt_cipher.h>
#include <tomcrypt_hash.h>
#include <tomcrypt_mac.h>
#include <tomcrypt_prng.h>
#include <tomcrypt_pk.h>
#include <tomcrypt_math.h>
#include <tomcrypt_misc.h>
#include <tomcrypt_argchk.h>
#include <tomcrypt_pkcs.h>
#ifdef __cplusplus
}
#endif
#endif /* TOMCRYPT_H_ */
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt.h,v $ */
/* $Revision: 1.20 $ */
/* $Date: 2006/11/26 01:45:14 $ */

View File

@ -0,0 +1,38 @@
/* Defines the LTC_ARGCHK macro used within the library */
/* ARGTYPE is defined in mycrypt_cfg.h */
#if ARGTYPE == 0
#include <signal.h>
/* this is the default LibTomCrypt macro */
void crypt_argchk(char *v, char *s, int d);
#define LTC_ARGCHK(x) if (!(x)) { crypt_argchk(#x, __FILE__, __LINE__); }
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 1
/* fatal type of error */
#define LTC_ARGCHK(x) assert((x))
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 2
#define LTC_ARGCHK(x) if (!(x)) { fprintf(stderr, "\nwarning: ARGCHK failed at %s:%d\n", __FILE__, __LINE__); }
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 3
#define LTC_ARGCHK(x)
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 4
#define LTC_ARGCHK(x) if (!(x)) return CRYPT_INVALID_ARG;
#define LTC_ARGCHKVD(x) if (!(x)) return;
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_argchk.h,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2006/08/27 20:50:21 $ */

View File

@ -0,0 +1,136 @@
/* This is the build config file.
*
* With this you can setup what to inlcude/exclude automatically during any build. Just comment
* out the line that #define's the word for the thing you want to remove. phew!
*/
#ifndef TOMCRYPT_CFG_H
#define TOMCRYPT_CFG_H
#if defined(_WIN32) || defined(_MSC_VER)
#define LTC_CALL __cdecl
#else
#ifndef LTC_CALL
#define LTC_CALL
#endif
#endif
#ifndef LTC_EXPORT
#define LTC_EXPORT
#endif
/* certain platforms use macros for these, making the prototypes broken */
#ifndef LTC_NO_PROTOTYPES
/* you can change how memory allocation works ... */
LTC_EXPORT void * LTC_CALL XMALLOC(size_t n);
LTC_EXPORT void * LTC_CALL XREALLOC(void *p, size_t n);
LTC_EXPORT void * LTC_CALL XCALLOC(size_t n, size_t s);
LTC_EXPORT void LTC_CALL XFREE(void *p);
LTC_EXPORT void LTC_CALL XQSORT(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *));
/* change the clock function too */
LTC_EXPORT clock_t LTC_CALL XCLOCK(void);
/* various other functions */
LTC_EXPORT void * LTC_CALL XMEMCPY(void *dest, const void *src, size_t n);
LTC_EXPORT int LTC_CALL XMEMCMP(const void *s1, const void *s2, size_t n);
LTC_EXPORT void * LTC_CALL XMEMSET(void *s, int c, size_t n);
LTC_EXPORT int LTC_CALL XSTRCMP(const char *s1, const char *s2);
#endif
/* type of argument checking, 0=default, 1=fatal and 2=error+continue, 3=nothing */
#ifndef ARGTYPE
#define ARGTYPE 0
#endif
/* Controls endianess and size of registers. Leave uncommented to get platform neutral [slower] code
*
* Note: in order to use the optimized macros your platform must support unaligned 32 and 64 bit read/writes.
* The x86 platforms allow this but some others [ARM for instance] do not. On those platforms you **MUST**
* use the portable [slower] macros.
*/
/* detect x86-32 machines somewhat */
#if !defined(__STRICT_ANSI__) && (defined(INTEL_CC) || (defined(_MSC_VER) && defined(WIN32)) || (defined(__GNUC__) && (defined(__DJGPP__) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__i386__))))
#define ENDIAN_LITTLE
#define ENDIAN_32BITWORD
#define LTC_FAST
#define LTC_FAST_TYPE unsigned long
#endif
/* detects MIPS R5900 processors (PS2) */
#if (defined(__R5900) || defined(R5900) || defined(__R5900__)) && (defined(_mips) || defined(__mips__) || defined(mips))
#define ENDIAN_LITTLE
#define ENDIAN_64BITWORD
#endif
/* detect amd64 */
#if !defined(__STRICT_ANSI__) && defined(__x86_64__)
#define ENDIAN_LITTLE
#define ENDIAN_64BITWORD
#define LTC_FAST
#define LTC_FAST_TYPE unsigned long
#endif
/* detect PPC32 */
#if !defined(__STRICT_ANSI__) && defined(LTC_PPC32)
#define ENDIAN_BIG
#define ENDIAN_32BITWORD
#define LTC_FAST
#define LTC_FAST_TYPE unsigned long
#endif
/* detect sparc and sparc64 */
#if defined(__sparc__)
#define ENDIAN_BIG
#if defined(__arch64__)
#define ENDIAN_64BITWORD
#else
#define ENDIAN_32BITWORD
#endif
#endif
#ifdef LTC_NO_FAST
#ifdef LTC_FAST
#undef LTC_FAST
#endif
#endif
/* No asm is a quick way to disable anything "not portable" */
#ifdef LTC_NO_ASM
#undef ENDIAN_LITTLE
#undef ENDIAN_BIG
#undef ENDIAN_32BITWORD
#undef ENDIAN_64BITWORD
#undef LTC_FAST
#undef LTC_FAST_TYPE
#define LTC_NO_ROLC
#define LTC_NO_BSWAP
#endif
/* #define ENDIAN_LITTLE */
/* #define ENDIAN_BIG */
/* #define ENDIAN_32BITWORD */
/* #define ENDIAN_64BITWORD */
#if (defined(ENDIAN_BIG) || defined(ENDIAN_LITTLE)) && !(defined(ENDIAN_32BITWORD) || defined(ENDIAN_64BITWORD))
#error You must specify a word size as well as endianess in tomcrypt_cfg.h
#endif
#if !(defined(ENDIAN_BIG) || defined(ENDIAN_LITTLE))
#define ENDIAN_NEUTRAL
#endif
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_cfg.h,v $ */
/* $Revision: 1.19 $ */
/* $Date: 2006/12/04 02:19:48 $ */

View File

@ -0,0 +1,839 @@
/* ---- SYMMETRIC KEY STUFF -----
*
* We put each of the ciphers scheduled keys in their own structs then we put all of
* the key formats in one union. This makes the function prototypes easier to use.
*/
#ifdef BLOWFISH
struct blowfish_key {
ulong32 S[4][256];
ulong32 K[18];
};
#endif
#ifdef RC5
struct rc5_key {
int rounds;
ulong32 K[50];
};
#endif
#ifdef RC6
struct rc6_key {
ulong32 K[44];
};
#endif
#ifdef SAFERP
struct saferp_key {
unsigned char K[33][16];
long rounds;
};
#endif
#ifdef RIJNDAEL
struct rijndael_key {
ulong32 eK[60], dK[60];
int Nr;
};
#endif
#ifdef KSEED
struct kseed_key {
ulong32 K[32], dK[32];
};
#endif
#ifdef LTC_KASUMI
struct kasumi_key {
ulong32 KLi1[8], KLi2[8],
KOi1[8], KOi2[8], KOi3[8],
KIi1[8], KIi2[8], KIi3[8];
};
#endif
#ifdef XTEA
struct xtea_key {
unsigned long A[32], B[32];
};
#endif
#ifdef TWOFISH
#ifndef TWOFISH_SMALL
struct twofish_key {
ulong32 S[4][256], K[40];
};
#else
struct twofish_key {
ulong32 K[40];
unsigned char S[32], start;
};
#endif
#endif
#ifdef SAFER
#define SAFER_K64_DEFAULT_NOF_ROUNDS 6
#define SAFER_K128_DEFAULT_NOF_ROUNDS 10
#define SAFER_SK64_DEFAULT_NOF_ROUNDS 8
#define SAFER_SK128_DEFAULT_NOF_ROUNDS 10
#define SAFER_MAX_NOF_ROUNDS 13
#define SAFER_BLOCK_LEN 8
#define SAFER_KEY_LEN (1 + SAFER_BLOCK_LEN * (1 + 2 * SAFER_MAX_NOF_ROUNDS))
typedef unsigned char safer_block_t[SAFER_BLOCK_LEN];
typedef unsigned char safer_key_t[SAFER_KEY_LEN];
struct safer_key { safer_key_t key; };
#endif
#ifdef RC2
struct rc2_key { unsigned xkey[64]; };
#endif
#ifdef DES
struct des_key {
ulong32 ek[32], dk[32];
};
struct des3_key {
ulong32 ek[3][32], dk[3][32];
};
#endif
#ifdef CAST5
struct cast5_key {
ulong32 K[32], keylen;
};
#endif
#ifdef NOEKEON
struct noekeon_key {
ulong32 K[4], dK[4];
};
#endif
#ifdef SKIPJACK
struct skipjack_key {
unsigned char key[10];
};
#endif
#ifdef KHAZAD
struct khazad_key {
ulong64 roundKeyEnc[8 + 1];
ulong64 roundKeyDec[8 + 1];
};
#endif
#ifdef ANUBIS
struct anubis_key {
int keyBits;
int R;
ulong32 roundKeyEnc[18 + 1][4];
ulong32 roundKeyDec[18 + 1][4];
};
#endif
typedef union Symmetric_key {
#ifdef DES
struct des_key des;
struct des3_key des3;
#endif
#ifdef RC2
struct rc2_key rc2;
#endif
#ifdef SAFER
struct safer_key safer;
#endif
#ifdef TWOFISH
struct twofish_key twofish;
#endif
#ifdef BLOWFISH
struct blowfish_key blowfish;
#endif
#ifdef RC5
struct rc5_key rc5;
#endif
#ifdef RC6
struct rc6_key rc6;
#endif
#ifdef SAFERP
struct saferp_key saferp;
#endif
#ifdef RIJNDAEL
struct rijndael_key rijndael;
#endif
#ifdef XTEA
struct xtea_key xtea;
#endif
#ifdef CAST5
struct cast5_key cast5;
#endif
#ifdef NOEKEON
struct noekeon_key noekeon;
#endif
#ifdef SKIPJACK
struct skipjack_key skipjack;
#endif
#ifdef KHAZAD
struct khazad_key khazad;
#endif
#ifdef ANUBIS
struct anubis_key anubis;
#endif
#ifdef KSEED
struct kseed_key kseed;
#endif
#ifdef LTC_KASUMI
struct kasumi_key kasumi;
#endif
void *data;
} symmetric_key;
#ifdef LTC_ECB_MODE
/** A block cipher ECB structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen;
/** The scheduled key */
symmetric_key key;
} symmetric_ECB;
#endif
#ifdef LTC_CFB_MODE
/** A block cipher CFB structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen,
/** The padding offset */
padlen;
/** The current IV */
unsigned char IV[MAXBLOCKSIZE],
/** The pad used to encrypt/decrypt */
pad[MAXBLOCKSIZE];
/** The scheduled key */
symmetric_key key;
} symmetric_CFB;
#endif
#ifdef LTC_OFB_MODE
/** A block cipher OFB structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen,
/** The padding offset */
padlen;
/** The current IV */
unsigned char IV[MAXBLOCKSIZE];
/** The scheduled key */
symmetric_key key;
} symmetric_OFB;
#endif
#ifdef LTC_CBC_MODE
/** A block cipher CBC structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen;
/** The current IV */
unsigned char IV[MAXBLOCKSIZE];
/** The scheduled key */
symmetric_key key;
} symmetric_CBC;
#endif
#ifdef LTC_CTR_MODE
/** A block cipher CTR structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen,
/** The padding offset */
padlen,
/** The mode (endianess) of the CTR, 0==little, 1==big */
mode;
/** The counter */
unsigned char ctr[MAXBLOCKSIZE],
/** The pad used to encrypt/decrypt */
pad[MAXBLOCKSIZE];
/** The scheduled key */
symmetric_key key;
} symmetric_CTR;
#endif
#ifdef LTC_LRW_MODE
/** A LRW structure */
typedef struct {
/** The index of the cipher chosen (must be a 128-bit block cipher) */
int cipher;
/** The current IV */
unsigned char IV[16],
/** the tweak key */
tweak[16],
/** The current pad, it's the product of the first 15 bytes against the tweak key */
pad[16];
/** The scheduled symmetric key */
symmetric_key key;
#ifdef LRW_TABLES
/** The pre-computed multiplication table */
unsigned char PC[16][256][16];
#endif
} symmetric_LRW;
#endif
#ifdef LTC_F8_MODE
/** A block cipher F8 structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen,
/** The padding offset */
padlen;
/** The current IV */
unsigned char IV[MAXBLOCKSIZE],
MIV[MAXBLOCKSIZE];
/** Current block count */
ulong32 blockcnt;
/** The scheduled key */
symmetric_key key;
} symmetric_F8;
#endif
/** cipher descriptor table, last entry has "name == NULL" to mark the end of table */
extern struct ltc_cipher_descriptor {
/** name of cipher */
char *name;
/** internal ID */
unsigned char ID;
/** min keysize (octets) */
int min_key_length,
/** max keysize (octets) */
max_key_length,
/** block size (octets) */
block_length,
/** default number of rounds */
default_rounds;
/** Setup the cipher
@param key The input symmetric key
@param keylen The length of the input key (octets)
@param num_rounds The requested number of rounds (0==default)
@param skey [out] The destination of the scheduled key
@return CRYPT_OK if successful
*/
int (*setup)(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
/** Encrypt a block
@param pt The plaintext
@param ct [out] The ciphertext
@param skey The scheduled key
@return CRYPT_OK if successful
*/
int (*ecb_encrypt)(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
/** Decrypt a block
@param ct The ciphertext
@param pt [out] The plaintext
@param skey The scheduled key
@return CRYPT_OK if successful
*/
int (*ecb_decrypt)(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
/** Test the block cipher
@return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
*/
int (*test)(void);
/** Terminate the context
@param skey The scheduled key
*/
void (*done)(symmetric_key *skey);
/** Determine a key size
@param keysize [in/out] The size of the key desired and the suggested size
@return CRYPT_OK if successful
*/
int (*keysize)(int *keysize);
/** Accelerators **/
/** Accelerated ECB encryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_ecb_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, symmetric_key *skey);
/** Accelerated ECB decryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_ecb_decrypt)(const unsigned char *ct, unsigned char *pt, unsigned long blocks, symmetric_key *skey);
/** Accelerated CBC encryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_cbc_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *IV, symmetric_key *skey);
/** Accelerated CBC decryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_cbc_decrypt)(const unsigned char *ct, unsigned char *pt, unsigned long blocks, unsigned char *IV, symmetric_key *skey);
/** Accelerated CTR encryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param mode little or big endian counter (mode=0 or mode=1)
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_ctr_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *IV, int mode, symmetric_key *skey);
/** Accelerated LRW
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param tweak The LRW tweak
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_lrw_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *IV, const unsigned char *tweak, symmetric_key *skey);
/** Accelerated LRW
@param ct Ciphertext
@param pt Plaintext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param tweak The LRW tweak
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_lrw_decrypt)(const unsigned char *ct, unsigned char *pt, unsigned long blocks, unsigned char *IV, const unsigned char *tweak, symmetric_key *skey);
/** Accelerated CCM packet (one-shot)
@param key The secret key to use
@param keylen The length of the secret key (octets)
@param uskey A previously scheduled key [optional can be NULL]
@param nonce The session nonce [use once]
@param noncelen The length of the nonce
@param header The header for the session
@param headerlen The length of the header (octets)
@param pt [out] The plaintext
@param ptlen The length of the plaintext (octets)
@param ct [out] The ciphertext
@param tag [out] The destination tag
@param taglen [in/out] The max size and resulting size of the authentication tag
@param direction Encrypt or Decrypt direction (0 or 1)
@return CRYPT_OK if successful
*/
int (*accel_ccm_memory)(
const unsigned char *key, unsigned long keylen,
symmetric_key *uskey,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
/** Accelerated GCM packet (one shot)
@param key The secret key
@param keylen The length of the secret key
@param IV The initial vector
@param IVlen The length of the initial vector
@param adata The additional authentication data (header)
@param adatalen The length of the adata
@param pt The plaintext
@param ptlen The length of the plaintext (ciphertext length is the same)
@param ct The ciphertext
@param tag [out] The MAC tag
@param taglen [in/out] The MAC tag length
@param direction Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
@return CRYPT_OK on success
*/
int (*accel_gcm_memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
/** Accelerated one shot OMAC
@param key The secret key
@param keylen The key length (octets)
@param in The message
@param inlen Length of message (octets)
@param out [out] Destination for tag
@param outlen [in/out] Initial and final size of out
@return CRYPT_OK on success
*/
int (*omac_memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
/** Accelerated one shot XCBC
@param key The secret key
@param keylen The key length (octets)
@param in The message
@param inlen Length of message (octets)
@param out [out] Destination for tag
@param outlen [in/out] Initial and final size of out
@return CRYPT_OK on success
*/
int (*xcbc_memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
/** Accelerated one shot F9
@param key The secret key
@param keylen The key length (octets)
@param in The message
@param inlen Length of message (octets)
@param out [out] Destination for tag
@param outlen [in/out] Initial and final size of out
@return CRYPT_OK on success
@remark Requires manual padding
*/
int (*f9_memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
} cipher_descriptor[];
#ifdef BLOWFISH
int blowfish_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int blowfish_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int blowfish_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int blowfish_test(void);
void blowfish_done(symmetric_key *skey);
int blowfish_keysize(int *keysize);
extern const struct ltc_cipher_descriptor blowfish_desc;
#endif
#ifdef RC5
int rc5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rc5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rc5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rc5_test(void);
void rc5_done(symmetric_key *skey);
int rc5_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rc5_desc;
#endif
#ifdef RC6
int rc6_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rc6_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rc6_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rc6_test(void);
void rc6_done(symmetric_key *skey);
int rc6_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rc6_desc;
#endif
#ifdef RC2
int rc2_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rc2_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rc2_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rc2_test(void);
void rc2_done(symmetric_key *skey);
int rc2_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rc2_desc;
#endif
#ifdef SAFERP
int saferp_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int saferp_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int saferp_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int saferp_test(void);
void saferp_done(symmetric_key *skey);
int saferp_keysize(int *keysize);
extern const struct ltc_cipher_descriptor saferp_desc;
#endif
#ifdef SAFER
int safer_k64_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_sk64_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_k128_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_sk128_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *key);
int safer_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *key);
int safer_k64_test(void);
int safer_sk64_test(void);
int safer_sk128_test(void);
void safer_done(symmetric_key *skey);
int safer_64_keysize(int *keysize);
int safer_128_keysize(int *keysize);
extern const struct ltc_cipher_descriptor safer_k64_desc, safer_k128_desc, safer_sk64_desc, safer_sk128_desc;
#endif
#ifdef RIJNDAEL
/* make aes an alias */
#define aes_setup rijndael_setup
#define aes_ecb_encrypt rijndael_ecb_encrypt
#define aes_ecb_decrypt rijndael_ecb_decrypt
#define aes_test rijndael_test
#define aes_done rijndael_done
#define aes_keysize rijndael_keysize
#define aes_enc_setup rijndael_enc_setup
#define aes_enc_ecb_encrypt rijndael_enc_ecb_encrypt
#define aes_enc_keysize rijndael_enc_keysize
int rijndael_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rijndael_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rijndael_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rijndael_test(void);
void rijndael_done(symmetric_key *skey);
int rijndael_keysize(int *keysize);
int rijndael_enc_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rijndael_enc_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
void rijndael_enc_done(symmetric_key *skey);
int rijndael_enc_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rijndael_desc, aes_desc;
extern const struct ltc_cipher_descriptor rijndael_enc_desc, aes_enc_desc;
#endif
#ifdef XTEA
int xtea_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int xtea_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int xtea_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int xtea_test(void);
void xtea_done(symmetric_key *skey);
int xtea_keysize(int *keysize);
extern const struct ltc_cipher_descriptor xtea_desc;
#endif
#ifdef TWOFISH
int twofish_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int twofish_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int twofish_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int twofish_test(void);
void twofish_done(symmetric_key *skey);
int twofish_keysize(int *keysize);
extern const struct ltc_cipher_descriptor twofish_desc;
#endif
#ifdef DES
static int des_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
static int des_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
static int des_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
static int des_test(void);
static void des_done(symmetric_key *skey);
static int des_keysize(int *keysize);
static int des3_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
static int des3_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
static int des3_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
static int des3_test(void);
static void des3_done(symmetric_key *skey);
static int des3_keysize(int *keysize);
/* extern const struct ltc_cipher_descriptor des_desc, des3_desc; */
#endif
#ifdef CAST5
int cast5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int cast5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int cast5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int cast5_test(void);
void cast5_done(symmetric_key *skey);
int cast5_keysize(int *keysize);
extern const struct ltc_cipher_descriptor cast5_desc;
#endif
#ifdef NOEKEON
int noekeon_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int noekeon_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int noekeon_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int noekeon_test(void);
void noekeon_done(symmetric_key *skey);
int noekeon_keysize(int *keysize);
extern const struct ltc_cipher_descriptor noekeon_desc;
#endif
#ifdef SKIPJACK
int skipjack_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int skipjack_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int skipjack_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int skipjack_test(void);
void skipjack_done(symmetric_key *skey);
int skipjack_keysize(int *keysize);
extern const struct ltc_cipher_descriptor skipjack_desc;
#endif
#ifdef KHAZAD
int khazad_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int khazad_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int khazad_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int khazad_test(void);
void khazad_done(symmetric_key *skey);
int khazad_keysize(int *keysize);
extern const struct ltc_cipher_descriptor khazad_desc;
#endif
#ifdef ANUBIS
int anubis_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int anubis_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int anubis_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int anubis_test(void);
void anubis_done(symmetric_key *skey);
int anubis_keysize(int *keysize);
extern const struct ltc_cipher_descriptor anubis_desc;
#endif
#ifdef KSEED
int kseed_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int kseed_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int kseed_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int kseed_test(void);
void kseed_done(symmetric_key *skey);
int kseed_keysize(int *keysize);
extern const struct ltc_cipher_descriptor kseed_desc;
#endif
#ifdef LTC_KASUMI
int kasumi_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int kasumi_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int kasumi_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int kasumi_test(void);
void kasumi_done(symmetric_key *skey);
int kasumi_keysize(int *keysize);
extern const struct ltc_cipher_descriptor kasumi_desc;
#endif
#ifdef LTC_ECB_MODE
int ecb_start(int cipher, const unsigned char *key,
int keylen, int num_rounds, symmetric_ECB *ecb);
int ecb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_ECB *ecb);
int ecb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_ECB *ecb);
int ecb_done(symmetric_ECB *ecb);
#endif
#ifdef LTC_CFB_MODE
int cfb_start(int cipher, const unsigned char *IV, const unsigned char *key,
int keylen, int num_rounds, symmetric_CFB *cfb);
int cfb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CFB *cfb);
int cfb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CFB *cfb);
int cfb_getiv(unsigned char *IV, unsigned long *len, symmetric_CFB *cfb);
int cfb_setiv(const unsigned char *IV, unsigned long len, symmetric_CFB *cfb);
int cfb_done(symmetric_CFB *cfb);
#endif
#ifdef LTC_OFB_MODE
int ofb_start(int cipher, const unsigned char *IV, const unsigned char *key,
int keylen, int num_rounds, symmetric_OFB *ofb);
int ofb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_OFB *ofb);
int ofb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_OFB *ofb);
int ofb_getiv(unsigned char *IV, unsigned long *len, symmetric_OFB *ofb);
int ofb_setiv(const unsigned char *IV, unsigned long len, symmetric_OFB *ofb);
int ofb_done(symmetric_OFB *ofb);
#endif
#ifdef LTC_CBC_MODE
int cbc_start(int cipher, const unsigned char *IV, const unsigned char *key,
int keylen, int num_rounds, symmetric_CBC *cbc);
int cbc_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CBC *cbc);
int cbc_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CBC *cbc);
int cbc_getiv(unsigned char *IV, unsigned long *len, symmetric_CBC *cbc);
int cbc_setiv(const unsigned char *IV, unsigned long len, symmetric_CBC *cbc);
int cbc_done(symmetric_CBC *cbc);
#endif
#ifdef LTC_CTR_MODE
#define CTR_COUNTER_LITTLE_ENDIAN 0
#define CTR_COUNTER_BIG_ENDIAN 1
#define LTC_CTR_RFC3686 2
int ctr_start( int cipher,
const unsigned char *IV,
const unsigned char *key, int keylen,
int num_rounds, int ctr_mode,
symmetric_CTR *ctr);
int ctr_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CTR *ctr);
int ctr_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CTR *ctr);
int ctr_getiv(unsigned char *IV, unsigned long *len, symmetric_CTR *ctr);
int ctr_setiv(const unsigned char *IV, unsigned long len, symmetric_CTR *ctr);
int ctr_done(symmetric_CTR *ctr);
int ctr_test(void);
#endif
#ifdef LTC_LRW_MODE
#define LRW_ENCRYPT 0
#define LRW_DECRYPT 1
int lrw_start( int cipher,
const unsigned char *IV,
const unsigned char *key, int keylen,
const unsigned char *tweak,
int num_rounds,
symmetric_LRW *lrw);
int lrw_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_LRW *lrw);
int lrw_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_LRW *lrw);
int lrw_getiv(unsigned char *IV, unsigned long *len, symmetric_LRW *lrw);
int lrw_setiv(const unsigned char *IV, unsigned long len, symmetric_LRW *lrw);
int lrw_done(symmetric_LRW *lrw);
int lrw_test(void);
/* don't call */
int lrw_process(const unsigned char *pt, unsigned char *ct, unsigned long len, int mode, symmetric_LRW *lrw);
#endif
#ifdef LTC_F8_MODE
int f8_start( int cipher, const unsigned char *IV,
const unsigned char *key, int keylen,
const unsigned char *salt_key, int skeylen,
int num_rounds, symmetric_F8 *f8);
int f8_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_F8 *f8);
int f8_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_F8 *f8);
int f8_getiv(unsigned char *IV, unsigned long *len, symmetric_F8 *f8);
int f8_setiv(const unsigned char *IV, unsigned long len, symmetric_F8 *f8);
int f8_done(symmetric_F8 *f8);
int f8_test_mode(void);
#endif
int find_cipher(const char *name);
int find_cipher_any(const char *name, int blocklen, int keylen);
int find_cipher_id(unsigned char ID);
int register_cipher(const struct ltc_cipher_descriptor *cipher);
int unregister_cipher(const struct ltc_cipher_descriptor *cipher);
int cipher_is_valid(int idx);
LTC_MUTEX_PROTO(ltc_cipher_mutex)
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_cipher.h,v $ */
/* $Revision: 1.46 $ */
/* $Date: 2006/11/13 23:09:38 $ */

View File

@ -0,0 +1,403 @@
#ifndef TOMCRYPT_CUSTOM_H_
#define TOMCRYPT_CUSTOM_H_
/* macros for various libc functions you can change for embedded targets */
#ifndef XMALLOC
#ifdef malloc
#define LTC_NO_PROTOTYPES
#endif
#define XMALLOC malloc
#endif
#ifndef XREALLOC
#ifdef realloc
#define LTC_NO_PROTOTYPES
#endif
#define XREALLOC realloc
#endif
#ifndef XCALLOC
#ifdef calloc
#define LTC_NO_PROTOTYPES
#endif
#define XCALLOC calloc
#endif
#ifndef XFREE
#ifdef free
#define LTC_NO_PROTOTYPES
#endif
#define XFREE free
#endif
#ifndef XMEMSET
#ifdef memset
#define LTC_NO_PROTOTYPES
#endif
#define XMEMSET memset
#endif
#ifndef XMEMCPY
#ifdef memcpy
#define LTC_NO_PROTOTYPES
#endif
#define XMEMCPY memcpy
#endif
#ifndef XMEMCMP
#ifdef memcmp
#define LTC_NO_PROTOTYPES
#endif
#define XMEMCMP memcmp
#endif
#ifndef XSTRCMP
#ifdef strcmp
#define LTC_NO_PROTOTYPES
#endif
#define XSTRCMP strcmp
#endif
#ifndef XCLOCK
#define XCLOCK clock
#endif
#ifndef XCLOCKS_PER_SEC
#define XCLOCKS_PER_SEC CLOCKS_PER_SEC
#endif
#ifndef XQSORT
#ifdef qsort
#define LTC_NO_PROTOTYPES
#endif
#define XQSORT qsort
#endif
/* Easy button? */
#ifdef LTC_EASY
#define LTC_NO_CIPHERS
#define RIJNDAEL
#define BLOWFISH
#define DES
#define CAST5
#define LTC_NO_MODES
#define LTC_ECB_MODE
#define LTC_CBC_MODE
#define LTC_CTR_MODE
#define LTC_NO_HASHES
#define SHA1
#define SHA512
#define SHA384
#define SHA256
#define SHA224
#define LTC_NO_MACS
#define HMAC
#define OMAC
#define CCM_MODE
#define LTC_NO_PRNGS
#define SPRNG
#define YARROW
#define DEVRANDOM
#define TRY_URANDOM_FIRST
#define LTC_NO_PK
#define MRSA
#define MECC
#endif
/* Use small code where possible */
/* #define LTC_SMALL_CODE */
/* Enable self-test test vector checking */
#ifndef LTC_NO_TEST
#define LTC_TEST
#endif
/* clean the stack of functions which put private information on stack */
/* #define LTC_CLEAN_STACK */
/* disable all file related functions */
/* #define LTC_NO_FILE */
/* disable all forms of ASM */
/* #define LTC_NO_ASM */
/* disable FAST mode */
/* #define LTC_NO_FAST */
/* disable BSWAP on x86 */
/* #define LTC_NO_BSWAP */
/* ---> Symmetric Block Ciphers <--- */
#ifndef LTC_NO_CIPHERS
#define BLOWFISH
#define RC2
#define RC5
#define RC6
#define SAFERP
#define RIJNDAEL
#define XTEA
/* _TABLES tells it to use tables during setup, _SMALL means to use the smaller scheduled key format
* (saves 4KB of ram), _ALL_TABLES enables all tables during setup */
#define TWOFISH
#ifndef LTC_NO_TABLES
#define TWOFISH_TABLES
/* #define TWOFISH_ALL_TABLES */
#else
#define TWOFISH_SMALL
#endif
/* #define TWOFISH_SMALL */
/* DES includes EDE triple-DES */
#define DES
#define CAST5
#define NOEKEON
#define SKIPJACK
#define SAFER
#define KHAZAD
#define ANUBIS
#define ANUBIS_TWEAK
#define KSEED
#define LTC_KASUMI
#endif /* LTC_NO_CIPHERS */
/* ---> Block Cipher Modes of Operation <--- */
#ifndef LTC_NO_MODES
#define LTC_CFB_MODE
#define LTC_OFB_MODE
#define LTC_ECB_MODE
#define LTC_CBC_MODE
#define LTC_CTR_MODE
/* F8 chaining mode */
#define LTC_F8_MODE
/* LRW mode */
#define LTC_LRW_MODE
#ifndef LTC_NO_TABLES
/* like GCM mode this will enable 16 8x128 tables [64KB] that make
* seeking very fast.
*/
#define LRW_TABLES
#endif
#endif /* LTC_NO_MODES */
/* ---> One-Way Hash Functions <--- */
#ifndef LTC_NO_HASHES
#define CHC_HASH
#define WHIRLPOOL
#define SHA512
#define SHA384
#define SHA256
#define SHA224
#define TIGER
#define SHA1
#define MD5
#define MD4
#define MD2
#define RIPEMD128
#define RIPEMD160
#define RIPEMD256
#define RIPEMD320
#endif /* LTC_NO_HASHES */
/* ---> MAC functions <--- */
#ifndef LTC_NO_MACS
#define LTC_HMAC
#define LTC_OMAC
#define LTC_PMAC
#define LTC_XCBC
#define LTC_F9_MODE
#define PELICAN
#if defined(PELICAN) && !defined(RIJNDAEL)
#error Pelican-MAC requires RIJNDAEL
#endif
/* ---> Encrypt + Authenticate Modes <--- */
#define EAX_MODE
#if defined(EAX_MODE) && !(defined(LTC_CTR_MODE) && defined(LTC_OMAC))
#error EAX_MODE requires CTR and OMAC mode
#endif
#define OCB_MODE
#define CCM_MODE
#define GCM_MODE
/* Use 64KiB tables */
#ifndef LTC_NO_TABLES
#define GCM_TABLES
#endif
/* USE SSE2? requires GCC works on x86_32 and x86_64*/
#ifdef GCM_TABLES
/* #define GCM_TABLES_SSE2 */
#endif
#endif /* LTC_NO_MACS */
/* Various tidbits of modern neatoness */
#define BASE64
/* --> Pseudo Random Number Generators <--- */
#ifndef LTC_NO_PRNGS
/* Yarrow */
#define YARROW
/* which descriptor of AES to use? */
/* 0 = rijndael_enc 1 = aes_enc, 2 = rijndael [full], 3 = aes [full] */
#define YARROW_AES 0
#if defined(YARROW) && !defined(LTC_CTR_MODE)
#error YARROW requires LTC_CTR_MODE chaining mode to be defined!
#endif
/* a PRNG that simply reads from an available system source */
#define SPRNG
/* The RC4 stream cipher */
#define RC4
/* Fortuna PRNG */
#define FORTUNA
/* reseed every N calls to the read function */
#define FORTUNA_WD 10
/* number of pools (4..32) can save a bit of ram by lowering the count */
#define FORTUNA_POOLS 32
/* Greg's SOBER128 PRNG ;-0 */
#define SOBER128
/* the *nix style /dev/random device */
#define DEVRANDOM
/* try /dev/urandom before trying /dev/random */
#define TRY_URANDOM_FIRST
#endif /* LTC_NO_PRNGS */
/* ---> math provider? <--- */
#ifndef LTC_NO_MATH
/* LibTomMath */
/* #define LTM_DESC */
/* TomsFastMath */
/* #define TFM_DESC */
#endif /* LTC_NO_MATH */
/* ---> Public Key Crypto <--- */
#ifndef LTC_NO_PK
/* Include RSA support */
#define MRSA
/* Include Katja (a Rabin variant like RSA) */
/* #define MKAT */
/* Digital Signature Algorithm */
#define MDSA
/* ECC */
#define MECC
/* use Shamir's trick for point mul (speeds up signature verification) */
#define LTC_ECC_SHAMIR
#if defined(TFM_DESC) && defined(MECC)
#define MECC_ACCEL
#endif
/* do we want fixed point ECC */
/* #define MECC_FP */
/* Timing Resistant? */
/* #define LTC_ECC_TIMING_RESISTANT */
#endif /* LTC_NO_PK */
/* PKCS #1 (RSA) and #5 (Password Handling) stuff */
#ifndef LTC_NO_PKCS
#define PKCS_1
#define PKCS_5
/* Include ASN.1 DER (required by DSA/RSA) */
#define LTC_DER
#endif /* LTC_NO_PKCS */
/* cleanup */
#ifdef MECC
/* Supported ECC Key Sizes */
#ifndef LTC_NO_CURVES
#define ECC112
#define ECC128
#define ECC160
#define ECC192
#define ECC224
#define ECC256
#define ECC384
#define ECC521
#endif
#endif
#if defined(MECC) || defined(MRSA) || defined(MDSA) || defined(MKATJA)
/* Include the MPI functionality? (required by the PK algorithms) */
#define MPI
#endif
#ifdef MRSA
#define PKCS_1
#endif
#if defined(LTC_DER) && !defined(MPI)
#error ASN.1 DER requires MPI functionality
#endif
#if (defined(MDSA) || defined(MRSA) || defined(MECC) || defined(MKATJA)) && !defined(LTC_DER)
#error PK requires ASN.1 DER functionality, make sure LTC_DER is enabled
#endif
/* THREAD management */
#ifdef LTC_PTHREAD
#include <pthread.h>
#define LTC_MUTEX_GLOBAL(x) pthread_mutex_t x = PTHREAD_MUTEX_INITIALIZER;
#define LTC_MUTEX_PROTO(x) extern pthread_mutex_t x;
#define LTC_MUTEX_TYPE(x) pthread_mutex_t x;
#define LTC_MUTEX_INIT(x) pthread_mutex_init(x, NULL);
#define LTC_MUTEX_LOCK(x) pthread_mutex_lock(x);
#define LTC_MUTEX_UNLOCK(x) pthread_mutex_unlock(x);
#else
/* default no functions */
#define LTC_MUTEX_GLOBAL(x)
#define LTC_MUTEX_PROTO(x)
#define LTC_MUTEX_TYPE(x)
#define LTC_MUTEX_INIT(x)
#define LTC_MUTEX_LOCK(x)
#define LTC_MUTEX_UNLOCK(x)
#endif
/* Debuggers */
/* define this if you use Valgrind, note: it CHANGES the way SOBER-128 and RC4 work (see the code) */
/* #define LTC_VALGRIND */
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_custom.h,v $ */
/* $Revision: 1.66 $ */
/* $Date: 2006/12/04 02:50:11 $ */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,379 @@
/* ---- HASH FUNCTIONS ---- */
#ifdef SHA512
struct sha512_state {
ulong64 length, state[8];
unsigned long curlen;
unsigned char buf[128];
};
#endif
#ifdef SHA256
struct sha256_state {
ulong64 length;
ulong32 state[8], curlen;
unsigned char buf[64];
};
#endif
#ifdef SHA1
struct sha1_state {
ulong64 length;
ulong32 state[5], curlen;
unsigned char buf[64];
};
#endif
#ifdef MD5
struct md5_state {
ulong64 length;
ulong32 state[4], curlen;
unsigned char buf[64];
};
#endif
#ifdef MD4
struct md4_state {
ulong64 length;
ulong32 state[4], curlen;
unsigned char buf[64];
};
#endif
#ifdef TIGER
struct tiger_state {
ulong64 state[3], length;
unsigned long curlen;
unsigned char buf[64];
};
#endif
#ifdef MD2
struct md2_state {
unsigned char chksum[16], X[48], buf[16];
unsigned long curlen;
};
#endif
#ifdef RIPEMD128
struct rmd128_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[4];
};
#endif
#ifdef RIPEMD160
struct rmd160_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[5];
};
#endif
#ifdef RIPEMD256
struct rmd256_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[8];
};
#endif
#ifdef RIPEMD320
struct rmd320_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[10];
};
#endif
#ifdef WHIRLPOOL
struct whirlpool_state {
ulong64 length, state[8];
unsigned char buf[64];
ulong32 curlen;
};
#endif
#ifdef CHC_HASH
struct chc_state {
ulong64 length;
unsigned char state[MAXBLOCKSIZE], buf[MAXBLOCKSIZE];
ulong32 curlen;
};
#endif
typedef union Hash_state {
char dummy[1];
#ifdef CHC_HASH
struct chc_state chc;
#endif
#ifdef WHIRLPOOL
struct whirlpool_state whirlpool;
#endif
#ifdef SHA512
struct sha512_state sha512;
#endif
#ifdef SHA256
struct sha256_state sha256;
#endif
#ifdef SHA1
struct sha1_state sha1;
#endif
#ifdef MD5
struct md5_state md5;
#endif
#ifdef MD4
struct md4_state md4;
#endif
#ifdef MD2
struct md2_state md2;
#endif
#ifdef TIGER
struct tiger_state tiger;
#endif
#ifdef RIPEMD128
struct rmd128_state rmd128;
#endif
#ifdef RIPEMD160
struct rmd160_state rmd160;
#endif
#ifdef RIPEMD256
struct rmd256_state rmd256;
#endif
#ifdef RIPEMD320
struct rmd320_state rmd320;
#endif
void *data;
} hash_state;
/** hash descriptor */
extern struct ltc_hash_descriptor {
/** name of hash */
char *name;
/** internal ID */
unsigned char ID;
/** Size of digest in octets */
unsigned long hashsize;
/** Input block size in octets */
unsigned long blocksize;
/** ASN.1 OID */
unsigned long OID[16];
/** Length of DER encoding */
unsigned long OIDlen;
/** Init a hash state
@param hash The hash to initialize
@return CRYPT_OK if successful
*/
int (*init)(hash_state *hash);
/** Process a block of data
@param hash The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
int (*process)(hash_state *hash, const unsigned char *in, unsigned long inlen);
/** Produce the digest and store it
@param hash The hash state
@param out [out] The destination of the digest
@return CRYPT_OK if successful
*/
int (*done)(hash_state *hash, unsigned char *out);
/** Self-test
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int (*test)(void);
/* accelerated hmac callback: if you need to-do multiple packets just use the generic hmac_memory and provide a hash callback */
int (*hmac_block)(const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
} hash_descriptor[];
#ifdef CHC_HASH
int chc_register(int cipher);
int chc_init(hash_state * md);
int chc_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int chc_done(hash_state * md, unsigned char *hash);
int chc_test(void);
extern const struct ltc_hash_descriptor chc_desc;
#endif
#ifdef WHIRLPOOL
int whirlpool_init(hash_state * md);
int whirlpool_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int whirlpool_done(hash_state * md, unsigned char *hash);
int whirlpool_test(void);
extern const struct ltc_hash_descriptor whirlpool_desc;
#endif
#ifdef SHA512
int sha512_init(hash_state * md);
int sha512_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha512_done(hash_state * md, unsigned char *hash);
int sha512_test(void);
extern const struct ltc_hash_descriptor sha512_desc;
#endif
#ifdef SHA384
#ifndef SHA512
#error SHA512 is required for SHA384
#endif
int sha384_init(hash_state * md);
#define sha384_process sha512_process
int sha384_done(hash_state * md, unsigned char *hash);
int sha384_test(void);
extern const struct ltc_hash_descriptor sha384_desc;
#endif
#ifdef SHA256
int sha256_init(hash_state * md);
int sha256_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha256_done(hash_state * md, unsigned char *hash);
int sha256_test(void);
extern const struct ltc_hash_descriptor sha256_desc;
#ifdef SHA224
#ifndef SHA256
#error SHA256 is required for SHA224
#endif
int sha224_init(hash_state * md);
#define sha224_process sha256_process
int sha224_done(hash_state * md, unsigned char *hash);
int sha224_test(void);
extern const struct ltc_hash_descriptor sha224_desc;
#endif
#endif
#ifdef SHA1
int sha1_init(hash_state * md);
int sha1_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha1_done(hash_state * md, unsigned char *hash);
int sha1_test(void);
extern const struct ltc_hash_descriptor sha1_desc;
#endif
#ifdef MD5
int md5_init(hash_state * md);
int md5_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md5_done(hash_state * md, unsigned char *hash);
int md5_test(void);
extern const struct ltc_hash_descriptor md5_desc;
#endif
#ifdef MD4
int md4_init(hash_state * md);
int md4_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md4_done(hash_state * md, unsigned char *hash);
int md4_test(void);
extern const struct ltc_hash_descriptor md4_desc;
#endif
#ifdef MD2
int md2_init(hash_state * md);
int md2_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md2_done(hash_state * md, unsigned char *hash);
int md2_test(void);
extern const struct ltc_hash_descriptor md2_desc;
#endif
#ifdef TIGER
int tiger_init(hash_state * md);
int tiger_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int tiger_done(hash_state * md, unsigned char *hash);
int tiger_test(void);
extern const struct ltc_hash_descriptor tiger_desc;
#endif
#ifdef RIPEMD128
int rmd128_init(hash_state * md);
int rmd128_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd128_done(hash_state * md, unsigned char *hash);
int rmd128_test(void);
extern const struct ltc_hash_descriptor rmd128_desc;
#endif
#ifdef RIPEMD160
int rmd160_init(hash_state * md);
int rmd160_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd160_done(hash_state * md, unsigned char *hash);
int rmd160_test(void);
extern const struct ltc_hash_descriptor rmd160_desc;
#endif
#ifdef RIPEMD256
int rmd256_init(hash_state * md);
int rmd256_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd256_done(hash_state * md, unsigned char *hash);
int rmd256_test(void);
extern const struct ltc_hash_descriptor rmd256_desc;
#endif
#ifdef RIPEMD320
int rmd320_init(hash_state * md);
int rmd320_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd320_done(hash_state * md, unsigned char *hash);
int rmd320_test(void);
extern const struct ltc_hash_descriptor rmd320_desc;
#endif
int find_hash(const char *name);
int find_hash_id(unsigned char ID);
int find_hash_oid(const unsigned long *ID, unsigned long IDlen);
int find_hash_any(const char *name, int digestlen);
int register_hash(const struct ltc_hash_descriptor *hash);
int unregister_hash(const struct ltc_hash_descriptor *hash);
int hash_is_valid(int idx);
LTC_MUTEX_PROTO(ltc_hash_mutex)
int hash_memory(int hash,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int hash_memory_multi(int hash, unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int hash_filehandle(int hash, FILE *in, unsigned char *out, unsigned long *outlen);
int hash_file(int hash, const char *fname, unsigned char *out, unsigned long *outlen);
/* a simple macro for making hash "process" functions */
#define HASH_PROCESS(func_name, compress_name, state_var, block_size) \
int func_name (hash_state * md, const unsigned char *in, unsigned long inlen) \
{ \
unsigned long n; \
int err; \
LTC_ARGCHK(md != NULL); \
LTC_ARGCHK(in != NULL); \
if (md-> state_var .curlen > sizeof(md-> state_var .buf)) { \
return CRYPT_INVALID_ARG; \
} \
while (inlen > 0) { \
if (md-> state_var .curlen == 0 && inlen >= block_size) { \
if ((err = compress_name (md, (unsigned char *)in)) != CRYPT_OK) { \
return err; \
} \
md-> state_var .length += block_size * 8; \
in += block_size; \
inlen -= block_size; \
} else { \
n = MIN(inlen, (block_size - md-> state_var .curlen)); \
memcpy(md-> state_var .buf + md-> state_var.curlen, in, (size_t)n); \
md-> state_var .curlen += n; \
in += n; \
inlen -= n; \
if (md-> state_var .curlen == block_size) { \
if ((err = compress_name (md, md-> state_var .buf)) != CRYPT_OK) { \
return err; \
} \
md-> state_var .length += 8*block_size; \
md-> state_var .curlen = 0; \
} \
} \
} \
return CRYPT_OK; \
}
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_hash.h,v $ */
/* $Revision: 1.19 $ */
/* $Date: 2006/11/05 01:36:43 $ */

View File

@ -0,0 +1,381 @@
#ifdef LTC_HMAC
typedef struct Hmac_state {
hash_state md;
int hash;
hash_state hashstate;
unsigned char *key;
} hmac_state;
int hmac_init(hmac_state *hmac, int hash, const unsigned char *key, unsigned long keylen);
int hmac_process(hmac_state *hmac, const unsigned char *in, unsigned long inlen);
int hmac_done(hmac_state *hmac, unsigned char *out, unsigned long *outlen);
int hmac_test(void);
int hmac_memory(int hash,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int hmac_memory_multi(int hash,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int hmac_file(int hash, const char *fname, const unsigned char *key,
unsigned long keylen,
unsigned char *dst, unsigned long *dstlen);
#endif
#ifdef LTC_OMAC
typedef struct {
int cipher_idx,
buflen,
blklen;
unsigned char block[MAXBLOCKSIZE],
prev[MAXBLOCKSIZE],
Lu[2][MAXBLOCKSIZE];
symmetric_key key;
} omac_state;
int omac_init(omac_state *omac, int cipher, const unsigned char *key, unsigned long keylen);
int omac_process(omac_state *omac, const unsigned char *in, unsigned long inlen);
int omac_done(omac_state *omac, unsigned char *out, unsigned long *outlen);
int omac_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int omac_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int omac_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int omac_test(void);
#endif /* OMAC */
#ifdef LTC_PMAC
typedef struct {
unsigned char Ls[32][MAXBLOCKSIZE], /* L shifted by i bits to the left */
Li[MAXBLOCKSIZE], /* value of Li [current value, we calc from previous recall] */
Lr[MAXBLOCKSIZE], /* L * x^-1 */
block[MAXBLOCKSIZE], /* currently accumulated block */
checksum[MAXBLOCKSIZE]; /* current checksum */
symmetric_key key; /* scheduled key for cipher */
unsigned long block_index; /* index # for current block */
int cipher_idx, /* cipher idx */
block_len, /* length of block */
buflen; /* number of bytes in the buffer */
} pmac_state;
int pmac_init(pmac_state *pmac, int cipher, const unsigned char *key, unsigned long keylen);
int pmac_process(pmac_state *pmac, const unsigned char *in, unsigned long inlen);
int pmac_done(pmac_state *pmac, unsigned char *out, unsigned long *outlen);
int pmac_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *msg, unsigned long msglen,
unsigned char *out, unsigned long *outlen);
int pmac_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int pmac_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int pmac_test(void);
/* internal functions */
int pmac_ntz(unsigned long x);
void pmac_shift_xor(pmac_state *pmac);
#endif /* PMAC */
#ifdef EAX_MODE
#if !(defined(LTC_OMAC) && defined(LTC_CTR_MODE))
#error EAX_MODE requires OMAC and CTR
#endif
typedef struct {
unsigned char N[MAXBLOCKSIZE];
symmetric_CTR ctr;
omac_state headeromac, ctomac;
} eax_state;
int eax_init(eax_state *eax, int cipher, const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen);
int eax_encrypt(eax_state *eax, const unsigned char *pt, unsigned char *ct, unsigned long length);
int eax_decrypt(eax_state *eax, const unsigned char *ct, unsigned char *pt, unsigned long length);
int eax_addheader(eax_state *eax, const unsigned char *header, unsigned long length);
int eax_done(eax_state *eax, unsigned char *tag, unsigned long *taglen);
int eax_encrypt_authenticate_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int eax_decrypt_verify_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
unsigned char *tag, unsigned long taglen,
int *stat);
int eax_test(void);
#endif /* EAX MODE */
#ifdef OCB_MODE
typedef struct {
unsigned char L[MAXBLOCKSIZE], /* L value */
Ls[32][MAXBLOCKSIZE], /* L shifted by i bits to the left */
Li[MAXBLOCKSIZE], /* value of Li [current value, we calc from previous recall] */
Lr[MAXBLOCKSIZE], /* L * x^-1 */
R[MAXBLOCKSIZE], /* R value */
checksum[MAXBLOCKSIZE]; /* current checksum */
symmetric_key key; /* scheduled key for cipher */
unsigned long block_index; /* index # for current block */
int cipher, /* cipher idx */
block_len; /* length of block */
} ocb_state;
int ocb_init(ocb_state *ocb, int cipher,
const unsigned char *key, unsigned long keylen, const unsigned char *nonce);
int ocb_encrypt(ocb_state *ocb, const unsigned char *pt, unsigned char *ct);
int ocb_decrypt(ocb_state *ocb, const unsigned char *ct, unsigned char *pt);
int ocb_done_encrypt(ocb_state *ocb,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int ocb_done_decrypt(ocb_state *ocb,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
const unsigned char *tag, unsigned long taglen, int *stat);
int ocb_encrypt_authenticate_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int ocb_decrypt_verify_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
const unsigned char *tag, unsigned long taglen,
int *stat);
int ocb_test(void);
/* internal functions */
void ocb_shift_xor(ocb_state *ocb, unsigned char *Z);
int ocb_ntz(unsigned long x);
int s_ocb_done(ocb_state *ocb, const unsigned char *pt, unsigned long ptlen,
unsigned char *ct, unsigned char *tag, unsigned long *taglen, int mode);
#endif /* OCB_MODE */
#ifdef CCM_MODE
#define CCM_ENCRYPT 0
#define CCM_DECRYPT 1
int ccm_memory(int cipher,
const unsigned char *key, unsigned long keylen,
symmetric_key *uskey,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
int ccm_test(void);
#endif /* CCM_MODE */
#if defined(LRW_MODE) || defined(GCM_MODE)
void gcm_gf_mult(const unsigned char *a, const unsigned char *b, unsigned char *c);
#endif
/* table shared between GCM and LRW */
#if defined(GCM_TABLES) || defined(LRW_TABLES) || ((defined(GCM_MODE) || defined(GCM_MODE)) && defined(LTC_FAST))
extern const unsigned char gcm_shift_table[];
#endif
#ifdef GCM_MODE
#define GCM_ENCRYPT 0
#define GCM_DECRYPT 1
#define GCM_MODE_IV 0
#define GCM_MODE_AAD 1
#define GCM_MODE_TEXT 2
typedef struct {
symmetric_key K;
unsigned char H[16], /* multiplier */
X[16], /* accumulator */
Y[16], /* counter */
Y_0[16], /* initial counter */
buf[16]; /* buffer for stuff */
int cipher, /* which cipher */
ivmode, /* Which mode is the IV in? */
mode, /* mode the GCM code is in */
buflen; /* length of data in buf */
ulong64 totlen, /* 64-bit counter used for IV and AAD */
pttotlen; /* 64-bit counter for the PT */
#ifdef GCM_TABLES
unsigned char PC[16][256][16] /* 16 tables of 8x128 */
#ifdef GCM_TABLES_SSE2
__attribute__ ((aligned (16)))
#endif
;
#endif
} gcm_state;
void gcm_mult_h(gcm_state *gcm, unsigned char *I);
int gcm_init(gcm_state *gcm, int cipher,
const unsigned char *key, int keylen);
int gcm_reset(gcm_state *gcm);
int gcm_add_iv(gcm_state *gcm,
const unsigned char *IV, unsigned long IVlen);
int gcm_add_aad(gcm_state *gcm,
const unsigned char *adata, unsigned long adatalen);
int gcm_process(gcm_state *gcm,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
int direction);
int gcm_done(gcm_state *gcm,
unsigned char *tag, unsigned long *taglen);
int gcm_memory( int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
int gcm_test(void);
#endif /* GCM_MODE */
#ifdef PELICAN
typedef struct pelican_state
{
symmetric_key K;
unsigned char state[16];
int buflen;
} pelican_state;
int pelican_init(pelican_state *pelmac, const unsigned char *key, unsigned long keylen);
int pelican_process(pelican_state *pelmac, const unsigned char *in, unsigned long inlen);
int pelican_done(pelican_state *pelmac, unsigned char *out);
int pelican_test(void);
int pelican_memory(const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out);
#endif
#ifdef LTC_XCBC
typedef struct {
unsigned char K[3][MAXBLOCKSIZE],
IV[MAXBLOCKSIZE];
symmetric_key key;
int cipher,
buflen,
blocksize;
} xcbc_state;
int xcbc_init(xcbc_state *xcbc, int cipher, const unsigned char *key, unsigned long keylen);
int xcbc_process(xcbc_state *xcbc, const unsigned char *in, unsigned long inlen);
int xcbc_done(xcbc_state *xcbc, unsigned char *out, unsigned long *outlen);
int xcbc_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int xcbc_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int xcbc_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int xcbc_test(void);
#endif
#ifdef LTC_F9_MODE
typedef struct {
unsigned char akey[MAXBLOCKSIZE],
ACC[MAXBLOCKSIZE],
IV[MAXBLOCKSIZE];
symmetric_key key;
int cipher,
buflen,
keylen,
blocksize;
} f9_state;
int f9_init(f9_state *f9, int cipher, const unsigned char *key, unsigned long keylen);
int f9_process(f9_state *f9, const unsigned char *in, unsigned long inlen);
int f9_done(f9_state *f9, unsigned char *out, unsigned long *outlen);
int f9_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int f9_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int f9_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int f9_test(void);
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_mac.h,v $ */
/* $Revision: 1.20 $ */
/* $Date: 2006/11/08 21:57:04 $ */

View File

@ -0,0 +1,424 @@
/* fix for MSVC ...evil! */
#ifdef _MSC_VER
#define CONST64(n) n ## ui64
typedef unsigned __int64 ulong64;
#else
#define CONST64(n) n ## ULL
typedef unsigned long long ulong64;
#endif
/* this is the "32-bit at least" data type
* Re-define it to suit your platform but it must be at least 32-bits
*/
#if defined(__x86_64__) || (defined(__sparc__) && defined(__arch64__))
typedef unsigned ulong32;
#else
typedef unsigned long ulong32;
#endif
/* ---- HELPER MACROS ---- */
#ifdef ENDIAN_NEUTRAL
#define STORE32L(x, y) \
{ (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
#define LOAD32L(x, y) \
{ x = ((unsigned long)((y)[3] & 255)<<24) | \
((unsigned long)((y)[2] & 255)<<16) | \
((unsigned long)((y)[1] & 255)<<8) | \
((unsigned long)((y)[0] & 255)); }
#define STORE64L(x, y) \
{ (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
#define LOAD64L(x, y) \
{ x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48)| \
(((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32)| \
(((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16)| \
(((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); }
#define STORE32H(x, y) \
{ (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255); \
(y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }
#define LOAD32H(x, y) \
{ x = ((unsigned long)((y)[0] & 255)<<24) | \
((unsigned long)((y)[1] & 255)<<16) | \
((unsigned long)((y)[2] & 255)<<8) | \
((unsigned long)((y)[3] & 255)); }
#define STORE64H(x, y) \
{ (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }
#define LOAD64H(x, y) \
{ x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48) | \
(((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32) | \
(((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16) | \
(((ulong64)((y)[6] & 255))<<8)|(((ulong64)((y)[7] & 255))); }
#endif /* ENDIAN_NEUTRAL */
#ifdef ENDIAN_LITTLE
#if !defined(LTC_NO_BSWAP) && (defined(INTEL_CC) || (defined(__GNUC__) && (defined(__DJGPP__) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__i386__) || defined(__x86_64__))))
#define STORE32H(x, y) \
asm __volatile__ ( \
"bswapl %0 \n\t" \
"movl %0,(%1)\n\t" \
"bswapl %0 \n\t" \
::"r"(x), "r"(y));
#define LOAD32H(x, y) \
asm __volatile__ ( \
"movl (%1),%0\n\t" \
"bswapl %0\n\t" \
:"=r"(x): "r"(y));
#else
#define STORE32H(x, y) \
{ (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255); \
(y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }
#define LOAD32H(x, y) \
{ x = ((unsigned long)((y)[0] & 255)<<24) | \
((unsigned long)((y)[1] & 255)<<16) | \
((unsigned long)((y)[2] & 255)<<8) | \
((unsigned long)((y)[3] & 255)); }
#endif
/* x86_64 processor */
#if !defined(LTC_NO_BSWAP) && (defined(__GNUC__) && defined(__x86_64__))
#define STORE64H(x, y) \
asm __volatile__ ( \
"bswapq %0 \n\t" \
"movq %0,(%1)\n\t" \
"bswapq %0 \n\t" \
::"r"(x), "r"(y));
#define LOAD64H(x, y) \
asm __volatile__ ( \
"movq (%1),%0\n\t" \
"bswapq %0\n\t" \
:"=r"(x): "r"(y));
#else
#define STORE64H(x, y) \
{ (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }
#define LOAD64H(x, y) \
{ x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48) | \
(((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32) | \
(((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16) | \
(((ulong64)((y)[6] & 255))<<8)|(((ulong64)((y)[7] & 255))); }
#endif
#ifdef ENDIAN_32BITWORD
#define STORE32L(x, y) \
{ ulong32 __t = (x); XMEMCPY(y, &__t, 4); }
#define LOAD32L(x, y) \
XMEMCPY(&(x), y, 4);
#define STORE64L(x, y) \
{ (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
#define LOAD64L(x, y) \
{ x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48)| \
(((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32)| \
(((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16)| \
(((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); }
#else /* 64-bit words then */
#define STORE32L(x, y) \
{ ulong32 __t = (x); XMEMCPY(y, &__t, 4); }
#define LOAD32L(x, y) \
{ XMEMCPY(&(x), y, 4); x &= 0xFFFFFFFF; }
#define STORE64L(x, y) \
{ ulong64 __t = (x); XMEMCPY(y, &__t, 8); }
#define LOAD64L(x, y) \
{ XMEMCPY(&(x), y, 8); }
#endif /* ENDIAN_64BITWORD */
#endif /* ENDIAN_LITTLE */
#ifdef ENDIAN_BIG
#define STORE32L(x, y) \
{ (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
#define LOAD32L(x, y) \
{ x = ((unsigned long)((y)[3] & 255)<<24) | \
((unsigned long)((y)[2] & 255)<<16) | \
((unsigned long)((y)[1] & 255)<<8) | \
((unsigned long)((y)[0] & 255)); }
#define STORE64L(x, y) \
{ (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
#define LOAD64L(x, y) \
{ x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48) | \
(((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32) | \
(((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16) | \
(((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); }
#ifdef ENDIAN_32BITWORD
#define STORE32H(x, y) \
{ ulong32 __t = (x); XMEMCPY(y, &__t, 4); }
#define LOAD32H(x, y) \
XMEMCPY(&(x), y, 4);
#define STORE64H(x, y) \
{ (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }
#define LOAD64H(x, y) \
{ x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48)| \
(((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32)| \
(((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16)| \
(((ulong64)((y)[6] & 255))<<8)| (((ulong64)((y)[7] & 255))); }
#else /* 64-bit words then */
#define STORE32H(x, y) \
{ ulong32 __t = (x); XMEMCPY(y, &__t, 4); }
#define LOAD32H(x, y) \
{ XMEMCPY(&(x), y, 4); x &= 0xFFFFFFFF; }
#define STORE64H(x, y) \
{ ulong64 __t = (x); XMEMCPY(y, &__t, 8); }
#define LOAD64H(x, y) \
{ XMEMCPY(&(x), y, 8); }
#endif /* ENDIAN_64BITWORD */
#endif /* ENDIAN_BIG */
#define BSWAP(x) ( ((x>>24)&0x000000FFUL) | ((x<<24)&0xFF000000UL) | \
((x>>8)&0x0000FF00UL) | ((x<<8)&0x00FF0000UL) )
/* 32-bit Rotates */
#if defined(_MSC_VER)
/* instrinsic rotate */
#include <stdlib.h>
#pragma intrinsic(_lrotr,_lrotl)
#define ROR(x,n) _lrotr(x,n)
#define ROL(x,n) _lrotl(x,n)
#define RORc(x,n) _lrotr(x,n)
#define ROLc(x,n) _lrotl(x,n)
#elif !defined(__STRICT_ANSI__) && defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) && !defined(INTEL_CC) && !defined(LTC_NO_ASM)
static inline unsigned ROL(unsigned word, int i)
{
asm ("roll %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
static inline unsigned ROR(unsigned word, int i)
{
asm ("rorl %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
#ifndef LTC_NO_ROLC
static inline unsigned ROLc(unsigned word, const int i)
{
asm ("roll %2,%0"
:"=r" (word)
:"0" (word),"I" (i));
return word;
}
static inline unsigned RORc(unsigned word, const int i)
{
asm ("rorl %2,%0"
:"=r" (word)
:"0" (word),"I" (i));
return word;
}
#else
#define ROLc ROL
#define RORc ROR
#endif
#elif !defined(__STRICT_ANSI__) && defined(LTC_PPC32)
static inline unsigned ROL(unsigned word, int i)
{
asm ("rotlw %0,%0,%2"
:"=r" (word)
:"0" (word),"r" (i));
return word;
}
static inline unsigned ROR(unsigned word, int i)
{
asm ("rotlw %0,%0,%2"
:"=r" (word)
:"0" (word),"r" (32-i));
return word;
}
#ifndef LTC_NO_ROLC
static inline unsigned ROLc(unsigned word, const int i)
{
asm ("rotlwi %0,%0,%2"
:"=r" (word)
:"0" (word),"I" (i));
return word;
}
static inline unsigned RORc(unsigned word, const int i)
{
asm ("rotrwi %0,%0,%2"
:"=r" (word)
:"0" (word),"I" (i));
return word;
}
#else
#define ROLc ROL
#define RORc ROR
#endif
#else
/* rotates the hard way */
#define ROL(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define ROR(x, y) ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define RORc(x, y) ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#endif
/* 64-bit Rotates */
#if !defined(__STRICT_ANSI__) && defined(__GNUC__) && defined(__x86_64__) && !defined(LTC_NO_ASM)
static inline unsigned long ROL64(unsigned long word, int i)
{
asm("rolq %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
static inline unsigned long ROR64(unsigned long word, int i)
{
asm("rorq %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
#ifndef LTC_NO_ROLC
static inline unsigned long ROL64c(unsigned long word, const int i)
{
asm("rolq %2,%0"
:"=r" (word)
:"0" (word),"J" (i));
return word;
}
static inline unsigned long ROR64c(unsigned long word, const int i)
{
asm("rorq %2,%0"
:"=r" (word)
:"0" (word),"J" (i));
return word;
}
#else /* LTC_NO_ROLC */
#define ROL64c ROL64
#define ROR64c ROR64
#endif
#else /* Not x86_64 */
#define ROL64(x, y) \
( (((x)<<((ulong64)(y)&63)) | \
(((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)64-((y)&63)))) & CONST64(0xFFFFFFFFFFFFFFFF))
#define ROR64(x, y) \
( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)(y)&CONST64(63))) | \
((x)<<((ulong64)(64-((y)&CONST64(63)))))) & CONST64(0xFFFFFFFFFFFFFFFF))
#define ROL64c(x, y) \
( (((x)<<((ulong64)(y)&63)) | \
(((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)64-((y)&63)))) & CONST64(0xFFFFFFFFFFFFFFFF))
#define ROR64c(x, y) \
( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)(y)&CONST64(63))) | \
((x)<<((ulong64)(64-((y)&CONST64(63)))))) & CONST64(0xFFFFFFFFFFFFFFFF))
#endif
#ifndef MAX
#define MAX(x, y) ( ((x)>(y))?(x):(y) )
#endif
#ifndef MIN
#define MIN(x, y) ( ((x)<(y))?(x):(y) )
#endif
/* extract a byte portably */
#ifdef _MSC_VER
#define byte(x, n) ((unsigned char)((x) >> (8 * (n))))
#else
#define byte(x, n) (((x) >> (8 * (n))) & 255)
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_macros.h,v $ */
/* $Revision: 1.15 $ */
/* $Date: 2006/11/29 23:43:57 $ */

View File

@ -0,0 +1,500 @@
/** math functions **/
#define LTC_MP_LT -1
#define LTC_MP_EQ 0
#define LTC_MP_GT 1
#define LTC_MP_NO 0
#define LTC_MP_YES 1
#ifndef MECC
typedef void ecc_point;
#endif
#ifndef MRSA
typedef void rsa_key;
#endif
/** math descriptor */
typedef struct {
/** Name of the math provider */
char *name;
/** Bits per digit, amount of bits must fit in an unsigned long */
int bits_per_digit;
/* ---- init/deinit functions ---- */
/** initialize a bignum
@param a The number to initialize
@return CRYPT_OK on success
*/
int (*init)(void **a);
/** init copy
@param dst The number to initialize and write to
@param src The number to copy from
@return CRYPT_OK on success
*/
int (*init_copy)(void **dst, void *src);
/** deinit
@param a The number to free
@return CRYPT_OK on success
*/
void (*deinit)(void *a);
/* ---- data movement ---- */
/** negate
@param src The number to negate
@param dst The destination
@return CRYPT_OK on success
*/
int (*neg)(void *src, void *dst);
/** copy
@param src The number to copy from
@param dst The number to write to
@return CRYPT_OK on success
*/
int (*copy)(void *src, void *dst);
/* ---- trivial low level functions ---- */
/** set small constant
@param a Number to write to
@param n Source upto bits_per_digit (actually meant for very small constants)
@return CRYPT_OK on succcess
*/
int (*set_int)(void *a, unsigned long n);
/** get small constant
@param a Number to read, only fetches upto bits_per_digit from the number
@return The lower bits_per_digit of the integer (unsigned)
*/
unsigned long (*get_int)(void *a);
/** get digit n
@param a The number to read from
@param n The number of the digit to fetch
@return The bits_per_digit sized n'th digit of a
*/
unsigned long (*get_digit)(void *a, int n);
/** Get the number of digits that represent the number
@param a The number to count
@return The number of digits used to represent the number
*/
int (*get_digit_count)(void *a);
/** compare two integers
@param a The left side integer
@param b The right side integer
@return LTC_MP_LT if a < b, LTC_MP_GT if a > b and LTC_MP_EQ otherwise. (signed comparison)
*/
int (*compare)(void *a, void *b);
/** compare against int
@param a The left side integer
@param b The right side integer (upto bits_per_digit)
@return LTC_MP_LT if a < b, LTC_MP_GT if a > b and LTC_MP_EQ otherwise. (signed comparison)
*/
int (*compare_d)(void *a, unsigned long n);
/** Count the number of bits used to represent the integer
@param a The integer to count
@return The number of bits required to represent the integer
*/
int (*count_bits)(void * a);
/** Count the number of LSB bits which are zero
@param a The integer to count
@return The number of contiguous zero LSB bits
*/
int (*count_lsb_bits)(void *a);
/** Compute a power of two
@param a The integer to store the power in
@param n The power of two you want to store (a = 2^n)
@return CRYPT_OK on success
*/
int (*twoexpt)(void *a , int n);
/* ---- radix conversions ---- */
/** read ascii string
@param a The integer to store into
@param str The string to read
@param radix The radix the integer has been represented in (2-64)
@return CRYPT_OK on success
*/
int (*read_radix)(void *a, const char *str, int radix);
/** write number to string
@param a The integer to store
@param str The destination for the string
@param radix The radix the integer is to be represented in (2-64)
@return CRYPT_OK on success
*/
int (*write_radix)(void *a, char *str, int radix);
/** get size as unsigned char string
@param a The integer to get the size (when stored in array of octets)
@return The length of the integer
*/
unsigned long (*unsigned_size)(void *a);
/** store an integer as an array of octets
@param src The integer to store
@param dst The buffer to store the integer in
@return CRYPT_OK on success
*/
int (*unsigned_write)(void *src, unsigned char *dst);
/** read an array of octets and store as integer
@param dst The integer to load
@param src The array of octets
@param len The number of octets
@return CRYPT_OK on success
*/
int (*unsigned_read)(void *dst, unsigned char *src, unsigned long len);
/* ---- basic math ---- */
/** add two integers
@param a The first source integer
@param b The second source integer
@param c The destination of "a + b"
@return CRYPT_OK on success
*/
int (*add)(void *a, void *b, void *c);
/** add two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_per_digit in length)
@param c The destination of "a + b"
@return CRYPT_OK on success
*/
int (*addi)(void *a, unsigned long b, void *c);
/** subtract two integers
@param a The first source integer
@param b The second source integer
@param c The destination of "a - b"
@return CRYPT_OK on success
*/
int (*sub)(void *a, void *b, void *c);
/** subtract two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_per_digit in length)
@param c The destination of "a - b"
@return CRYPT_OK on success
*/
int (*subi)(void *a, unsigned long b, void *c);
/** multiply two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_per_digit in length)
@param c The destination of "a * b"
@return CRYPT_OK on success
*/
int (*mul)(void *a, void *b, void *c);
/** multiply two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_per_digit in length)
@param c The destination of "a * b"
@return CRYPT_OK on success
*/
int (*muli)(void *a, unsigned long b, void *c);
/** Square an integer
@param a The integer to square
@param b The destination
@return CRYPT_OK on success
*/
int (*sqr)(void *a, void *b);
/** Divide an integer
@param a The dividend
@param b The divisor
@param c The quotient (can be NULL to signify don't care)
@param d The remainder (can be NULL to signify don't care)
@return CRYPT_OK on success
*/
int (*mpdiv)(void *a, void *b, void *c, void *d);
/** divide by two
@param a The integer to divide (shift right)
@param b The destination
@return CRYPT_OK on success
*/
int (*div_2)(void *a, void *b);
/** Get remainder (small value)
@param a The integer to reduce
@param b The modulus (upto bits_per_digit in length)
@param c The destination for the residue
@return CRYPT_OK on success
*/
int (*modi)(void *a, unsigned long b, unsigned long *c);
/** gcd
@param a The first integer
@param b The second integer
@param c The destination for (a, b)
@return CRYPT_OK on success
*/
int (*gcd)(void *a, void *b, void *c);
/** lcm
@param a The first integer
@param b The second integer
@param c The destination for [a, b]
@return CRYPT_OK on success
*/
int (*lcm)(void *a, void *b, void *c);
/** Modular multiplication
@param a The first source
@param b The second source
@param c The modulus
@param d The destination (a*b mod c)
@return CRYPT_OK on success
*/
int (*mulmod)(void *a, void *b, void *c, void *d);
/** Modular squaring
@param a The first source
@param b The modulus
@param c The destination (a*a mod b)
@return CRYPT_OK on success
*/
int (*sqrmod)(void *a, void *b, void *c);
/** Modular inversion
@param a The value to invert
@param b The modulus
@param c The destination (1/a mod b)
@return CRYPT_OK on success
*/
int (*invmod)(void *, void *, void *);
/* ---- reduction ---- */
/** setup montgomery
@param a The modulus
@param b The destination for the reduction digit
@return CRYPT_OK on success
*/
int (*montgomery_setup)(void *a, void **b);
/** get normalization value
@param a The destination for the normalization value
@param b The modulus
@return CRYPT_OK on success
*/
int (*montgomery_normalization)(void *a, void *b);
/** reduce a number
@param a The number [and dest] to reduce
@param b The modulus
@param c The value "b" from montgomery_setup()
@return CRYPT_OK on success
*/
int (*montgomery_reduce)(void *a, void *b, void *c);
/** clean up (frees memory)
@param a The value "b" from montgomery_setup()
@return CRYPT_OK on success
*/
void (*montgomery_deinit)(void *a);
/* ---- exponentiation ---- */
/** Modular exponentiation
@param a The base integer
@param b The power (can be negative) integer
@param c The modulus integer
@param d The destination
@return CRYPT_OK on success
*/
int (*exptmod)(void *a, void *b, void *c, void *d);
/** Primality testing
@param a The integer to test
@param b The destination of the result (FP_YES if prime)
@return CRYPT_OK on success
*/
int (*isprime)(void *a, int *b);
/* ---- (optional) ecc point math ---- */
/** ECC GF(p) point multiplication (from the NIST curves)
@param k The integer to multiply the point by
@param G The point to multiply
@param R The destination for kG
@param modulus The modulus for the field
@param map Boolean indicated whether to map back to affine or not (can be ignored if you work in affine only)
@return CRYPT_OK on success
*/
int (*ecc_ptmul)(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);
/** ECC GF(p) point addition
@param P The first point
@param Q The second point
@param R The destination of P + Q
@param modulus The modulus
@param mp The "b" value from montgomery_setup()
@return CRYPT_OK on success
*/
int (*ecc_ptadd)(ecc_point *P, ecc_point *Q, ecc_point *R, void *modulus, void *mp);
/** ECC GF(p) point double
@param P The first point
@param R The destination of 2P
@param modulus The modulus
@param mp The "b" value from montgomery_setup()
@return CRYPT_OK on success
*/
int (*ecc_ptdbl)(ecc_point *P, ecc_point *R, void *modulus, void *mp);
/** ECC mapping from projective to affine, currently uses (x,y,z) => (x/z^2, y/z^3, 1)
@param P The point to map
@param modulus The modulus
@param mp The "b" value from montgomery_setup()
@return CRYPT_OK on success
@remark The mapping can be different but keep in mind a ecc_point only has three
integers (x,y,z) so if you use a different mapping you have to make it fit.
*/
int (*ecc_map)(ecc_point *P, void *modulus, void *mp);
/** Computes kA*A + kB*B = C using Shamir's Trick
@param A First point to multiply
@param kA What to multiple A by
@param B Second point to multiply
@param kB What to multiple B by
@param C [out] Destination point (can overlap with A or B
@param modulus Modulus for curve
@return CRYPT_OK on success
*/
int (*ecc_mul2add)(ecc_point *A, void *kA,
ecc_point *B, void *kB,
ecc_point *C,
void *modulus);
/* ---- (optional) rsa optimized math (for internal CRT) ---- */
/** RSA Key Generation
@param prng An active PRNG state
@param wprng The index of the PRNG desired
@param size The size of the modulus (key size) desired (octets)
@param e The "e" value (public key). e==65537 is a good choice
@param key [out] Destination of a newly created private key pair
@return CRYPT_OK if successful, upon error all allocated ram is freed
*/
int (*rsa_keygen)(prng_state *prng, int wprng, int size, long e, rsa_key *key);
/** RSA exponentiation
@param in The octet array representing the base
@param inlen The length of the input
@param out The destination (to be stored in an octet array format)
@param outlen The length of the output buffer and the resulting size (zero padded to the size of the modulus)
@param which PK_PUBLIC for public RSA and PK_PRIVATE for private RSA
@param key The RSA key to use
@return CRYPT_OK on success
*/
int (*rsa_me)(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
rsa_key *key);
} ltc_math_descriptor;
extern ltc_math_descriptor ltc_mp;
int ltc_init_multi(void **a, ...);
void ltc_deinit_multi(void *a, ...);
#ifdef LTM_DESC
extern const ltc_math_descriptor ltm_desc;
#endif
#ifdef TFM_DESC
extern const ltc_math_descriptor tfm_desc;
#endif
#ifdef GMP_DESC
extern const ltc_math_descriptor gmp_desc;
#endif
#if !defined(DESC_DEF_ONLY) && defined(LTC_SOURCE)
#define MP_DIGIT_BIT ltc_mp.bits_per_digit
/* some handy macros */
#define mp_init(a) ltc_mp.init(a)
#define mp_init_multi ltc_init_multi
#define mp_clear(a) ltc_mp.deinit(a)
#define mp_clear_multi ltc_deinit_multi
#define mp_init_copy(a, b) ltc_mp.init_copy(a, b)
#define mp_neg(a, b) ltc_mp.neg(a, b)
#define mp_copy(a, b) ltc_mp.copy(a, b)
#define mp_set(a, b) ltc_mp.set_int(a, b)
#define mp_set_int(a, b) ltc_mp.set_int(a, b)
#define mp_get_int(a) ltc_mp.get_int(a)
#define mp_get_digit(a, n) ltc_mp.get_digit(a, n)
#define mp_get_digit_count(a) ltc_mp.get_digit_count(a)
#define mp_cmp(a, b) ltc_mp.compare(a, b)
#define mp_cmp_d(a, b) ltc_mp.compare_d(a, b)
#define mp_count_bits(a) ltc_mp.count_bits(a)
#define mp_cnt_lsb(a) ltc_mp.count_lsb_bits(a)
#define mp_2expt(a, b) ltc_mp.twoexpt(a, b)
#define mp_read_radix(a, b, c) ltc_mp.read_radix(a, b, c)
#define mp_toradix(a, b, c) ltc_mp.write_radix(a, b, c)
#define mp_unsigned_bin_size(a) ltc_mp.unsigned_size(a)
#define mp_to_unsigned_bin(a, b) ltc_mp.unsigned_write(a, b)
#define mp_read_unsigned_bin(a, b, c) ltc_mp.unsigned_read(a, b, c)
#define mp_add(a, b, c) ltc_mp.add(a, b, c)
#define mp_add_d(a, b, c) ltc_mp.addi(a, b, c)
#define mp_sub(a, b, c) ltc_mp.sub(a, b, c)
#define mp_sub_d(a, b, c) ltc_mp.subi(a, b, c)
#define mp_mul(a, b, c) ltc_mp.mul(a, b, c)
#define mp_mul_d(a, b, c) ltc_mp.muli(a, b, c)
#define mp_sqr(a, b) ltc_mp.sqr(a, b)
#define mp_div(a, b, c, d) ltc_mp.mpdiv(a, b, c, d)
#define mp_div_2(a, b) ltc_mp.div_2(a, b)
#define mp_mod(a, b, c) ltc_mp.mpdiv(a, b, NULL, c)
#define mp_mod_d(a, b, c) ltc_mp.modi(a, b, c)
#define mp_gcd(a, b, c) ltc_mp.gcd(a, b, c)
#define mp_lcm(a, b, c) ltc_mp.lcm(a, b, c)
#define mp_mulmod(a, b, c, d) ltc_mp.mulmod(a, b, c, d)
#define mp_sqrmod(a, b, c) ltc_mp.sqrmod(a, b, c)
#define mp_invmod(a, b, c) ltc_mp.invmod(a, b, c)
#define mp_montgomery_setup(a, b) ltc_mp.montgomery_setup(a, b)
#define mp_montgomery_normalization(a, b) ltc_mp.montgomery_normalization(a, b)
#define mp_montgomery_reduce(a, b, c) ltc_mp.montgomery_reduce(a, b, c)
#define mp_montgomery_free(a) ltc_mp.montgomery_deinit(a)
#define mp_exptmod(a,b,c,d) ltc_mp.exptmod(a,b,c,d)
#define mp_prime_is_prime(a, b, c) ltc_mp.isprime(a, c)
#define mp_iszero(a) (mp_cmp_d(a, 0) == LTC_MP_EQ ? LTC_MP_YES : LTC_MP_NO)
#define mp_isodd(a) (mp_get_digit_count(a) > 0 ? (mp_get_digit(a, 0) & 1 ? LTC_MP_YES : LTC_MP_NO) : LTC_MP_NO)
#define mp_exch(a, b) do { void *ABC__tmp = a; a = b; b = ABC__tmp; } while(0);
#define mp_tohex(a, b) mp_toradix(a, b, 16)
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_math.h,v $ */
/* $Revision: 1.43 $ */
/* $Date: 2006/12/02 19:23:13 $ */

View File

@ -0,0 +1,23 @@
/* ---- BASE64 Routines ---- */
#ifdef BASE64
int base64_encode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
int base64_decode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
#endif
/* ---- MEM routines ---- */
void zeromem(void *dst, size_t len);
void burn_stack(unsigned long len);
const char *error_to_string(int err);
extern const char *crypt_build_settings;
/* ---- HMM ---- */
int crypt_fsa(void *mp, ...);
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_misc.h,v $ */
/* $Revision: 1.4 $ */
/* $Date: 2006/11/06 03:03:01 $ */

View File

@ -0,0 +1,544 @@
/* ---- NUMBER THEORY ---- */
enum {
PK_PUBLIC=0,
PK_PRIVATE=1
};
int rand_prime(void *N, long len, prng_state *prng, int wprng);
/* ---- RSA ---- */
#ifdef MRSA
/* Min and Max RSA key sizes (in bits) */
#define MIN_RSA_SIZE 1024
#define MAX_RSA_SIZE 4096
/** RSA PKCS style key */
typedef struct Rsa_key {
/** Type of key, PK_PRIVATE or PK_PUBLIC */
int type;
/** The public exponent */
void *e;
/** The private exponent */
void *d;
/** The modulus */
void *N;
/** The p factor of N */
void *p;
/** The q factor of N */
void *q;
/** The 1/q mod p CRT param */
void *qP;
/** The d mod (p - 1) CRT param */
void *dP;
/** The d mod (q - 1) CRT param */
void *dQ;
} rsa_key;
int rsa_make_key(prng_state *prng, int wprng, int size, long e, rsa_key *key);
int rsa_exptmod(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
rsa_key *key);
void rsa_free(rsa_key *key);
/* These use PKCS #1 v2.0 padding */
#define rsa_encrypt_key(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _prng, _prng_idx, _hash_idx, _key) \
rsa_encrypt_key_ex(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _prng, _prng_idx, _hash_idx, LTC_PKCS_1_OAEP, _key)
#define rsa_decrypt_key(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _hash_idx, _stat, _key) \
rsa_decrypt_key_ex(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _hash_idx, LTC_PKCS_1_OAEP, _stat, _key)
#define rsa_sign_hash(_in, _inlen, _out, _outlen, _prng, _prng_idx, _hash_idx, _saltlen, _key) \
rsa_sign_hash_ex(_in, _inlen, _out, _outlen, LTC_PKCS_1_PSS, _prng, _prng_idx, _hash_idx, _saltlen, _key)
#define rsa_verify_hash(_sig, _siglen, _hash, _hashlen, _hash_idx, _saltlen, _stat, _key) \
rsa_verify_hash_ex(_sig, _siglen, _hash, _hashlen, LTC_PKCS_1_PSS, _hash_idx, _saltlen, _stat, _key)
/* These can be switched between PKCS #1 v2.x and PKCS #1 v1.5 paddings */
int rsa_encrypt_key_ex(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
prng_state *prng, int prng_idx, int hash_idx, int padding, rsa_key *key);
int rsa_decrypt_key_ex(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
int hash_idx, int padding,
int *stat, rsa_key *key);
int rsa_sign_hash_ex(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
int padding,
prng_state *prng, int prng_idx,
int hash_idx, unsigned long saltlen,
rsa_key *key);
int rsa_verify_hash_ex(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int padding,
int hash_idx, unsigned long saltlen,
int *stat, rsa_key *key);
/* PKCS #1 import/export */
int rsa_export(unsigned char *out, unsigned long *outlen, int type, rsa_key *key);
int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key);
#endif
/* ---- Katja ---- */
#ifdef MKAT
/* Min and Max KAT key sizes (in bits) */
#define MIN_KAT_SIZE 1024
#define MAX_KAT_SIZE 4096
/** Katja PKCS style key */
typedef struct KAT_key {
/** Type of key, PK_PRIVATE or PK_PUBLIC */
int type;
/** The private exponent */
void *d;
/** The modulus */
void *N;
/** The p factor of N */
void *p;
/** The q factor of N */
void *q;
/** The 1/q mod p CRT param */
void *qP;
/** The d mod (p - 1) CRT param */
void *dP;
/** The d mod (q - 1) CRT param */
void *dQ;
/** The pq param */
void *pq;
} katja_key;
int katja_make_key(prng_state *prng, int wprng, int size, katja_key *key);
int katja_exptmod(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
katja_key *key);
void katja_free(katja_key *key);
/* These use PKCS #1 v2.0 padding */
int katja_encrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
prng_state *prng, int prng_idx, int hash_idx, katja_key *key);
int katja_decrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
int hash_idx, int *stat,
katja_key *key);
/* PKCS #1 import/export */
int katja_export(unsigned char *out, unsigned long *outlen, int type, katja_key *key);
int katja_import(const unsigned char *in, unsigned long inlen, katja_key *key);
#endif
/* ---- ECC Routines ---- */
#ifdef MECC
/* size of our temp buffers for exported keys */
#define ECC_BUF_SIZE 256
/* max private key size */
#define ECC_MAXSIZE 66
/** Structure defines a NIST GF(p) curve */
typedef struct {
/** The size of the curve in octets */
int size;
/** name of curve */
char *name;
/** The prime that defines the field the curve is in (encoded in hex) */
char *prime;
/** The fields B param (hex) */
char *B;
/** The order of the curve (hex) */
char *order;
/** The x co-ordinate of the base point on the curve (hex) */
char *Gx;
/** The y co-ordinate of the base point on the curve (hex) */
char *Gy;
} ltc_ecc_set_type;
/** A point on a ECC curve, stored in Jacbobian format such that (x,y,z) => (x/z^2, y/z^3, 1) when interpretted as affine */
typedef struct {
/** The x co-ordinate */
void *x;
/** The y co-ordinate */
void *y;
/** The z co-ordinate */
void *z;
} ecc_point;
/** An ECC key */
typedef struct {
/** Type of key, PK_PRIVATE or PK_PUBLIC */
int type;
/** Index into the ltc_ecc_sets[] for the parameters of this curve; if -1, then this key is using user supplied curve in dp */
int idx;
/** pointer to domain parameters; either points to NIST curves (identified by idx >= 0) or user supplied curve */
const ltc_ecc_set_type *dp;
/** The public key */
ecc_point pubkey;
/** The private key */
void *k;
} ecc_key;
/** the ECC params provided */
extern const ltc_ecc_set_type ltc_ecc_sets[];
int ecc_test(void);
void ecc_sizes(int *low, int *high);
int ecc_get_size(ecc_key *key);
int ecc_make_key(prng_state *prng, int wprng, int keysize, ecc_key *key);
int ecc_make_key_ex(prng_state *prng, int wprng, ecc_key *key, const ltc_ecc_set_type *dp);
void ecc_free(ecc_key *key);
int ecc_export(unsigned char *out, unsigned long *outlen, int type, ecc_key *key);
int ecc_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
int ecc_import_ex(const unsigned char *in, unsigned long inlen, ecc_key *key, const ltc_ecc_set_type *dp);
int ecc_ansi_x963_export(ecc_key *key, unsigned char *out, unsigned long *outlen);
int ecc_ansi_x963_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
int ecc_ansi_x963_import_ex(const unsigned char *in, unsigned long inlen, ecc_key *key, ltc_ecc_set_type *dp);
int ecc_shared_secret(ecc_key *private_key, ecc_key *public_key,
unsigned char *out, unsigned long *outlen);
int ecc_encrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, int hash,
ecc_key *key);
int ecc_decrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
ecc_key *key);
int ecc_sign_hash(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, ecc_key *key);
int ecc_verify_hash(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int *stat, ecc_key *key);
/* low level functions */
ecc_point *ltc_ecc_new_point(void);
void ltc_ecc_del_point(ecc_point *p);
int ltc_ecc_is_valid_idx(int n);
/* point ops (mp == montgomery digit) */
#if !defined(MECC_ACCEL) || defined(LTM_DESC) || defined(GMP_DESC)
/* R = 2P */
int ltc_ecc_projective_dbl_point(ecc_point *P, ecc_point *R, void *modulus, void *mp);
/* R = P + Q */
int ltc_ecc_projective_add_point(ecc_point *P, ecc_point *Q, ecc_point *R, void *modulus, void *mp);
#endif
#if defined(MECC_FP)
int ltc_ecc_fp_mulmod(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);
int ltc_ecc_fp_save_state(unsigned char **out, unsigned long *outlen);
int ltc_ecc_fp_restore_state(unsigned char *in, unsigned long inlen);
void ltc_ecc_fp_free(void);
#endif
/* R = kG */
int ltc_ecc_mulmod(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);
#ifdef LTC_ECC_SHAMIR
/* kA*A + kB*B = C */
int ltc_ecc_mul2add(ecc_point *A, void *kA,
ecc_point *B, void *kB,
ecc_point *C,
void *modulus);
#ifdef MECC_FP
int ltc_ecc_fp_mul2add(ecc_point *A, void *kA,
ecc_point *B, void *kB,
ecc_point *C, void *modulus);
#endif
#endif
/* map P to affine from projective */
int ltc_ecc_map(ecc_point *P, void *modulus, void *mp);
#endif
#ifdef MDSA
/* Max diff between group and modulus size in bytes */
#define MDSA_DELTA 512
/* Max DSA group size in bytes (default allows 4k-bit groups) */
#define MDSA_MAX_GROUP 512
/** DSA key structure */
typedef struct {
/** The key type, PK_PRIVATE or PK_PUBLIC */
int type;
/** The order of the sub-group used in octets */
int qord;
/** The generator */
void *g;
/** The prime used to generate the sub-group */
void *q;
/** The large prime that generats the field the contains the sub-group */
void *p;
/** The private key */
void *x;
/** The public key */
void *y;
} dsa_key;
int dsa_make_key(prng_state *prng, int wprng, int group_size, int modulus_size, dsa_key *key);
void dsa_free(dsa_key *key);
int dsa_sign_hash_raw(const unsigned char *in, unsigned long inlen,
void *r, void *s,
prng_state *prng, int wprng, dsa_key *key);
int dsa_sign_hash(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, dsa_key *key);
int dsa_verify_hash_raw( void *r, void *s,
const unsigned char *hash, unsigned long hashlen,
int *stat, dsa_key *key);
int dsa_verify_hash(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int *stat, dsa_key *key);
int dsa_encrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, int hash,
dsa_key *key);
int dsa_decrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
dsa_key *key);
int dsa_import(const unsigned char *in, unsigned long inlen, dsa_key *key);
int dsa_export(unsigned char *out, unsigned long *outlen, int type, dsa_key *key);
int dsa_verify_key(dsa_key *key, int *stat);
int dsa_shared_secret(void *private_key, void *base,
dsa_key *public_key,
unsigned char *out, unsigned long *outlen);
#endif
#ifdef LTC_DER
/* DER handling */
enum {
LTC_ASN1_EOL,
LTC_ASN1_BOOLEAN,
LTC_ASN1_INTEGER,
LTC_ASN1_SHORT_INTEGER,
LTC_ASN1_BIT_STRING,
LTC_ASN1_OCTET_STRING,
LTC_ASN1_NULL,
LTC_ASN1_OBJECT_IDENTIFIER,
LTC_ASN1_IA5_STRING,
LTC_ASN1_PRINTABLE_STRING,
LTC_ASN1_UTF8_STRING,
LTC_ASN1_UTCTIME,
LTC_ASN1_CHOICE,
LTC_ASN1_SEQUENCE,
LTC_ASN1_SET,
LTC_ASN1_SETOF
};
/** A LTC ASN.1 list type */
typedef struct ltc_asn1_list_ {
/** The LTC ASN.1 enumerated type identifier */
int type;
/** The data to encode or place for decoding */
void *data;
/** The size of the input or resulting output */
unsigned long size;
/** The used flag, this is used by the CHOICE ASN.1 type to indicate which choice was made */
int used;
/** prev/next entry in the list */
struct ltc_asn1_list_ *prev, *next, *child, *parent;
} ltc_asn1_list;
#define LTC_SET_ASN1(list, index, Type, Data, Size) \
do { \
int LTC_MACRO_temp = (index); \
ltc_asn1_list *LTC_MACRO_list = (list); \
LTC_MACRO_list[LTC_MACRO_temp].type = (Type); \
LTC_MACRO_list[LTC_MACRO_temp].data = (void*)(Data); \
LTC_MACRO_list[LTC_MACRO_temp].size = (Size); \
LTC_MACRO_list[LTC_MACRO_temp].used = 0; \
} while (0);
/* SEQUENCE */
int der_encode_sequence_ex(ltc_asn1_list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int type_of);
#define der_encode_sequence(list, inlen, out, outlen) der_encode_sequence_ex(list, inlen, out, outlen, LTC_ASN1_SEQUENCE)
int der_decode_sequence_ex(const unsigned char *in, unsigned long inlen,
ltc_asn1_list *list, unsigned long outlen, int ordered);
#define der_decode_sequence(in, inlen, list, outlen) der_decode_sequence_ex(in, inlen, list, outlen, 1)
int der_length_sequence(ltc_asn1_list *list, unsigned long inlen,
unsigned long *outlen);
/* SET */
#define der_decode_set(in, inlen, list, outlen) der_decode_sequence_ex(in, inlen, list, outlen, 0)
#define der_length_set der_length_sequence
int der_encode_set(ltc_asn1_list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_encode_setof(ltc_asn1_list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
/* VA list handy helpers with triplets of <type, size, data> */
int der_encode_sequence_multi(unsigned char *out, unsigned long *outlen, ...);
int der_decode_sequence_multi(const unsigned char *in, unsigned long inlen, ...);
/* FLEXI DECODER handle unknown list decoder */
int der_decode_sequence_flexi(const unsigned char *in, unsigned long *inlen, ltc_asn1_list **out);
void der_free_sequence_flexi(ltc_asn1_list *list);
void der_sequence_free(ltc_asn1_list *in);
/* BOOLEAN */
int der_length_boolean(unsigned long *outlen);
int der_encode_boolean(int in,
unsigned char *out, unsigned long *outlen);
int der_decode_boolean(const unsigned char *in, unsigned long inlen,
int *out);
/* INTEGER */
int der_encode_integer(void *num, unsigned char *out, unsigned long *outlen);
int der_decode_integer(const unsigned char *in, unsigned long inlen, void *num);
int der_length_integer(void *num, unsigned long *len);
/* INTEGER -- handy for 0..2^32-1 values */
int der_decode_short_integer(const unsigned char *in, unsigned long inlen, unsigned long *num);
int der_encode_short_integer(unsigned long num, unsigned char *out, unsigned long *outlen);
int der_length_short_integer(unsigned long num, unsigned long *outlen);
/* BIT STRING */
int der_encode_bit_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_bit_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_bit_string(unsigned long nbits, unsigned long *outlen);
/* OCTET STRING */
int der_encode_octet_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_octet_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_octet_string(unsigned long noctets, unsigned long *outlen);
/* OBJECT IDENTIFIER */
int der_encode_object_identifier(unsigned long *words, unsigned long nwords,
unsigned char *out, unsigned long *outlen);
int der_decode_object_identifier(const unsigned char *in, unsigned long inlen,
unsigned long *words, unsigned long *outlen);
int der_length_object_identifier(unsigned long *words, unsigned long nwords, unsigned long *outlen);
unsigned long der_object_identifier_bits(unsigned long x);
/* IA5 STRING */
int der_encode_ia5_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_ia5_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_ia5_string(const unsigned char *octets, unsigned long noctets, unsigned long *outlen);
int der_ia5_char_encode(int c);
int der_ia5_value_decode(int v);
/* Printable STRING */
int der_encode_printable_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_printable_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_printable_string(const unsigned char *octets, unsigned long noctets, unsigned long *outlen);
int der_printable_char_encode(int c);
int der_printable_value_decode(int v);
/* UTF-8 */
#if (defined(SIZE_MAX) || __STDC_VERSION__ >= 199901L || defined(WCHAR_MAX) || defined(_WCHAR_T) || defined(_WCHAR_T_DEFINED)) && !defined(LTC_NO_WCHAR)
#include <wchar.h>
#else
typedef ulong32 wchar_t;
#endif
int der_encode_utf8_string(const wchar_t *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_utf8_string(const unsigned char *in, unsigned long inlen,
wchar_t *out, unsigned long *outlen);
unsigned long der_utf8_charsize(const wchar_t c);
int der_length_utf8_string(const wchar_t *in, unsigned long noctets, unsigned long *outlen);
/* CHOICE */
int der_decode_choice(const unsigned char *in, unsigned long *inlen,
ltc_asn1_list *list, unsigned long outlen);
/* UTCTime */
typedef struct {
unsigned YY, /* year */
MM, /* month */
DD, /* day */
hh, /* hour */
mm, /* minute */
ss, /* second */
off_dir, /* timezone offset direction 0 == +, 1 == - */
off_hh, /* timezone offset hours */
off_mm; /* timezone offset minutes */
} ltc_utctime;
int der_encode_utctime(ltc_utctime *utctime,
unsigned char *out, unsigned long *outlen);
int der_decode_utctime(const unsigned char *in, unsigned long *inlen,
ltc_utctime *out);
int der_length_utctime(ltc_utctime *utctime, unsigned long *outlen);
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_pk.h,v $ */
/* $Revision: 1.77 $ */
/* $Date: 2006/12/03 00:39:56 $ */

View File

@ -0,0 +1,89 @@
/* PKCS Header Info */
/* ===> PKCS #1 -- RSA Cryptography <=== */
#ifdef PKCS_1
enum ltc_pkcs_1_v1_5_blocks
{
LTC_PKCS_1_EMSA = 1, /* Block type 1 (PKCS #1 v1.5 signature padding) */
LTC_PKCS_1_EME = 2 /* Block type 2 (PKCS #1 v1.5 encryption padding) */
};
enum ltc_pkcs_1_paddings
{
LTC_PKCS_1_V1_5 = 1, /* PKCS #1 v1.5 padding (\sa ltc_pkcs_1_v1_5_blocks) */
LTC_PKCS_1_OAEP = 2, /* PKCS #1 v2.0 encryption padding */
LTC_PKCS_1_PSS = 3 /* PKCS #1 v2.1 signature padding */
};
int pkcs_1_mgf1( int hash_idx,
const unsigned char *seed, unsigned long seedlen,
unsigned char *mask, unsigned long masklen);
int pkcs_1_i2osp(void *n, unsigned long modulus_len, unsigned char *out);
int pkcs_1_os2ip(void *n, unsigned char *in, unsigned long inlen);
/* *** v1.5 padding */
int pkcs_1_v1_5_encode(const unsigned char *msg,
unsigned long msglen,
int block_type,
unsigned long modulus_bitlen,
prng_state *prng,
int prng_idx,
unsigned char *out,
unsigned long *outlen);
int pkcs_1_v1_5_decode(const unsigned char *msg,
unsigned long msglen,
int block_type,
unsigned long modulus_bitlen,
unsigned char *out,
unsigned long *outlen,
int *is_valid);
/* *** v2.1 padding */
int pkcs_1_oaep_encode(const unsigned char *msg, unsigned long msglen,
const unsigned char *lparam, unsigned long lparamlen,
unsigned long modulus_bitlen, prng_state *prng,
int prng_idx, int hash_idx,
unsigned char *out, unsigned long *outlen);
int pkcs_1_oaep_decode(const unsigned char *msg, unsigned long msglen,
const unsigned char *lparam, unsigned long lparamlen,
unsigned long modulus_bitlen, int hash_idx,
unsigned char *out, unsigned long *outlen,
int *res);
int pkcs_1_pss_encode(const unsigned char *msghash, unsigned long msghashlen,
unsigned long saltlen, prng_state *prng,
int prng_idx, int hash_idx,
unsigned long modulus_bitlen,
unsigned char *out, unsigned long *outlen);
int pkcs_1_pss_decode(const unsigned char *msghash, unsigned long msghashlen,
const unsigned char *sig, unsigned long siglen,
unsigned long saltlen, int hash_idx,
unsigned long modulus_bitlen, int *res);
#endif /* PKCS_1 */
/* ===> PKCS #5 -- Password Based Cryptography <=== */
#ifdef PKCS_5
/* Algorithm #1 (old) */
int pkcs_5_alg1(const unsigned char *password, unsigned long password_len,
const unsigned char *salt,
int iteration_count, int hash_idx,
unsigned char *out, unsigned long *outlen);
/* Algorithm #2 (new) */
int pkcs_5_alg2(const unsigned char *password, unsigned long password_len,
const unsigned char *salt, unsigned long salt_len,
int iteration_count, int hash_idx,
unsigned char *out, unsigned long *outlen);
#endif /* PKCS_5 */
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_pkcs.h,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/11/15 12:44:59 $ */

View File

@ -0,0 +1,199 @@
/* ---- PRNG Stuff ---- */
#ifdef YARROW
struct yarrow_prng {
int cipher, hash;
unsigned char pool[MAXBLOCKSIZE];
symmetric_CTR ctr;
LTC_MUTEX_TYPE(prng_lock)
};
#endif
#ifdef RC4
struct rc4_prng {
int x, y;
unsigned char buf[256];
};
#endif
#ifdef FORTUNA
struct fortuna_prng {
hash_state pool[FORTUNA_POOLS]; /* the pools */
symmetric_key skey;
unsigned char K[32], /* the current key */
IV[16]; /* IV for CTR mode */
unsigned long pool_idx, /* current pool we will add to */
pool0_len, /* length of 0'th pool */
wd;
ulong64 reset_cnt; /* number of times we have reset */
LTC_MUTEX_TYPE(prng_lock)
};
#endif
#ifdef SOBER128
struct sober128_prng {
ulong32 R[17], /* Working storage for the shift register */
initR[17], /* saved register contents */
konst, /* key dependent constant */
sbuf; /* partial word encryption buffer */
int nbuf, /* number of part-word stream bits buffered */
flag, /* first add_entropy call or not? */
set; /* did we call add_entropy to set key? */
};
#endif
typedef union Prng_state {
char dummy[1];
#ifdef YARROW
struct yarrow_prng yarrow;
#endif
#ifdef RC4
struct rc4_prng rc4;
#endif
#ifdef FORTUNA
struct fortuna_prng fortuna;
#endif
#ifdef SOBER128
struct sober128_prng sober128;
#endif
} prng_state;
/** PRNG descriptor */
extern struct ltc_prng_descriptor {
/** Name of the PRNG */
char *name;
/** size in bytes of exported state */
int export_size;
/** Start a PRNG state
@param prng [out] The state to initialize
@return CRYPT_OK if successful
*/
int (*start)(prng_state *prng);
/** Add entropy to the PRNG
@param in The entropy
@param inlen Length of the entropy (octets)\
@param prng The PRNG state
@return CRYPT_OK if successful
*/
int (*add_entropy)(const unsigned char *in, unsigned long inlen, prng_state *prng);
/** Ready a PRNG state to read from
@param prng The PRNG state to ready
@return CRYPT_OK if successful
*/
int (*ready)(prng_state *prng);
/** Read from the PRNG
@param out [out] Where to store the data
@param outlen Length of data desired (octets)
@param prng The PRNG state to read from
@return Number of octets read
*/
unsigned long (*read)(unsigned char *out, unsigned long outlen, prng_state *prng);
/** Terminate a PRNG state
@param prng The PRNG state to terminate
@return CRYPT_OK if successful
*/
int (*done)(prng_state *prng);
/** Export a PRNG state
@param out [out] The destination for the state
@param outlen [in/out] The max size and resulting size of the PRNG state
@param prng The PRNG to export
@return CRYPT_OK if successful
*/
int (*pexport)(unsigned char *out, unsigned long *outlen, prng_state *prng);
/** Import a PRNG state
@param in The data to import
@param inlen The length of the data to import (octets)
@param prng The PRNG to initialize/import
@return CRYPT_OK if successful
*/
int (*pimport)(const unsigned char *in, unsigned long inlen, prng_state *prng);
/** Self-test the PRNG
@return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
*/
int (*test)(void);
} prng_descriptor[];
#ifdef YARROW
int yarrow_start(prng_state *prng);
int yarrow_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int yarrow_ready(prng_state *prng);
unsigned long yarrow_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int yarrow_done(prng_state *prng);
int yarrow_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int yarrow_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int yarrow_test(void);
extern const struct ltc_prng_descriptor yarrow_desc;
#endif
#ifdef FORTUNA
int fortuna_start(prng_state *prng);
int fortuna_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int fortuna_ready(prng_state *prng);
unsigned long fortuna_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int fortuna_done(prng_state *prng);
int fortuna_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int fortuna_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int fortuna_test(void);
extern const struct ltc_prng_descriptor fortuna_desc;
#endif
#ifdef RC4
int rc4_start(prng_state *prng);
int rc4_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int rc4_ready(prng_state *prng);
unsigned long rc4_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int rc4_done(prng_state *prng);
int rc4_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int rc4_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int rc4_test(void);
extern const struct ltc_prng_descriptor rc4_desc;
#endif
#ifdef SPRNG
int sprng_start(prng_state *prng);
int sprng_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sprng_ready(prng_state *prng);
unsigned long sprng_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int sprng_done(prng_state *prng);
int sprng_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int sprng_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sprng_test(void);
extern const struct ltc_prng_descriptor sprng_desc;
#endif
#ifdef SOBER128
int sober128_start(prng_state *prng);
int sober128_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sober128_ready(prng_state *prng);
unsigned long sober128_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int sober128_done(prng_state *prng);
int sober128_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int sober128_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sober128_test(void);
extern const struct ltc_prng_descriptor sober128_desc;
#endif
int find_prng(const char *name);
int register_prng(const struct ltc_prng_descriptor *prng);
int unregister_prng(const struct ltc_prng_descriptor *prng);
int prng_is_valid(int idx);
LTC_MUTEX_PROTO(ltc_prng_mutex)
/* Slow RNG you **might** be able to use to seed a PRNG with. Be careful as this
* might not work on all platforms as planned
*/
unsigned long rng_get_bytes(unsigned char *out,
unsigned long outlen,
void (*callback)(void));
int rng_make_prng(int bits, int wprng, prng_state *prng, void (*callback)(void));
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_prng.h,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2006/11/05 01:36:43 $ */

View File

@ -0,0 +1,77 @@
/*
* pycrypto_compat.h: Compatibility with older versions of Python
*
* Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*/
#ifndef PYCRYPTO_COMPAT_H
#define PYCRYPTO_COMPAT_H
#include "Python.h"
/*
* Python 3.x defines, for conditional compiles
*/
#if PY_MAJOR_VERSION >= 3
#define IS_PY3K
#else
#define PyBytes_GET_SIZE PyString_GET_SIZE
#define PyBytes_FromStringAndSize PyString_FromStringAndSize
#define PyBytes_AS_STRING PyString_AS_STRING
#define PyBytes_Check PyString_Check
#define PyBytes_Size PyString_Size
#define PyBytes_AsString PyString_AsString
#define PyBytesObject PyStringObject
#if PY_MINOR_VERSION <= 5 /* PyUnicode_FromString exists from Python 2.6 on up */
#define PyUnicode_FromString PyString_FromString
#endif
#endif
/*
* Py_CLEAR for Python < 2.4
* See http://docs.python.org/api/countingRefs.html
*/
#if PY_VERSION_HEX < 0x02040000 && !defined(Py_CLEAR)
#define Py_CLEAR(obj) \
do {\
PyObject *tmp = (PyObject *)(obj);\
(obj) = NULL;\
Py_XDECREF(tmp);\
} while(0)
#endif
/*
* Compatibility code for Python < 2.5 (see PEP 353)
* PEP 353 has been placed into the public domain, so we can use this code
* without restriction.
*/
#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#endif
/* Compatibility code for Python < 2.3 */
#if PY_VERSION_HEX < 0x02030000
typedef void PyMODINIT_FUNC;
#endif
#endif /* PYCRYPTO_COMPAT_H */
/* vim:set ts=4 sw=4 sts=4 expandtab: */

View File

@ -0,0 +1,364 @@
/* -*- C -*- */
/*
* stream_template.c : Generic framework for stream ciphers
*
* Written by Andrew Kuchling and others
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef _HAVE_STDC_HEADERS
#include <string.h>
#endif
#include "Python.h"
#include "pycrypto_compat.h"
#include "modsupport.h"
#define _STR(x) #x
#define _XSTR(x) _STR(x)
#define _PASTE(x,y) x##y
#define _PASTE2(x,y) _PASTE(x,y)
#ifdef IS_PY3K
#define _MODULE_NAME _PASTE2(PyInit_,MODULE_NAME)
#else
#define _MODULE_NAME _PASTE2(init,MODULE_NAME)
#endif
#define _MODULE_STRING _XSTR(MODULE_NAME)
/*
*
* Python interface
*
*/
typedef struct
{
PyObject_HEAD
stream_state st;
} ALGobject;
/* Please see PEP3123 for a discussion of PyObject_HEAD and changes made in 3.x to make it conform to Standard C.
* These changes also dictate using Py_TYPE to check type, and PyVarObject_HEAD_INIT(NULL, 0) to initialize
*/
#ifdef IS_PY3K
static PyTypeObject ALGtype;
#define is_ALGobject(v) (Py_TYPE(v) == &ALGtype)
#else
staticforward PyTypeObject ALGtype;
#define is_ALGobject(v) ((v)->ob_type == &ALGtype)
#define PyLong_FromLong PyInt_FromLong /* For Python 2.x */
#endif
static ALGobject *
newALGobject(void)
{
ALGobject * new;
new = PyObject_New(ALGobject, &ALGtype);
return new;
}
static void
ALGdealloc(PyObject *ptr)
{
ALGobject *self = (ALGobject *)ptr;
/* Overwrite the contents of the object */
memset((char*)&(self->st), 0, sizeof(stream_state));
PyObject_Del(ptr);
}
static char ALGnew__doc__[] =
"Return a new " _MODULE_STRING " encryption object.";
static char *kwlist[] = {"key", NULL};
static ALGobject *
ALGnew(PyObject *self, PyObject *args, PyObject *kwdict)
{
unsigned char *key;
ALGobject * new;
int keylen;
new = newALGobject();
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s#", kwlist,
&key, &keylen))
{
Py_DECREF(new);
return NULL;
}
if (KEY_SIZE!=0 && keylen != KEY_SIZE)
{
PyErr_SetString(PyExc_ValueError,
_MODULE_STRING " key must be "
"KEY_SIZE bytes long");
return NULL;
}
if (KEY_SIZE== 0 && keylen == 0)
{
PyErr_SetString(PyExc_ValueError,
_MODULE_STRING " key cannot be "
"the null string (0 bytes long)");
return NULL;
}
stream_init(&(new->st), key, keylen);
if (PyErr_Occurred())
{
Py_DECREF(new);
return NULL;
}
return new;
}
static char ALG_Encrypt__doc__[] =
"Decrypt the provided string of binary data.";
static PyObject *
ALG_Encrypt(ALGobject *self, PyObject *args)
{
unsigned char *buffer, *str;
int len;
PyObject *result;
if (!PyArg_Parse(args, "s#", &str, &len))
return NULL;
if (len == 0) /* Handle empty string */
{
return PyBytes_FromStringAndSize(NULL, 0);
}
buffer = malloc(len);
if (buffer == NULL)
{
PyErr_SetString(PyExc_MemoryError, "No memory available in "
_MODULE_STRING " encrypt");
return NULL;
}
Py_BEGIN_ALLOW_THREADS;
memcpy(buffer, str, len);
stream_encrypt(&(self->st), buffer, len);
Py_END_ALLOW_THREADS;
result = PyBytes_FromStringAndSize((char *)buffer, len);
free(buffer);
return (result);
}
static char ALG_Decrypt__doc__[] =
"decrypt(string): Decrypt the provided string of binary data.";
static PyObject *
ALG_Decrypt(ALGobject *self, PyObject *args)
{
unsigned char *buffer, *str;
int len;
PyObject *result;
if (!PyArg_Parse(args, "s#", &str, &len))
return NULL;
if (len == 0) /* Handle empty string */
{
return PyBytes_FromStringAndSize(NULL, 0);
}
buffer = malloc(len);
if (buffer == NULL)
{
PyErr_SetString(PyExc_MemoryError, "No memory available in "
_MODULE_STRING " decrypt");
return NULL;
}
Py_BEGIN_ALLOW_THREADS;
memcpy(buffer, str, len);
stream_decrypt(&(self->st), buffer, len);
Py_END_ALLOW_THREADS;
result = PyBytes_FromStringAndSize((char *)buffer, len);
free(buffer);
return (result);
}
/* ALGobject methods */
static PyMethodDef ALGmethods[] =
{
#ifdef IS_PY3K
{"encrypt", (PyCFunction) ALG_Encrypt, METH_O, ALG_Encrypt__doc__},
{"decrypt", (PyCFunction) ALG_Decrypt, METH_O, ALG_Decrypt__doc__},
#else
{"encrypt", (PyCFunction) ALG_Encrypt, 0, ALG_Encrypt__doc__},
{"decrypt", (PyCFunction) ALG_Decrypt, 0, ALG_Decrypt__doc__},
#endif
{NULL, NULL} /* sentinel */
};
static PyObject *
#ifdef IS_PY3K
ALGgetattro(PyObject *self, PyObject *attr)
#else
ALGgetattr(PyObject *self, char *name)
#endif
{
#ifdef IS_PY3K
if (!PyUnicode_Check(attr))
goto generic;
if (PyUnicode_CompareWithASCIIString(attr, "block_size") == 0)
#else
if (strcmp(name, "block_size") == 0)
#endif
{
return PyLong_FromLong(BLOCK_SIZE);
}
#ifdef IS_PY3K
if (PyUnicode_CompareWithASCIIString(attr, "key_size") == 0)
#else
if (strcmp(name, "key_size") == 0)
#endif
{
return PyLong_FromLong(KEY_SIZE);
}
#ifdef IS_PY3K
generic:
return PyObject_GenericGetAttr(self, attr);
#else
return Py_FindMethod(ALGmethods, self, name);
#endif
}
/* List of functions defined in the module */
static struct PyMethodDef modulemethods[] =
{
{"new", (PyCFunction) ALGnew,
METH_VARARGS|METH_KEYWORDS, ALGnew__doc__},
{NULL, NULL} /* sentinel */
};
static PyTypeObject ALGtype =
{
#ifdef IS_PY3K
PyVarObject_HEAD_INIT(NULL, 0) /* deferred type init for compilation on Windows, type will be filled in at runtime */
#else
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
#endif
_MODULE_STRING, /*tp_name*/
sizeof(ALGobject), /*tp_size*/
0, /*tp_itemsize*/
/* methods */
(destructor) ALGdealloc, /*tp_dealloc*/
0, /*tp_print*/
#ifdef IS_PY3K
0, /*tp_getattr*/
#else
ALGgetattr, /*tp_getattr*/
#endif
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
#ifdef IS_PY3K
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
ALGgetattro, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
ALGmethods, /*tp_methods*/
#endif
};
#ifdef IS_PY3K
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"Crypto.Cipher." _MODULE_STRING,
NULL,
-1,
modulemethods,
NULL,
NULL,
NULL,
NULL
};
#endif
/* Initialization function for the module */
/* Deal with old API in Python 2.1 */
#if PYTHON_API_VERSION < 1011
#define PyModule_AddIntConstant(m,n,v) {PyObject *o=PyInt_FromLong(v); \
if (o!=NULL) \
{PyDict_SetItemString(PyModule_GetDict(m),n,o); Py_DECREF(o);}}
#endif
#ifdef IS_PY3K
PyMODINIT_FUNC
#else
void
#endif
_MODULE_NAME (void)
{
PyObject *m, *d, *x;
#ifdef IS_PY3K
/* PyType_Ready automatically fills in ob_type with &PyType_Type if it's not already set */
if (PyType_Ready(&ALGtype) < 0)
return NULL;
/* Create the module and add the functions */
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
#else
ALGtype.ob_type = &PyType_Type;
/* Create the module and add the functions */
m = Py_InitModule("Crypto.Cipher." _MODULE_STRING, modulemethods);
#endif
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
x = PyUnicode_FromString(_MODULE_STRING ".error");
PyDict_SetItemString(d, "error", x);
PyModule_AddIntConstant(m, "block_size", BLOCK_SIZE);
PyModule_AddIntConstant(m, "key_size", KEY_SIZE);
/* Check for errors */
if (PyErr_Occurred())
Py_FatalError("can't initialize module " _MODULE_STRING);
#ifdef IS_PY3K
return m;
#endif
}
/* vim:set ts=4 sw=4 sts=0 noexpandtab: */

View File

@ -0,0 +1,257 @@
/*
* strxor.c: string XOR functions
*
* Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
*
* ===================================================================
* The contents of this file are dedicated to the public domain. To
* the extent that dedication to the public domain is not available,
* everyone is granted a worldwide, perpetual, royalty-free,
* non-exclusive license to exercise all rights associated with the
* contents of this file for any purpose whatsoever.
* No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ===================================================================
*/
#include "Python.h"
#include <stddef.h>
#include <assert.h>
#include <string.h>
#include "pycrypto_compat.h"
static const char rcsid[] = "$Id$";
/*
* xor_strings - XOR two strings together to produce a third string
*
* dest[0..n-1] := src_a[0..n-1] ^ src_b[0..n-1]
*
*/
static void
xor_strings(char *dest, const char *src_a, const char *src_b, size_t n)
{
size_t i;
/* assert no pointer overflow */
assert(src_a + n > src_a);
assert(src_b + n > src_b);
assert(dest + n > dest);
for (i = 0; i < n; i++) {
dest[i] = src_a[i] ^ src_b[i];
}
}
/*
* xor_string_with_char - XOR a string with a char to produce another string
*
* dest[0..n-1] := src[0..n-1] ^ c
*
*/
static void
xor_string_with_char(char *dest, const char *src, char c, size_t n)
{
size_t i;
/* assert no pointer overflow */
assert(src + n > src);
assert(dest + n > dest);
for (i = 0; i < n; i++) {
dest[i] = src[i] ^ c;
}
}
/*
* "Import assertions"
*
* These runtime checks are performed when this module is first initialized
*
*/
#define IMP_ASSERT(exp) do {\
if (!(exp)) {\
PyErr_Format(PyExc_AssertionError, "%s:%d: assertion failure: '%s'", __FILE__, __LINE__, #exp);\
return;\
}\
} while(0)
static void
runtime_test(void)
{
/* size_t should be able to represent the length of any size buffer */
IMP_ASSERT(sizeof(size_t) == sizeof(void *));
/* we must be able to perform the assignment (Py_ssize_t) -> (size_t)
* as long as the value is non-negative. */
IMP_ASSERT(sizeof(size_t) >= sizeof(Py_ssize_t));
/* char must be one octet */
IMP_ASSERT(sizeof(char) == 1);
/* Perform a basic test of the xor_strings function, including a test for
* an off-by-one bug. */
{
char x[7] = "\x00hello"; /* NUL + "hello" + NUL */
char y[7] = "\xffworld"; /* 0xff + "world" + NUL */
char z[9] = "[ABCDEFG]"; /* "[ABCDEFG]" + NUL */
xor_strings(z+1, x, y, 7);
IMP_ASSERT(!memcmp(z, "[\xff\x1f\x0a\x1e\x00\x0b\x00]", 9));
}
/* Perform a basic test of the xor_string_with_char function, including a test for
* an off-by-one bug. */
{
char x[7] = "\x00hello"; /* NUL + "hello" + NUL */
char y = 170; /* 0xaa */
char z[9] = "[ABCDEFG]"; /* "[ABCDEFG]" + NUL */
xor_string_with_char(z+1, x, y, 7);
IMP_ASSERT(!memcmp(z, "[\xaa\xc2\xcf\xc6\xc6\xc5\xaa]", 9));
}
}
/*
* The strxor Python function
*/
static char strxor__doc__[] =
"strxor(a:str, b:str) -> str\n"
"\n"
"Return a XOR b. Both a and b must have the same length.\n";
static PyObject *
strxor_function(PyObject *self, PyObject *args)
{
PyObject *a, *b, *retval;
Py_ssize_t len_a, len_b;
if (!PyArg_ParseTuple(args, "SS", &a, &b))
return NULL;
len_a = PyBytes_GET_SIZE(a);
len_b = PyBytes_GET_SIZE(b);
assert(len_a >= 0);
assert(len_b >= 0);
if (len_a != len_b) {
PyErr_SetString(PyExc_ValueError, "length of both strings must be equal");
return NULL;
}
/* Create return string */
retval = PyBytes_FromStringAndSize(NULL, len_a);
if (!retval) {
return NULL;
}
/* retval := a ^ b */
xor_strings(PyBytes_AS_STRING(retval), PyBytes_AS_STRING(a), PyBytes_AS_STRING(b), len_a);
return retval;
}
/*
* The strxor_c Python function
*/
static char strxor_c__doc__[] =
"strxor_c(s:str, c:int) -> str\n"
"\n"
"Return s XOR chr(c). c must be in range(256).\n";
static PyObject *
strxor_c_function(PyObject *self, PyObject *args)
{
PyObject *s, *retval;
int c;
Py_ssize_t length;
if (!PyArg_ParseTuple(args, "Si", &s, &c))
return NULL;
if ((c < 0) || (c > 255)) {
PyErr_SetString(PyExc_ValueError, "c must be in range(256)");
return NULL;
}
length = PyBytes_GET_SIZE(s);
assert(length >= 0);
/* Create return string */
retval = PyBytes_FromStringAndSize(NULL, length);
if (!retval) {
return NULL;
}
/* retval := a ^ chr(c)*length */
xor_string_with_char(PyBytes_AS_STRING(retval), PyBytes_AS_STRING(s), (char) c, length);
return retval;
}
/*
* Module-level method table and module initialization function
*/
static PyMethodDef strxor_methods[] = {
{"strxor", strxor_function, METH_VARARGS, strxor__doc__},
{"strxor_c", strxor_c_function, METH_VARARGS, strxor_c__doc__},
{NULL, NULL, 0, NULL} /* end-of-list sentinel value */
};
#ifdef IS_PY3K
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"strxor",
NULL,
-1,
strxor_methods,
NULL,
NULL,
NULL,
NULL
};
#endif
PyMODINIT_FUNC
#ifdef IS_PY3K
PyInit_strxor(void)
#else
initstrxor(void)
#endif
{
PyObject *m;
/* Initialize the module */
#ifdef IS_PY3K
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
#else
m = Py_InitModule("strxor", strxor_methods);
if (m == NULL)
return;
#endif
/* Perform runtime tests */
runtime_test();
#ifdef IS_PY3K
return m;
#endif
}
/* vim:set ts=4 sw=4 sts=4 expandtab: */

View File

@ -0,0 +1,472 @@
/* -*- C -*- */
/*
* Uses Windows CryptoAPI CryptGenRandom to get random bytes.
* The "new" method returns an object, whose "get_bytes" method
* can be called repeatedly to get random bytes, seeded by the
* OS. See the description in the comment at the end.
*
* If you have the Intel Security Driver header files (icsp4ms.h)
* for their hardware random number generator in the 810 and 820 chipsets,
* then define HAVE_INTEL_RNG.
*
* =======================================================================
* The contents of this file are dedicated to the public domain. To the
* extent that dedication to the public domain is not available, everyone
* is granted a worldwide, perpetual, royalty-free, non-exclusive license
* to exercise all rights associated with the contents of this file for
* any purpose whatsoever. No rights are reserved.
*
* 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 AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* =======================================================================
*
*/
/* Author: Mark Moraes */
#include "Python.h"
#include "pycrypto_compat.h"
#ifdef MS_WIN32
#define _WIN32_WINNT 0x400
#define WINSOCK
#include <windows.h>
#include <wincrypt.h>
#ifdef HAVE_INTEL_RNG
# include "icsp4ms.h"
#else
# define PROV_INTEL_SEC 22
# define INTEL_DEF_PROV "Intel Hardware Cryptographic Service Provider"
#endif
/* To-Do: store provider name and type for print/repr? */
typedef struct
{
PyObject_HEAD
HCRYPTPROV hcp;
} WRobject;
/* Please see PEP3123 for a discussion of PyObject_HEAD and changes made in 3.x to make it conform to Standard C.
* These changes also dictate using Py_TYPE to check type, and PyVarObject_HEAD_INIT(NULL, 0) to initialize
*/
#ifdef IS_PY3K
static PyTypeObject WRtype;
#define is_WRobject(v) (Py_TYPE(v) == &WRtype)
#else
staticforward PyTypeObject WRtype;
#define is_WRobject(v) ((v)->ob_type == &WRtype)
#define PyLong_FromLong PyInt_FromLong /* for Python 2.x */
#endif
static void
WRdealloc(PyObject *ptr)
{
WRobject *o = (WRobject *)ptr;
if (! is_WRobject(ptr)) {
PyErr_Format(PyExc_TypeError,
"WinRandom trying to dealloc non-WinRandom object");
return;
}
if (! CryptReleaseContext(o->hcp, 0)) {
PyErr_Format(PyExc_SystemError,
"CryptReleaseContext failed, error 0x%x",
(unsigned int) GetLastError());
return;
}
/* Overwrite the contents of the object */
o->hcp = 0;
PyObject_Del(ptr);
}
static char winrandom__doc__[] =
"new([provider], [provtype]): Returns an object handle to Windows\n\
CryptoAPI that can be used to access a cryptographically strong\n\
pseudo-random generator that uses OS-gathered entropy.\n\
Provider is a string that specifies the Cryptographic Service Provider\n\
to use, default is the default OS CSP.\n\
provtype is an integer specifying the provider type to use, default\n\
is 1 (PROV_RSA_FULL)";
static char WR_get_bytes__doc__[] =
"get_bytes(nbytes, [userdata]]): Returns nbytes of random data\n\
from Windows CryptGenRandom.\n\
userdata is a string with any additional entropic data that the\n\
user wishes to provide.";
static WRobject *
winrandom_new(PyObject *self, PyObject *args, PyObject *kwdict)
{
HCRYPTPROV hcp = 0;
WRobject *res;
char *provname = NULL;
int provtype = PROV_RSA_FULL;
static char *kwlist[] = { "provider", "provtype", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|si", kwlist,
&provname, &provtype)) {
return NULL;
}
if (! CryptAcquireContext(&hcp, NULL, (LPCTSTR) provname,
(DWORD) provtype,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
PyErr_Format(PyExc_SystemError,
"CryptAcquireContext for provider \"%s\" type %i failed, error 0x%x",
provname? provname : "(null)", provtype,
(unsigned int) GetLastError());
return NULL;
}
res = PyObject_New(WRobject, &WRtype);
res->hcp = hcp;
return res;
}
static PyObject *
WR_get_bytes(WRobject *self, PyObject *args)
{
int n, nbytes, len = 0;
PyObject *res;
char *buf, *str = NULL;
if (! is_WRobject(self)) {
PyErr_Format(PyExc_TypeError,
"WinRandom trying to get_bytes with non-WinRandom object");
return NULL;
}
if (!PyArg_ParseTuple(args, "i|s#", &n, &str, &len)) {
return NULL;
}
if (n <= 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be positive number");
return NULL;
}
/* Just in case char != BYTE, or userdata > desired result */
nbytes = (((n > len) ? n : len) * sizeof(char)) / sizeof(BYTE) + 1;
if ((buf = (char *) PyMem_Malloc(nbytes)) == NULL)
return PyErr_NoMemory();
if (len > 0)
memcpy(buf, str, len);
/*
* if userdata > desired result, we end up getting
* more bytes than we really needed to return. No
* easy way to avoid that: we prefer that
* CryptGenRandom does the distillation of userdata
* down to entropy, rather than trying to do it
* ourselves. Since the extra bytes presumably come
* from an RC4 stream, they should be relatively
* cheap.
*/
if (! CryptGenRandom(self->hcp, (DWORD) nbytes, (BYTE *) buf)) {
PyErr_Format(PyExc_SystemError,
"CryptGenRandom failed, error 0x%x",
(unsigned int) GetLastError());
PyMem_Free(buf);
return NULL;
}
res = PyBytes_FromStringAndSize(buf, n);
PyMem_Free(buf);
return res;
}
/* WinRandom object methods */
static PyMethodDef WRmethods[] =
{
{"get_bytes", (PyCFunction) WR_get_bytes, METH_VARARGS,
WR_get_bytes__doc__},
{NULL, NULL} /* sentinel */
};
/* winrandom module methods */
static PyMethodDef WR_mod_methods[] = {
{"new", (PyCFunction) winrandom_new, METH_VARARGS|METH_KEYWORDS,
winrandom__doc__},
{NULL, NULL} /* Sentinel */
};
static PyObject *
#ifdef IS_PY3K
WRgetattro(PyObject *s, PyObject *attr)
#else
WRgetattr(PyObject *s, char *name)
#endif
{
WRobject *self = (WRobject*)s;
if (! is_WRobject(self)) {
PyErr_Format(PyExc_TypeError,
"WinRandom trying to getattr with non-WinRandom object");
return NULL;
}
#ifdef IS_PY3K
if (!PyUnicode_Check(attr))
goto generic;
if (PyUnicode_CompareWithASCIIString(attr, "hcp") == 0)
#else
if (strcmp(name, "hcp") == 0)
#endif
return PyLong_FromLong((long) self->hcp);
#ifdef IS_PY3K
generic:
return PyObject_GenericGetAttr(s, attr);
#else
return Py_FindMethod(WRmethods, (PyObject *) self, name);
#endif
}
static PyTypeObject WRtype =
{
#ifdef IS_PY3K
PyVarObject_HEAD_INIT(NULL, 0) /* deferred type init for compilation on Windows, type will be filled in at runtime */
#else
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
#endif
"winrandom.WinRandom", /*tp_name*/
sizeof(WRobject), /*tp_size*/
0, /*tp_itemsize*/
/* methods */
(destructor) WRdealloc, /*tp_dealloc*/
0, /*tp_print*/
#ifndef IS_PY3K
WRgetattr, /*tp_getattr*/
#else
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number */
0, /*tp_as_sequence */
0, /*tp_as_mapping */
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
WRgetattro, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
WRmethods, /*tp_methods*/
#endif
};
#ifdef IS_PY3K
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"winrandom",
NULL,
-1,
WR_mod_methods,
NULL,
NULL,
NULL,
NULL
};
#endif
#ifdef IS_PY3K
PyMODINIT_FUNC
PyInit_winrandom()
#else
void
initwinrandom()
#endif
{
PyObject *m;
#ifdef IS_PY3K
/* PyType_Ready automatically fills in ob_type with &PyType_Type if it's not already set */
if (PyType_Ready(&WRtype) < 0)
return NULL;
/* Initialize the module */
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
#else
WRtype.ob_type = &PyType_Type;
m = Py_InitModule("winrandom", WR_mod_methods);
#endif
/* define Windows CSP Provider Types */
#ifdef PROV_RSA_FULL
PyModule_AddIntConstant(m, "PROV_RSA_FULL", PROV_RSA_FULL);
#endif
#ifdef PROV_RSA_SIG
PyModule_AddIntConstant(m, "PROV_RSA_SIG", PROV_RSA_SIG);
#endif
#ifdef PROV_DSS
PyModule_AddIntConstant(m, "PROV_DSS", PROV_DSS);
#endif
#ifdef PROV_FORTEZZA
PyModule_AddIntConstant(m, "PROV_FORTEZZA", PROV_FORTEZZA);
#endif
#ifdef PROV_MS_EXCHANGE
PyModule_AddIntConstant(m, "PROV_MS_EXCHANGE", PROV_MS_EXCHANGE);
#endif
#ifdef PROV_SSL
PyModule_AddIntConstant(m, "PROV_SSL", PROV_SSL);
#endif
#ifdef PROV_RSA_SCHANNEL
PyModule_AddIntConstant(m, "PROV_RSA_SCHANNEL", PROV_RSA_SCHANNEL);
#endif
#ifdef PROV_DSS_DH
PyModule_AddIntConstant(m, "PROV_DSS_DH", PROV_DSS_DH);
#endif
#ifdef PROV_EC_ECDSA_SIG
PyModule_AddIntConstant(m, "PROV_EC_ECDSA_SIG", PROV_EC_ECDSA_SIG);
#endif
#ifdef PROV_EC_ECNRA_SIG
PyModule_AddIntConstant(m, "PROV_EC_ECNRA_SIG", PROV_EC_ECNRA_SIG);
#endif
#ifdef PROV_EC_ECDSA_FULL
PyModule_AddIntConstant(m, "PROV_EC_ECDSA_FULL", PROV_EC_ECDSA_FULL);
#endif
#ifdef PROV_EC_ECNRA_FULL
PyModule_AddIntConstant(m, "PROV_EC_ECNRA_FULL", PROV_EC_ECNRA_FULL);
#endif
#ifdef PROV_SPYRUS_LYNKS
PyModule_AddIntConstant(m, "PROV_SPYRUS_LYNKS", PROV_SPYRUS_LYNKS);
#endif
#ifdef PROV_INTEL_SEC
PyModule_AddIntConstant(m, "PROV_INTEL_SEC", PROV_INTEL_SEC);
#endif
/* Define Windows CSP Provider Names */
#ifdef MS_DEF_PROV
PyModule_AddStringConstant(m, "MS_DEF_PROV", MS_DEF_PROV);
#endif
#ifdef MS_ENHANCED_PROV
PyModule_AddStringConstant(m, "MS_ENHANCED_PROV", MS_ENHANCED_PROV);
#endif
#ifdef MS_DEF_RSA_SIG_PROV
PyModule_AddStringConstant(m, "MS_DEF_RSA_SIG_PROV",
MS_DEF_RSA_SIG_PROV);
#endif
#ifdef MS_DEF_RSA_SCHANNEL_PROV
PyModule_AddStringConstant(m, "MS_DEF_RSA_SCHANNEL_PROV",
MS_DEF_RSA_SCHANNEL_PROV);
#endif
#ifdef MS_ENHANCED_RSA_SCHANNEL_PROV
PyModule_AddStringConstant(m, "MS_ENHANCED_RSA_SCHANNEL_PROV",
MS_ENHANCED_RSA_SCHANNEL_PROV);
#endif
#ifdef MS_DEF_DSS_PROV
PyModule_AddStringConstant(m, "MS_DEF_DSS_PROV", MS_DEF_DSS_PROV);
#endif
#ifdef MS_DEF_DSS_DH_PROV
PyModule_AddStringConstant(m, "MS_DEF_DSS_DH_PROV",
MS_DEF_DSS_DH_PROV);
#endif
#ifdef INTEL_DEF_PROV
PyModule_AddStringConstant(m, "INTEL_DEF_PROV", INTEL_DEF_PROV);
#endif
if (PyErr_Occurred())
Py_FatalError("can't initialize module winrandom");
#ifdef IS_PY3K
return m;
#endif
}
/*
CryptGenRandom usage is described in
http://msdn.microsoft.com/library/en-us/security/security/cryptgenrandom.asp
and many associated pages on Windows Cryptographic Service
Providers, which say:
With Microsoft CSPs, CryptGenRandom uses the same
random number generator used by other security
components. This allows numerous processes to
contribute to a system-wide seed. CryptoAPI stores
an intermediate random seed with every user. To form
the seed for the random number generator, a calling
application supplies bits it might havefor instance,
mouse or keyboard timing inputthat are then added to
both the stored seed and various system data and
user data such as the process ID and thread ID, the
system clock, the system time, the system counter,
memory status, free disk clusters, the hashed user
environment block. This result is SHA-1 hashed, and
the output is used to seed an RC4 stream, which is
then used as the random stream and used to update
the stored seed.
The only other detailed description I've found of the
sources of randomness for CryptGenRandom is this excerpt
from a posting
http://www.der-keiler.de/Newsgroups/comp.security.ssh/2002-06/0169.html
From: Jon McClelland (dowot69@hotmail.com)
Date: 06/12/02
...
Windows, call a function such as CryptGenRandom, which has two of
the properties of a good random number generator, unpredictability and
even value distribution. This function, declared in Wincrypt.h, is
available on just about every Windows platform, including Windows 95
with Internet Explorer 3.02 or later, Windows 98, Windows Me, Windows
CE v3, Windows NT 4, Windows 2000, and Windows XP.
CryptGenRandom gets its randomness, also known as entropy, from many
sources in Windows 2000, including the following:
The current process ID (GetCurrentProcessID).
The current thread ID (GetCurrentThreadID).
The ticks since boot (GetTickCount).
The current time (GetLocalTime).
Various high-precision performance counters (QueryPerformanceCounter).
A Message Digest 4 (MD4) hash of the user's environment block, which
includes username, computer name, and search path.
High-precision internal CPU counters, such as RDTSC, RDMSR, RDPMC (x86
only-more information about these counters is at
developer.intel.com/software/idap/resources/technical_collateral/pentiumii/RDTSCPM1.HTM
<http://developer.intel.com>).
Low-level system information, such as idle time, kernel time,
interrupt times, commit limit, page read count, cache read count,
nonpaged pool allocations, alignment fixup count, operating system
lookaside information.
Such information is added to a buffer, which is hashed using MD4 and
used as the key to modify a buffer, using RC4, provided by the user.
(Refer to the CryptGenRandom documentation in the Platform SDK for
more information about the user-provided buffer.) Hence, if the user
provides additional data in the buffer, this is used as an element in
the witches brew to generate the random data. The result is a
cryptographically random number generator.
Also, note that if you plan to sell your software to the United States
federal government, you'll need to use FIPS 140-1-approved algorithms.
The default versions of CryptGenRandom in Microsoft Windows CE v3,
Windows 95, Windows 98, Windows Me, Windows 2000, and Windows XP are
FIPS-approved. Obviously FIPS-140 compliance is necessary but not
sufficient to provide a properly secure source of random data.
*/
/*
[Update: 2007-11-13]
CryptGenRandom does not necessarily provide forward secrecy or reverse
secrecy. See the paper by Leo Dorrendorf and Zvi Gutterman and Benny
Pinkas, _Cryptanalysis of the Random Number Generator of the Windows
Operating System_, Cryptology ePrint Archive, Report 2007/419,
http://eprint.iacr.org/2007/419
*/
#endif /* MS_WIN32 */

View File

@ -0,0 +1,6 @@
*.pyc
.idea
dist
build
MANIFEST
TODO

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 hellman ( hellman1908@gmail.com )
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,109 @@
xortool.py
====================
A tool to do some xor analysis:
- guess the key length (based on count of equal chars)
- guess the key (base on knowledge of most frequent char)
Usage
---------------------
! *python3 is not supported, use python 2.x*
<pre>
xortool [-h|--help] [OPTIONS] [&lt;filename&gt;]
Options:
-l,--key-length length of the key (integer)
-c,--char most possible char (one char or hex code)
-m,--max-keylen=32 maximum key length to probe (integer)
-x,--hex input is hex-encoded str
-b,--brute-chars brute-force all possible characters
-o,--brute-printable same as -b but will only use printable
characters for keys
</pre>
Example
---------------------
<pre>
# xor is tools/xor.py
tests $ xor -f /bin/ls -s "secret_key" > binary_xored
tests $ xortool binary_xored
The most probable key lengths:
2: 5.0%
5: 8.7%
8: 4.9%
10: 15.4%
12: 4.8%
15: 8.5%
18: 4.8%
20: 15.1%
25: 8.4%
30: 14.9%
Key-length can be 5*n
Most possible char is needed to guess the key!
# 00 is the most frequent byte in binaries
tests $ xortool binary_xored -l 10 -c 00
...
1 possible key(s) of length 10:
secret_key
# decrypted ciphertexts are placed in ./xortool_out/Number_&lt;key repr&gt;
# ( have no better idea )
tests $ md5sum xortool_out/0_secret_key /bin/ls
29942e290876703169e1b614d0b4340a xortool_out/0_secret_key
29942e290876703169e1b614d0b4340a /bin/ls
</pre>
The most common use is to pass just the encrypted file and the most frequent character (usually 00 for binaries and 20 for text files) - length will be automatically chosen:
<pre>
tests $ xortool tool_xored -c 20
The most probable key lengths:
2: 5.6%
5: 7.8%
8: 6.0%
10: 11.7%
12: 5.6%
15: 7.6%
20: 19.8%
25: 7.8%
28: 5.7%
30: 11.4%
Key-length can be 5*n
1 possible key(s) of length 20:
an0ther s3cret \xdd key
</pre>
Here, the key is longer then default 32 limit:
<pre>
tests $ xortool ls_xored -c 00 -m 64
The most probable key lengths:
3: 3.3%
6: 3.3%
9: 3.3%
11: 7.0%
22: 6.9%
24: 3.3%
27: 3.2%
33: 18.4%
44: 6.8%
55: 6.7%
Key-length can be 3*n
1 possible key(s) of length 33:
really long s3cr3t k3y... PADDING
</pre>
So, if automated decryption fails, you can calibrate:
- (-m) max length to try longer keys
- (-l) selected length to see some interesting keys
- (-c) the most frequent char to produce right plaintext
Author: hellman ( hellman1908@gmail.com )
License: MIT License (opensource.org/licenses/MIT)

View File

@ -0,0 +1,35 @@
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from distutils.core import setup
import xortool
setup(name='xortool',
version=xortool.__version__,
author='hellman',
author_email='hellman1908@gmail.com',
license="MIT",
url='https://github.com/hellman/xortool',
description='Tool for xor cipher analysis',
long_description=open("README.md").read(), # not in rst, but something
keywords="xor xortool analysis",
packages=['xortool'],
provides=['xortool'],
install_requires=['docopt>=0.6.1'],
scripts=["xortool/xortool", "xortool/xortool-xor"],
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'Intended Audience :: Information Technology',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'License :: OSI Approved :: MIT License',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Security :: Cryptography',
],
)

Binary file not shown.

View File

@ -0,0 +1 @@
ラ込マ<EFBFBD>瞹悴采<EFBFBD>ニミ€ゥテ檮ォハヘマ<EFBFBD>ロ擡フラ<EFBFBD>ヤ棘サ゚ヌマキテン€ウンメ巻ネ怜ラ込マ<EFBFBD>€<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>灘ヤ<EFBFBD>€ヘ崛タホユ<EFBFBD>糟゚郞奈蕫鈷<EFBFBD>怕ユ巐<EFBFBD><EFBFBD>レ攴ンホ堪洞蜉ナラ<EFBFBD>ヒムΥツノ<EFBFBD>ハ档ギハマスツミ崛トミ<EFBFBD>ルヨ€ュネ檮ォハヘマゥナラ幻桜ネウ罪仭゚ロマアヒ積<EFBFBD><EFBFBD>メ漢゙ロ蟲フユ<EFBFBD>゙ヒ攴彩<EFBFBD>ル檮ォハヘマァツヒマャネホ€ャル梹ャネ栫アル档ギハ桓斎堪ネ積<EFBFBD>蒭マァツヒマスフミマクトニマアテロ螻ヒ椦カネヘ<EFBFBD>マヒ渥ぴ<EFBFBD>トハ蒔トム<EFBFBD>桜ネイチ梃サ゚ハ執テメ<EFBFBD>マロマケチ゚<EFBFBD>ルムマャネン換ロロマソ歳蒔ホヨチヤァ<EFBFBD><EFBFBD>ルヨ堪栽€ォ゚ン<EFBFBD>ツリマキテリ€ャタ゚峭ツミマソマム坎剤垰゙梟ュ彩<EFBFBD>歳擲マメ患載蒔フ檮ゾロマアヒ椦カネエィ煽棔ャツヤ歓ル積<EFBFBD><EFBFBD>堪ネ梟ュ罪<EFBFBD>ネ゚悸彩€<EFBFBD>リヘ<EFBFBD>楨ク<EFBFBD>トミ崕゚リ漆ネ梹ィフラαマメ<EFBFBD>フハ袂込マ<EFBFBD>込マカルハ滉愕リフ現レ゚攴τ攣ま垰ララΥフ大ヤ苙亞リメ<EFBFBD>フホ洳ネン<EFBFBD>ルロマキル棘サ゚ヌマウリン<EFBFBD>トリマァツヒマスツヒ<EFBFBD>妻堪トリ<EFBFBD>ルヨ<EFBFBD>ンフ€シチロ<EFBFBD>レ゚慟テム<EFBFBD>゚ロ浤゚ハ桓剤敢ツフ<EFBFBD>マヌマイツム┨テルマェナフ€ォハヨマェナロマコフハ湿フヘ嬉刷敢ツフ<EFBFBD>゚ロ浤゚ハ<EFBFBD>ハエ<EFBFBD>マヒ<EFBFBD>ンメ漢゙ロマスナロ厳彩<EFBFBD>鮭ョ渚ヘ<EFBFBD>ホロマキル梛ギン坏゙ロ<EFBFBD>フメ愕罪マイツハマアヒエ洳ツワ<EFBFBD>タ゚峭ホ棡キルヒ蒔トム<EFBFBD>Χ袂モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ態ァ孖ィネフ<EFBFBD><EFBFBD><EFBFBD>槐ロハ€<EFBFBD><EFBFBD><EFBFBD>エ蜈鵠ナロ椪イツヘ<EFBFBD>ハ棡カフフ桓采唆ネン岶細<EFBFBD>゙ハ蒔トン軸チヌマイトミ┰ノ檮キテ゚攅ネヘマウツヘ<EFBFBD>ツリマェナロ<EFBFBD>込マ<EFBFBD>込峭タロ<EFBFBD>チロ室゙椦ア在攸゙ヨ姦載址トミ<EFBFBD>ルヨ<EFBFBD>ノメ€ョネミヌ<EFBFBD>槃摸フ<EFBFBD>ルムマクトニチヤァ袞<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ホム興細<EFBFBD>テム<EFBFBD>寢マシトハマスチロ鴫<EFBFBD>マ看ラ<EFBFBD>トヘマケネハ峭テルマュチム亟ヤ梔キユロ欽込マ<EFBFBD>込マシリハマサユホ歓ル梟ーホムぐフハ<EFBFBD>チロマスナ゚∋ネヘマアテ樂鼾ワ<EFBFBD>αルリ€ャタヘマイトユ<EFBFBD><EFBFBD>涕フ仙ヤ<EFBFBD><EFBFBD>槃看ロマョ゚ロ弦゙ラ€ー采<EFBFBD>ルヨ<EFBFBD>ヘヘ<EFBFBD>ナメネ<EFBFBD>フミ虞ツフマセフヘ<EFBFBD>ナメネ<EFBFBD>ヒヒ⊃ルラ€ー載€<EFBFBD>テム<EFBFBD>゙ロ患ァ槃<EFBFBD>込マ<EFBFBD>ルムマシネ椦カネ檮ザハチヤァ袞<EFBFBD><EFBFBD><EFBFBD>簟マ墜ミ圜◇峺ネフ<EFBFBD>゙ヨ€ォチレマシネ梹<EFBFBD>レ゚<EFBFBD>ルムマョ゚ロ匳テハマコネリ<EFBFBD>トミ<EFBFBD>ルヨ<EFBFBD>゙ヌぞツメ<EFBFBD>込マ<EFBFBD>込。<EFBFBD><EFBFBD><EFBFBD>發滸梟ー彩<EFBFBD><EFBFBD>テヒ列チラすルヘチカ到<EFBFBD>フレ堪菜<EFBFBD>ネ積<EFBFBD>菻マケチラ鎖細嶽込マ<EFBFBD>込マギ梛サヒラ⊇ノ梟ー高浤゙ラ暦<EFBFBD><EFBFBD>ωム<EFBFBD>レヨ<EFBFBD>ナ桙ォ゙ハマーツハマウフユ<EFBFBD>ルヨ<EFBFBD>ツハ<EFBFBD>゚エマ<EFBFBD>込マ<EFBFBD>栽無マムΟ<EFBFBD><EFBFBD>リニタイトモ<EFBFBD>゙睡熏゚卅トメ湿チロチヤ込マ<EFBFBD>込マ<EFBFBD><EFBFBD>イトワ佼怺゚Ιエエ<EFBFBD>鵠イ<EFBFBD><EFBFBD><EFBFBD>タ宕サネロマセパさフ厮クリミ謙トム<EFBFBD>ハラ匳゙椈ャツミ<EFBFBD>゚ロ忰チハ<EFBFBD><EFBFBD><EFBFBD>チロ鹿ル梔ア゚エマ<EFBFBD>込マ<EFBFBD>酷゚<EFBFBD>涼ヤァ袞<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>チラ叉€ラ棺ネ桴ュポ<EFBFBD>萱沖テン峭ツミマケトネ姦宰擲テルマャネヘ坿ルヘマクツフ<EFBFBD>込マ<EFBFBD><EFBFBD>テ宕ールロ握フメマュネン€ーノ棔ソ゚゚そルロ擯Χ蜈込ナロ楙サロロ攸チ槁ウツヘ帋<EFBFBD>験チメ蒔トム<EFBFBD>゙ホ歓トリ<EFBFBD>フハ<EFBFBD>テヘマソ゚ロマシ゚ム┰テ積<EFBFBD><EFBFBD><EFBFBD>ホム興宰<EFBFBD>ホヨ<EFBFBD>込マ<EFBFBD><EFBFBD>在址゚ロ↑チヌマェナロ攴細<EFBFBD>トミマウツヘ<EFBFBD>ポ惱゙梟ーナロ攅ルロ<EFBFBD>ヒフ€ウ彩<EFBFBD>采攅ハラ<EFBFBD>フメ<EFBFBD>込マ<EFBFBD>込辞ルヨ€ャ獄<EFBFBD>在鹿ネ椦カネフ<EFBFBD>トヘマソ柵ャ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>゙ホ歓トリ<EFBFBD>フハ<EFBFBD>テ梟ー彩<EFBFBD>€スフメ間込マ<EFBFBD>込マクトメ机采<EFBFBD>トヘマコネリ<EFBFBD>ネレマォ゙ラ∋彩<EFBFBD>載敢フヒΜ<EFBFBD>細愕怺ル<EFBFBD><EFBFBD><EFBFBD>トミ鹸リレ桓ю袂込マ<EFBFBD>込マ療梹ーヤ梃ゾロマゥネ梹ャネ桙ギヘ<EFBFBD>ハ梟ーヒム攀フハ<EFBFBD>テ椦ア在€ャ゚ロ謙彩<EFBFBD>栽渊ホラ温ポ峭ツミチヤ込マ<EFBFBD>込マ陵椁アリ梔キテレマェナロマュンロ弦ヒラ諺ルラ€ー菜€ャ塞€ォ゚档ソテル堊ハロマシネ梔ソリメ岌歳<EFBFBD>フヘ間込マ<EFBFBD>込マュネミ<EFBFBD>フ椌サンム擡宰<EFBFBD>ナ梟ー゙ハ抬ホハ<EFBFBD>テ梳ー宰<EFBFBD>ル椦ア菜<EFBFBD><EFBFBD><EFBFBD>ヒマコツミネェ斎耳ネ椦アァ槃<EFBFBD>込マ<EFBFBD>ヒラ<EFBFBD>ルヨ<EFBFBD>゙ホ歓トリ<EFBFBD>フハ<EFBFBD>テ椁アリフ惱チリチヤァ槃<EFBFBD>込マ<EFBFBD><EFBFBD><EFBFBD>レ゚<EFBFBD>トハマクトミ軸チヌマュナム坿ノ档アツユマイトユ<EFBFBD><EFBFBD><EFBFBD>ルヨ<EFBFBD>ハロ⊇゚ラ<EFBFBD>゙ホ歓トリ<EFBFBD>フハ<EFBFBD>テエマ<EFBFBD>込マ<EFBFBD><EFBFBD>テム<EFBFBD>ホム擣ネン庠在鴫剤<EFBFBD>゙ロ寛細<EFBFBD>ルヨ<EFBFBD>゙ネー崎梔キチロチ<EFBFBD>搾垤ルロマソ菜勧在<EFBFBD>テル姦ァ槃<EFBFBD>込マ<EFBFBD>ツミマェツホマアヒ椦カネ梭サテロ攅ホ棡ョネン<EFBFBD>トン蒔トム<EFBFBD>ポ<EFBFBD>マロマウフレ<EFBFBD>レラ峺ツヒ<EFBFBD>ノヒ浚トン蒔トム<EFBFBD>込マ<EFBFBD>込マアヒ椦カネ椈カツメ<EFBFBD><EFBFBD>ー昶<EFBFBD>漱鋧コネヘ軒トホ峭ツミチヤァ袞<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ムそ采<EFBFBD>ルヨ<EFBFBD>ヒヒ⊃ルラ€ー゙椈カトン<EFBFBD>フメ愕斎鴫ノメ桓桜ソィ屓汐ネ梃ォ゚フ寛ルメ<EFBFBD>マフ€オネミチヤ込マ<EFBFBD>込マ<EFBFBD>ネル<EFBFBD>フミ<EFBFBD>蒡呟犀€アニヒ洒采舷フヘ<EFBFBD>テ゚Υヤ梏ソンホ寛宰<EFBFBD>テ栫アル栫サネレ桓<EFBFBD>マ看ラ慟込マ<EFBFBD>込マカフホ渊テヘマキテ梭サル゚脅゚ラ∈ツ免<EFBFBD>フミ<EFBFBD>ハロ峅フモ換テリ€<EFBFBD><EFBFBD>蒡呟斎鴫ノメ<EFBFBD>ハ梳クァ槃<EFBFBD>込マ<EFBFBD>ルヨ姦ネ梔ォテン峭ツミ<EFBFBD>トヘマ第椦カツヒ宛罪⊆彩<EFBFBD>゚ロマソ゚ロマョフハ幻ネヘマソロ゚<EFBFBD>フワ<EFBFBD>€<EFBFBD>ヒラ琳込マ<EFBFBD>込マェナロマ<EFBFBD>ネル<EFBFBD>ホム興罪<EFBFBD>レロΥΧ蝣モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蔵モタ蜍チフ<EFBFBD>ナ椨ャネホ渊゚エ峡ネホ渊゚<EFBFBD>攴ノヨ蒔<EFBFBD>€ウァ

Binary file not shown.

View File

@ -0,0 +1,5 @@
#!/usr/bin/env python
#-*- coding:utf-8 -*-
__all__ = ["args", "colors", "libcolors", "routine"]
__version__ = "0.96"

View File

@ -0,0 +1,28 @@
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from docopt import docopt
from routine import parse_char
class ArgError(Exception):
pass
def parse_parameters(doc, version):
p = docopt(doc, version=version)
p = {k.lstrip("-"): v for k, v in p.items()}
try:
return {
"input_is_hex": bool(p["hex"]),
"max_key_length": int(p["max-keylen"]),
"known_key_length": int(p["key-length"]) if p["key-length"] else None,
"most_frequent_char": parse_char(p["char"]) if p["char"] else None,
"brute_chars": bool(p["brute-chars"]),
"brute_printable": bool(p["brute-printable"]),
"frequency_spread": 0, # to be removed
"filename": p["FILE"] if p["FILE"] else "-", # stdin by default
}
except ValueError as err:
raise ArgError(str(err))

View File

@ -0,0 +1,19 @@
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from libcolors import color
C_RESET = color()
C_FATAL = color("red")
C_WARN = color("yellow")
C_KEYLEN = color("green")
C_PROB = color("white", attrs="")
C_BEST_KEYLEN = color("green", attrs="bold")
C_BEST_PROB = color("white", attrs="bold")
C_DIV = color(attrs="bold")
C_KEY = color("red", attrs="bold")
C_BOLD = color(attrs="bold")
C_COUNT = color("yellow", attrs="bold")

View File

@ -0,0 +1,80 @@
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
BASH_ATTRIBUTES = {"regular": "0",
"bold": "1", "underline": "4", "strike": "9",
"light": "1", "dark": "2",
"invert": "7"} # invert bg and fg
BASH_COLORS = {"black": "30", "red": "31", "green": "32", "yellow": "33",
"blue": "34", "purple": "35", "cyan": "36", "white": "37"}
BASH_BGCOLORS = {"black": "40", "red": "41", "green": "42", "yellow": "43",
"blue": "44", "purple": "45", "cyan": "46", "white": "47"}
def _main():
header = color("white", "black", "dark")
print
print header + " " + "Colors and backgrounds: " + color()
for c in _keys_sorted_by_values(BASH_COLORS):
c1 = color(c)
c2 = color("white" if c != "white" else "black", bgcolor=c)
print (c.ljust(10) +
c1 + "colored text" + color() + " " +
c2 + "background" + color())
print
print header + " " + "Attributes: " + color()
for c in _keys_sorted_by_values(BASH_ATTRIBUTES):
c1 = color("red", attrs=c)
c2 = color("white", attrs=c)
print (c.ljust(13) +
c1 + "red text" + color() + " " +
c2 + "white text" + color())
print
return
def color(color=None, bgcolor=None, attrs=None):
if not is_bash():
return ""
ret = "\x1b[0"
if attrs:
for attr in attrs.lower().split():
attr = attr.strip(",+|")
if attr not in BASH_ATTRIBUTES:
raise ValueError("Unknown color attribute: " + attr)
ret += ";" + BASH_ATTRIBUTES[attr]
if color:
if color in BASH_COLORS:
ret += ";" + BASH_COLORS[color]
else:
raise ValueError("Unknown color: " + color)
if bgcolor:
if bgcolor in BASH_BGCOLORS:
ret += ";" + BASH_BGCOLORS[bgcolor]
else:
raise ValueError("Unknown background color: " + bgcolor)
return ret + "m"
def is_bash():
return os.environ.get("SHELL", "unknown").endswith("bash")
def _keys_sorted_by_values(adict):
"""Return list of the keys of @adict sorted by values."""
return sorted(adict, key=adict.get)
if __name__ == "__main__":
_main()

View File

@ -0,0 +1,98 @@
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import sys
import string
class MkdirError(Exception):
pass
def load_file(filename):
if filename == "-":
return sys.stdin.read()
fd = open(filename, "rb")
contents = fd.read()
fd.close()
return contents
def save_file(filename, data):
fd = open(filename, "wb")
fd.write(data)
fd.close()
return
def mkdir(dirname):
if os.path.exists(dirname):
return
try:
os.mkdir(dirname)
except BaseException as err:
raise MkdirError(str(err))
return
def rmdir(dirname):
if dirname[-1] == os.sep:
dirname = dirname[:-1]
if os.path.islink(dirname):
return # do not clear link - we can get out of dir
files = os.listdir(dirname)
for f in files:
if f == '.' or f == '..':
continue
path = dirname + os.sep + f
if os.path.isdir(path):
rmdir(path)
else:
os.unlink(path)
os.rmdir(dirname)
return
def decode_from_hex(text):
only_hex_digits = "".join([c for c in text if c in string.hexdigits])
return only_hex_digits.decode("hex")
def parse_char(ch):
"""
'A' or '\x41' or '41'
"""
if len(ch) == 1:
return ord(ch)
if ch[0:2] == "\\x":
ch = ch[2:]
if not ch:
raise ValueError("Empty char")
return ord(chr(int(ch, 16)))
def dexor(text, key):
ret = list(text)
mod = len(key)
for index, char in enumerate(ret):
ret[index] = chr(ord(char) ^ ord(key[index % mod]))
return "".join(ret)
def die(exitMessage, exitCode=1):
print exitMessage
sys.exit(exitCode)
def is_linux():
return sys.platform.startswith("linux")
def alphanum(s):
lst = list(s)
for index, char in enumerate(lst):
if char in (string.letters + string.digits):
continue
lst[index] = char.encode("hex")
return "".join(lst)

View File

@ -0,0 +1,381 @@
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
xortool
A tool to do some xor analysis:
- guess the key length (based on count of equal chars)
- guess the key (base on knowledge of most frequent char)
Usage:
xortool [-x] [-m MAX-LEN] [FILE]
xortool [-x] [-l LEN] [-c CHAR | -b | -o] [FILE]
xortool [-x] [-m MAX-LEN| -l LEN] [-c CHAR | -b | -o] [FILE]
xortool [-h | --help]
xortool --version
Options:
-x --hex input is hex-encoded str
-l LEN, --key-length=LEN length of the key
-m MAX-LEN, --max-keylen=MAX-LEN maximum key length to probe [default: 65]
-c CHAR, --char=CHAR most frequent char (one char or hex code)
-b --brute-chars brute force all possible most frequent chars
-o --brute-printable same as -b but will only check printable chars
-h --help show this help
Examples:
xortool file.bin
xortool -l 11 -c 20 file.bin
xortool -x -c ' ' file.hex
"""
from operator import itemgetter
import os
import string
import xortool
from xortool.colors import *
from xortool.routine import *
from xortool.args import parse_parameters, ArgError
DIRNAME = 'xortool_out' # here plaintexts will be placed
PARAMETERS = dict()
class AnalysisError(Exception):
pass
def main():
global PARAMETERS
try:
PARAMETERS = parse_parameters(__doc__, xortool.__version__)
ciphertext = get_ciphertext()
update_key_length(ciphertext)
if PARAMETERS["brute_chars"]:
try_chars = range(256)
elif PARAMETERS["brute_printable"]:
try_chars = map(ord, string.printable)
elif PARAMETERS["most_frequent_char"] != None:
try_chars = [PARAMETERS["most_frequent_char"]]
else:
die(C_WARN +
"Most possible char is needed to guess the key!" +
C_RESET)
(probable_keys,
key_char_used) = guess_probable_keys_for_chars(ciphertext, try_chars)
print_keys(probable_keys)
produce_plaintexts(ciphertext, probable_keys, key_char_used)
except IOError as err:
print C_FATAL + "[ERROR] Can't load file:\n\t", err, C_RESET
except ArgError as err:
print C_FATAL + "[ERROR] Bad argument:\n\t", err, C_RESET
except MkdirError as err:
print C_FATAL + "[ERROR] Can't create directory:\n\t", err, C_RESET
except AnalysisError as err:
print C_FATAL + "[ERROR] Analysis error:\n\t", err, C_RESET
else:
return
cleanup()
# -----------------------------------------------------------------------------
# LOADING CIPHERTEXT
# -----------------------------------------------------------------------------
def get_ciphertext():
"""
Load ciphertext from a file or stdin and hex-decode if needed
"""
ciphertext = load_file(PARAMETERS["filename"])
if PARAMETERS["input_is_hex"]:
ciphertext = decode_from_hex(ciphertext)
return ciphertext
# -----------------------------------------------------------------------------
# KEYLENGTH GUESSING SECTION
# -----------------------------------------------------------------------------
def update_key_length(text):
"""
Guess length of the key if it's not set. (Updates PARAMETERS)
"""
global PARAMETERS
if PARAMETERS["known_key_length"]:
return
PARAMETERS["known_key_length"] = guess_key_length(text)
return
def guess_key_length(text):
"""
Try key lengths from 1 to max_key_length and print local maximums.
Set key_length to the most possible if it's not set by user.
"""
fitnesses = calculate_fitnesses(text)
if not fitnesses:
raise AnalysisError("No candidates for key length found! Too small file?")
print_fitnesses(fitnesses)
guess_and_print_divisors(fitnesses)
return get_max_fitnessed_key_length(fitnesses)
def calculate_fitnesses(text):
"""
Calc. fitnesses for each keylen
"""
prev = 0
pprev = 0
fitnesses = []
for key_length in range(1, PARAMETERS["max_key_length"] + 1):
fitness = count_equals(text, key_length)
# smaller key-length with nearly the same fitness is preferable
fitness = (float(fitness) /
(PARAMETERS["max_key_length"] + key_length ** 1.5))
if pprev < prev and prev > fitness: # local maximum
fitnesses += [(key_length - 1, prev)]
pprev = prev
prev = fitness
if pprev < prev:
fitnesses += [(key_length - 1, prev)]
return fitnesses
def print_fitnesses(fitnesses):
print "The most probable key lengths:"
# top sorted by fitness, but print sorted by length
fitnesses.sort(key=itemgetter(1), reverse=True)
top10 = fitnesses[:10]
best_fitness = top10[0][1]
top10.sort(key=itemgetter(0))
fitness_sum = calculate_fitness_sum(top10)
for key_length, fitness in top10:
s1 = str(key_length).rjust(4, " ")
s2 = str(round(100 * fitness * 1.0 / fitness_sum, 1)) + "%"
if fitness == best_fitness:
print (C_BEST_KEYLEN + s1 + C_RESET + ": "
+ C_BEST_PROB + s2 + C_RESET)
else:
print (C_KEYLEN + s1 + C_RESET + ": "
+ C_PROB + s2 + C_RESET)
return
def calculate_fitness_sum(fitnesses):
return sum([f[1] for f in fitnesses])
def count_equals(text, key_length):
"""
count equal chars count for each offset and sum them
"""
equals_count = 0
if key_length >= len(text):
return 0
for offset in range(key_length):
chars_count = chars_count_at_offset(text, key_length, offset)
equals_count += max(chars_count.values()) - 1 # why -1? don't know
return equals_count
def guess_and_print_divisors(fitnesses):
"""
Prints common divisors and returns the most common divisor
"""
divisors_counts = [0] * (PARAMETERS["max_key_length"] + 1)
for key_length, fitness in fitnesses:
for number in range(3, key_length + 1):
if key_length % number == 0:
divisors_counts[number] += 1
max_divisors = max(divisors_counts)
limit = 3
ret = 2
for number, divisors_count in enumerate(divisors_counts):
if divisors_count == max_divisors:
print "Key-length can be " + C_DIV + str(number) + "*n" + C_RESET
ret = number
limit -= 1
if limit == 0:
return ret
return ret
def get_max_fitnessed_key_length(fitnesses):
max_fitness = 0
max_fitnessed_key_length = 0
for key_length, fitness in fitnesses:
if fitness > max_fitness:
max_fitness = fitness
max_fitnessed_key_length = key_length
return max_fitnessed_key_length
def chars_count_at_offset(text, key_length, offset):
chars_count = dict()
for pos in range(offset, len(text), key_length):
c = text[pos]
if c in chars_count:
chars_count[c] += 1
else:
chars_count[c] = 1
return chars_count
# -----------------------------------------------------------------------------
# KEYS GUESSING SECTION
# -----------------------------------------------------------------------------
def guess_probable_keys_for_chars(text, try_chars):
"""
Guess keys for list of characters.
"""
probable_keys = []
key_char_used = {}
for c in try_chars:
keys = guess_keys(text, c)
for key in keys:
key_char_used[key] = c
if key not in probable_keys:
probable_keys.append(key)
return probable_keys, key_char_used
def guess_keys(text, most_char):
"""
Generate all possible keys for key length
and the most possible char
"""
key_length = PARAMETERS["known_key_length"]
key_possible_bytes = [[] for _ in range(key_length)]
for offset in range(key_length): # each byte of key<
chars_count = chars_count_at_offset(text, key_length, offset)
max_count = max(chars_count.values())
for char in chars_count:
if chars_count[char] >= max_count:
key_possible_bytes[offset].append(chr(ord(char) ^ most_char))
return all_keys(key_possible_bytes)
def all_keys(key_possible_bytes, key_part="", offset=0):
"""
Produce all combinations of possible key chars
"""
keys = []
if offset >= len(key_possible_bytes):
return [key_part]
for c in key_possible_bytes[offset]:
keys += all_keys(key_possible_bytes, key_part + c, offset + 1)
return keys
def print_keys(keys):
if not keys:
print "No keys guessed!"
return
s1 = C_COUNT + str(len(keys)) + C_RESET
s2 = C_COUNT + str(len(keys[0])) + C_RESET
print "{} possible key(s) of length {}:".format(s1, s2)
for key in keys[:5]:
print C_KEY + repr(key)[1:-1] + C_RESET
if len(keys) > 10:
print "..."
# -----------------------------------------------------------------------------
# RETURNS PERCENTAGE OF PRINTABLE CHARS
# -----------------------------------------------------------------------------
def percentage_printable(text):
x = 0.0
for c in text:
if c in string.printable:
x += 1
return x / len(text)
# -----------------------------------------------------------------------------
# PRODUCE OUTPUT
# -----------------------------------------------------------------------------
def produce_plaintexts(ciphertext, keys, key_char_used):
"""
Produce plaintext variant for each possible key,
creates csv files with keys, percentage of printable
characters and used most frequent character
"""
cleanup()
mkdir(DIRNAME)
# this is split up in two files since the
# key can contain all kinds of characters
fn_key_mapping = "filename-key.csv"
fn_perc_mapping = "filename-char_used-perc_printable.csv"
key_mapping = open(os.path.join(DIRNAME, fn_key_mapping), "w")
perc_mapping = open(os.path.join(DIRNAME, fn_perc_mapping), "w")
key_mapping.write("file_name;key_repr\n")
perc_mapping.write("file_name;char_used;perc_printable\n")
threshold_printable = 95
count_printable = 0
for index, key in enumerate(keys):
key_index = str(index).rjust(len(str(len(keys) - 1)), "0")
key_repr = repr(key)[1:-1].replace("/", "\\x2f")
if not is_linux():
key_repr = alphanum(key)
file_name = os.path.join(DIRNAME, key_index + ".out")
dexored = dexor(ciphertext, key)
perc = round(100 * percentage_printable(dexored))
if perc > threshold_printable:
count_printable += 1
key_mapping.write("{};{}\n".format(file_name, key_repr))
perc_mapping.write("{};{};{}\n".format(file_name,
repr(key_char_used[key]),
perc))
f = open(file_name, "wb")
f.write(dexored)
f.close()
key_mapping.close()
perc_mapping.close()
s1 = C_COUNT + str(count_printable) + C_RESET
s2 = C_COUNT + str(round(threshold_printable)) + C_RESET
print "Found {} plaintexts with {}%+ printable characters".format(s1, s2)
print "See files {}, {}".format(fn_key_mapping, fn_perc_mapping)
return
def cleanup():
if os.path.exists(DIRNAME):
rmdir(DIRNAME)
return
if __name__ == "__main__":
main()

View File

@ -0,0 +1,116 @@
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
xor strings
options:
-s - string with \\xAF escapes
-r - raw string
-h - hex-encoded string (non-letterdigit chars are stripped)
-f - read data from file (- for stdin)
-n - no newline at the end
--no-cycle / --nc - pad smaller strings with null bytes
example: xor -s lol -h 414243 -f /etc/passwd
author: hellman ( hellman1908@gmail.com )
"""
import sys
import string
import getopt
DATA_OPTS = "s:r:h:f:"
HEXES = set("0123456789abcdefABCDEF")
def main():
nocycle = False
nonewline = False
try:
opts, args = getopt.getopt(sys.argv[1:], "n" + DATA_OPTS, ["no-cycle", "nc"])
datas = []
for c, val in opts:
if c in ("--no-cycle", "--nc"):
nocycle = True
elif c == "-n":
nonewline = True
else:
v = arg_data(c, val)
if v is None:
raise getopt.GetoptError("unknown option %s" % c)
datas.append(v)
if not datas:
raise getopt.GetoptError("no data given")
except getopt.GetoptError as e:
print >>sys.stderr, "error:", e
print >>sys.stderr, __doc__
quit()
sys.stdout.write(xor(datas, nocycle=nocycle))
if not nonewline:
sys.stdout.write("\n")
def xor(args, nocycle=False):
maxlen = max(map(len, args))
res = [0] * maxlen
if nocycle:
for s in args:
for i in xrange(len(s)):
res[i] ^= ord(s[i])
else:
for s in args:
slen = len(s)
for i in xrange(maxlen):
res[i] ^= ord(s[i % slen])
return "".join(map(chr, res))
def from_str(s):
res = ""
i = 0
while True:
if i + 4 > len(s):
break
if s[i+1] == "x" and s[i+2] in HEXES and s[i+3] in HEXES:
res += chr(int(s[i+2:i+4], 16))
i += 4
else:
res += s[i]
i += 1
res += s[i:]
return res
def from_hex(s):
res = ""
for c in s:
if c in HEXES:
res += c
elif c in string.ascii_letters:
raise ValueError("Bad splitters (alphanum)")
return res.decode("hex")
def from_file(s):
if s == "-":
return sys.stdin.read()
return open(s, "rb").read()
def arg_data(opt, s):
if opt == "-s":
return from_str(s)
elif opt == "-r":
return s
elif opt == "-h":
return from_hex(s)
elif opt == "-f":
return from_file(s)
return None
if __name__ == '__main__':
main()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 184 KiB