Browse Source

Init

master
Kris Kwiatkowski 5 years ago
commit
60779f40ca
100 changed files with 91264 additions and 0 deletions
  1. +43
    -0
      Makefile
  2. +42
    -0
      ext/libtomcrypt/.clang-format
  3. +134
    -0
      ext/libtomcrypt/.travis.yml
  4. +29
    -0
      ext/libtomcrypt/LICENSE
  5. +117
    -0
      ext/libtomcrypt/README.md
  6. +3
    -0
      ext/libtomcrypt/TODO
  7. +59
    -0
      ext/libtomcrypt/build.sh
  8. +1621
    -0
      ext/libtomcrypt/changes
  9. +15
    -0
      ext/libtomcrypt/check_source.sh
  10. +51
    -0
      ext/libtomcrypt/coverage.sh
  11. +24
    -0
      ext/libtomcrypt/coverage_more.sh
  12. +40
    -0
      ext/libtomcrypt/coverity.sh
  13. +52
    -0
      ext/libtomcrypt/demos/constants.c
  14. +206
    -0
      ext/libtomcrypt/demos/demo_dynamic.py
  15. +284
    -0
      ext/libtomcrypt/demos/hashsum.c
  16. +204
    -0
      ext/libtomcrypt/demos/ltcrypt.c
  17. +397
    -0
      ext/libtomcrypt/demos/openssl-enc.c
  18. +45
    -0
      ext/libtomcrypt/demos/sizes.c
  19. +22
    -0
      ext/libtomcrypt/demos/small.c
  20. +1456
    -0
      ext/libtomcrypt/demos/timing.c
  21. +797
    -0
      ext/libtomcrypt/demos/tv_gen.c
  22. +2430
    -0
      ext/libtomcrypt/doc/Doxyfile
  23. +7326
    -0
      ext/libtomcrypt/doc/crypt.tex
  24. BIN
     
  25. +60
    -0
      ext/libtomcrypt/doc/makefile
  26. +383
    -0
      ext/libtomcrypt/helper.pl
  27. +49
    -0
      ext/libtomcrypt/hooks/pre-commit
  28. +10
    -0
      ext/libtomcrypt/libtomcrypt.pc.in
  29. +11
    -0
      ext/libtomcrypt/libtomcrypt.sublime-project
  30. +2497
    -0
      ext/libtomcrypt/libtomcrypt.sublime-workspace
  31. +26
    -0
      ext/libtomcrypt/libtomcrypt_VS2008.sln
  32. +2526
    -0
      ext/libtomcrypt/libtomcrypt_VS2008.vcproj
  33. +138
    -0
      ext/libtomcrypt/makefile
  34. +285
    -0
      ext/libtomcrypt/makefile.mingw
  35. +270
    -0
      ext/libtomcrypt/makefile.msvc
  36. +74
    -0
      ext/libtomcrypt/makefile.shared
  37. +291
    -0
      ext/libtomcrypt/makefile.unix
  38. +465
    -0
      ext/libtomcrypt/makefile_include.mk
  39. +35
    -0
      ext/libtomcrypt/notes/base64_tv.txt
  40. +284
    -0
      ext/libtomcrypt/notes/ccm_tv.txt
  41. +2287
    -0
      ext/libtomcrypt/notes/cipher_tv.txt
  42. +569
    -0
      ext/libtomcrypt/notes/eax_tv.txt
  43. +1261
    -0
      ext/libtomcrypt/notes/ecc_tv.txt
  44. +249
    -0
      ext/libtomcrypt/notes/etc/NoekeonVects.java
  45. +177
    -0
      ext/libtomcrypt/notes/etc/saferp_optimizer.c
  46. +95
    -0
      ext/libtomcrypt/notes/etc/whirlgen.c
  47. +19
    -0
      ext/libtomcrypt/notes/etc/whirltest.c
  48. +284
    -0
      ext/libtomcrypt/notes/gcm_tv.txt
  49. +5147
    -0
      ext/libtomcrypt/notes/hash_tv.txt
  50. +29
    -0
      ext/libtomcrypt/notes/hashsum_tv.txt
  51. +5147
    -0
      ext/libtomcrypt/notes/hmac_tv.txt
  52. +126
    -0
      ext/libtomcrypt/notes/lrw_tv.txt
  53. +569
    -0
      ext/libtomcrypt/notes/ocb3_tv.txt
  54. +569
    -0
      ext/libtomcrypt/notes/ocb_tv.txt
  55. +569
    -0
      ext/libtomcrypt/notes/omac_tv.txt
  56. +569
    -0
      ext/libtomcrypt/notes/pmac_tv.txt
  57. +11
    -0
      ext/libtomcrypt/notes/rsa-testvectors/makefile
  58. +369
    -0
      ext/libtomcrypt/notes/rsa-testvectors/oaep-int.txt
  59. +1418
    -0
      ext/libtomcrypt/notes/rsa-testvectors/oaep-vect.c
  60. +2212
    -0
      ext/libtomcrypt/notes/rsa-testvectors/oaep-vect.txt
  61. +5463
    -0
      ext/libtomcrypt/notes/rsa-testvectors/pkcs1v15crypt-vectors.c
  62. +9709
    -0
      ext/libtomcrypt/notes/rsa-testvectors/pkcs1v15crypt-vectors.txt
  63. +4261
    -0
      ext/libtomcrypt/notes/rsa-testvectors/pkcs1v15sign-vectors.c
  64. +9049
    -0
      ext/libtomcrypt/notes/rsa-testvectors/pkcs1v15sign-vectors.txt
  65. +162
    -0
      ext/libtomcrypt/notes/rsa-testvectors/pss-int.txt
  66. +1418
    -0
      ext/libtomcrypt/notes/rsa-testvectors/pss-vect.c
  67. +2581
    -0
      ext/libtomcrypt/notes/rsa-testvectors/pss-vect.txt
  68. +22
    -0
      ext/libtomcrypt/notes/rsa-testvectors/readme.txt
  69. +253
    -0
      ext/libtomcrypt/notes/rsa-testvectors/rt.py
  70. +73
    -0
      ext/libtomcrypt/notes/tech0001.txt
  71. +52
    -0
      ext/libtomcrypt/notes/tech0002.txt
  72. +52
    -0
      ext/libtomcrypt/notes/tech0003.txt
  73. +91
    -0
      ext/libtomcrypt/notes/tech0004.txt
  74. +20
    -0
      ext/libtomcrypt/notes/tech0005.txt
  75. +91
    -0
      ext/libtomcrypt/notes/tech0006.txt
  76. +5
    -0
      ext/libtomcrypt/notes/tech0007.txt
  77. +20
    -0
      ext/libtomcrypt/printinfo.sh
  78. +49
    -0
      ext/libtomcrypt/run.sh
  79. +19
    -0
      ext/libtomcrypt/scan_build.sh
  80. +743
    -0
      ext/libtomcrypt/src/ciphers/aes/aes.c
  81. +1030
    -0
      ext/libtomcrypt/src/ciphers/aes/aes_tab.c
  82. +1558
    -0
      ext/libtomcrypt/src/ciphers/anubis.c
  83. +594
    -0
      ext/libtomcrypt/src/ciphers/blowfish.c
  84. +726
    -0
      ext/libtomcrypt/src/ciphers/camellia.c
  85. +720
    -0
      ext/libtomcrypt/src/ciphers/cast5.c
  86. +2083
    -0
      ext/libtomcrypt/src/ciphers/des.c
  87. +318
    -0
      ext/libtomcrypt/src/ciphers/kasumi.c
  88. +855
    -0
      ext/libtomcrypt/src/ciphers/khazad.c
  89. +376
    -0
      ext/libtomcrypt/src/ciphers/kseed.c
  90. +319
    -0
      ext/libtomcrypt/src/ciphers/multi2.c
  91. +328
    -0
      ext/libtomcrypt/src/ciphers/noekeon.c
  92. +417
    -0
      ext/libtomcrypt/src/ciphers/rc2.c
  93. +322
    -0
      ext/libtomcrypt/src/ciphers/rc5.c
  94. +331
    -0
      ext/libtomcrypt/src/ciphers/rc6.c
  95. +495
    -0
      ext/libtomcrypt/src/ciphers/safer/safer.c
  96. +64
    -0
      ext/libtomcrypt/src/ciphers/safer/safer_tab.c
  97. +568
    -0
      ext/libtomcrypt/src/ciphers/safer/saferp.c
  98. +343
    -0
      ext/libtomcrypt/src/ciphers/skipjack.c
  99. +711
    -0
      ext/libtomcrypt/src/ciphers/twofish/twofish.c
  100. +496
    -0
      ext/libtomcrypt/src/ciphers/twofish/twofish_tab.c

+ 43
- 0
Makefile View File

@@ -0,0 +1,43 @@
objify = $(patsubst %.c,obj/%.$2,$(patsubst %.s,obj/%.$2,$1))

CC=clang
INC = -Iext/libtomcrypt/src/headers
CFLAGS = -std=c99 -D_GNU_SOURCE
CFLAGS += -Wextra -Wall -Werror -Wno-missing-braces -Wno-missing-field-initializers $(INC)
LDFLAGS = -Lext/libtomcrypt -ltomcrypt
DIRS=bin obj out
OBJS = $(call objify,$(SRC),o)

# Enable for testing only
DEBUG=1

ifeq ($(DEBUG), 1)
CFLAGS += -g -O0 -fsanitize=undefined,leak,address
LDFLAGS += -fsanitize=undefined,leak,address
CC=clang
else
CFLAGS += -O2
endif

# source files
SRC = \
src/crypt.c \
src/i2c.c \
src/main.c

all: libtomcrypt bin/main

obj/%.o: %.c
case $@ in */*) f=$@; mkdir -p $${f%/*} ;; esac
$(CC) -o $@ -c $< $(CFLAGS)

bin/main: $(OBJS)
case $@ in */*) f=$@; mkdir -p $${f%/*} ;; esac
$(CC) -o bin/main $(OBJS) $(LDFLAGS)

clean:
rm -rf $(DIRS)
make -C ext/libtomcrypt clean

libtomcrypt:
make -C ext/libtomcrypt

+ 42
- 0
ext/libtomcrypt/.clang-format View File

@@ -0,0 +1,42 @@
---
AccessModifierOffset: -2
ConstructorInitializerIndentWidth: 4
AlignEscapedNewlinesLeft: false
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakTemplateDeclarations: false
AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: false
BreakConstructorInitializersBeforeComma: false
BinPackParameters: true
ColumnLimit: 120
ConstructorInitializerAllOnOneLineOrOnePerLine: true
DerivePointerBinding: true
ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: true
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCSpaceBeforeProtocolList: false
PenaltyBreakComment: 60
PenaltyBreakString: 1000
PenaltyBreakFirstLessLess: 120
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerBindsToType: false
SpacesBeforeTrailingComments: 1
Cpp11BracedListStyle: false
Standard: Cpp03
IndentWidth: 3
TabWidth: 8
UseTab: Never
BreakBeforeBraces: Linux
IndentFunctionDeclarationAfterType: false
SpacesInParentheses: false
SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false
SpaceAfterControlStatementKeyword: true
SpaceBeforeAssignmentOperators: true
...


+ 134
- 0
ext/libtomcrypt/.travis.yml View File

@@ -0,0 +1,134 @@
dist: trusty
sudo: required

language: c

addons:
apt:
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.8
packages:
- clang-3.8

install:
- sudo apt-get update -qq
- sudo apt-get install libtommath-dev

before_script:
- gem install coveralls-lcov
- curl http://ftp.de.debian.org/debian/pool/main/l/lcov/lcov_1.11.orig.tar.gz | tar xz
- export PATH=$PATH:`pwd`/lcov-1.11/bin
- curl -s https://packagecloud.io/install/repositories/libtom/packages/script.deb.sh | sudo bash
- sudo apt-get install libtfm-dev=0.13-5

matrix:
fast_finish: true
branches:
only:
- master
- develop
- /^release\/.*$/

compiler:
- gcc
- clang
script:
- bash "${BUILDSCRIPT}" "${BUILDNAME}" "${BUILDOPTIONS}" "makefile V=1" "-DUSE_LTM -DLTM_DESC" "-ltommath"
- bash "${BUILDSCRIPT}" "${BUILDNAME}" "${BUILDOPTIONS}" "makefile.shared V=1" "-DUSE_TFM -DTFM_DESC" "-ltfm"
env:
- |
BUILDSCRIPT="check_source.sh"
BUILDNAME="CHECK_SOURCES"
BUILDOPTIONS=" "
- |
BUILDSCRIPT="scan_build.sh"
BUILDNAME="SCAN_BUILD"
BUILDOPTIONS=" "
- |
BUILDSCRIPT="coverage.sh"
BUILDNAME="COVERAGE"
BUILDOPTIONS=" "
- |
BUILDSCRIPT="run.sh"
BUILDNAME="STOCK"
BUILDOPTIONS=" "
- |
BUILDSCRIPT="run.sh"
BUILDNAME="EASY"
BUILDOPTIONS="-DLTC_EASY"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="SMALL"
BUILDOPTIONS="-DLTC_SMALL_CODE"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="NOTABLES"
BUILDOPTIONS="-DLTC_NO_TABLES"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="SMALL+NOTABLES"
BUILDOPTIONS="-DLTC_SMALL_CODE -DLTC_NO_TABLES"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="CLEANSTACK"
BUILDOPTIONS="-DLTC_CLEAN_STACK"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="CLEANSTACK+SMALL"
BUILDOPTIONS="-DLTC_SMALL_CODE -DLTC_CLEAN_STACK"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="CLEANSTACK+NOTABLES"
BUILDOPTIONS="-DLTC_NO_TABLES -DLTC_CLEAN_STACK"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="CLEANSTACK+NOTABLES+SMALL"
BUILDOPTIONS="-DLTC_NO_TABLES -DLTC_CLEAN_STACK -DLTC_SMALL_CODE"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="NO_FAST"
BUILDOPTIONS="-DLTC_NO_FAST"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="NO_FAST+NOTABLES"
BUILDOPTIONS="-DLTC_NO_FAST -DLTC_NO_TABLES"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="NO_ASM"
BUILDOPTIONS="-DLTC_NO_ASM"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="NO_TIMING_RESISTANCE"
BUILDOPTIONS="-DLTC_NO_ECC_TIMING_RESISTANT -DLTC_NO_RSA_BLINDING"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="CLEANSTACK+NOTABLES+SMALL+NO_ASM+NO_TIMING_RESISTANCE"
BUILDOPTIONS="-DLTC_CLEAN_STACK -DLTC_NO_TABLES -DLTC_SMALL_CODE -DLTC_NO_ECC_TIMING_RESISTANT -DLTC_NO_RSA_BLINDING"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="PTHREAD"
BUILDOPTIONS="-DLTC_PTHREAD"
- |
BUILDSCRIPT="run.sh"
BUILDNAME="CLEANSTACK+NOTABLES+SMALL+NO_ASM+NO_TIMING_RESISTANCE+PTHREAD"
BUILDOPTIONS="-DLTC_CLEAN_STACK -DLTC_NO_TABLES -DLTC_SMALL_CODE -DLTC_NO_ECC_TIMING_RESISTANT -DLTC_NO_RSA_BLINDING -DLTC_PTHREAD"
- |
BUILDSCRIPT="testbuild.sh"
BUILDNAME="NOTEST"
BUILDOPTIONS="-DLTC_NO_TEST"
- |
BUILDSCRIPT="testbuild.sh"
BUILDNAME="NOFILE"
BUILDOPTIONS="-DLTC_NO_FILE"

after_failure:
- cat test_std.txt
- cat test_err.txt

after_script:
- cat gcc_1.txt
- cat gcc_2.txt

notifications:
irc: "chat.freenode.net#libtom-notifications"

+ 29
- 0
ext/libtomcrypt/LICENSE View File

@@ -0,0 +1,29 @@
LibTomCrypt is licensed under DUAL licensing terms.

Choose and use the license of your needs.

[LICENSE #1]

LibTomCrypt is public domain. As should all quality software be.

Tom St Denis

[/LICENSE #1]

[LICENSE #2]

DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004

Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.

DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

0. You just DO WHAT THE FUCK YOU WANT TO.

[/LICENSE #2]

+ 117
- 0
ext/libtomcrypt/README.md View File

@@ -0,0 +1,117 @@
# libtomcrypt

See `doc/crypt.pdf` for a detailed documentation

## Project Status

master: [![Build Status](https://api.travis-ci.org/libtom/libtomcrypt.png?branch=master)](https://travis-ci.org/libtom/libtomcrypt) [![Coverage Status](https://coveralls.io/repos/libtom/libtomcrypt/badge.png?branch=master)](https://coveralls.io/r/libtom/libtomcrypt)

develop: [![Build Status](https://api.travis-ci.org/libtom/libtomcrypt.png?branch=develop)](https://travis-ci.org/libtom/libtomcrypt) [![Coverage Status](https://coveralls.io/repos/libtom/libtomcrypt/badge.png?branch=develop)](https://coveralls.io/r/libtom/libtomcrypt)

[![Coverity Scan Build Status](https://scan.coverity.com/projects/487/badge.svg)](https://scan.coverity.com/projects/487)

## Submitting patches

Please branch off from develop if you want to submit a patch.

Patch integration will be faster if tests and documentation are included.

Please update the makefiles in a separate commit. To update them simply run the `updatemakes.sh` script.

## Branches

Please be aware, that all branches besides _master_ and _develop_ __can__ and __will be__ force-pushed, rebased and/or removed!

If you want to rely on such an _unstable_ branch, create your own fork of this repository to make sure nothing breaks for you.

## Configuration options

By default the library builds its entire feature set (besides `katja`) in a (depending on your needs more or less) optimal way.

There are numerous configuration options available if you want to trim down the functionality of the library.

Please have a look at `src/headers/tomcrypt_custom.h` for all available configuration options.

The following list is a small part of the available, but the most often required, configuration switches.

| Flag | Behavior |
| ---- | -------- |
| `LTC_NO_TEST` | Remove all algorithm self-tests from the library |
| `LTC_NO_FILE` | Remove all API functions requiring a pre-defined `FILE` data-type (mostly useful for embedded targets) |
| `MAX_RSA_SIZE` | Per default set to `4096`, if you need support for importing or generating bigger RSA keys, change this at compile-time. |
| `GMP_DESC` | enable [gmp](https://gmplib.org/) as MPI provider *\*1* |
| `LTM_DESC` | enable [libtommath](http://www.libtom.net/) as MPI provider *\*1* |
| `TFM_DESC` | enable [tomsfastmath](http://www.libtom.net/) as MPI provider *\*1* *\*2* |
| `USE_GMP` | use `gmp` as MPI provider when building the binaries *\*3* |
| `USE_LTM` | use `libtommath` as MPI provider when building the binaries *\*3* |
| `USE_TFM` | use `tomsfastmath` as MPI provider when building the binaries *\*3* |

*\*1* It is possible to build the library against all MPI providers in parallel and choose at startup-time which math library should be used.

*\*2* Please be aware that `tomsfastmath` has the limitation of a fixed max size of MPI's.

*\*3* Only one is supported at the time & this is only required when building the binaries, not when building the library itself.

## Building the library

There are several `makefile`s provided. Please choose the one that fits best for you.

| makefile | use-case |
| -------- | -------- |
| `makefile` | builds a static library (GNU Make required, broken on Mac OSX - use `makefile.unix` instead) |
| `makefile.shared` | builds a shared (and static) library (GNU Make required) |
| `makefile.unix` | for unusual UNIX platforms, or if you do not have GNU Make |
| `makefile.mingw` | for usage with the mingw compiler on MS Windows |
| `makefile.msvc` | for usage with the MSVC compiler on MS Windows |
| `libtomcrypt_VS2008.sln` | A VisualStudio 2008 project for MS Windows |

### Make targets

The `makefile`s provide several targets to build (VS project excluded).
The following list does not claim to be complete resp. to be available across all `makefile` variants.

| target | application |
| ------ | ----------- |
| *empty target*/none given | c.f. `library`
| `library` | builds only the library |
| `hashsum` | builds the `hashsum` binary, similar to [`shasum`](https://linux.die.net/man/1/shasum), but with support for all hash-algorithms included in the library *\*4* |
| `ltcrypt` | builds the `ltcrypt` binary, implementing something similar to [`crypt`](https://linux.die.net/man/3/crypt) *\*4* |
| `sizes` | builds the `sizes` binary, printing all internal data sizes on invocation *\*4* |
| `constants` | builds the `constants` binary, printing all internal constants on invocation *\*4* |
| `openssl-enc` | builds the `openssl-enc` binary, which is more or less compatible to [`openssl enc`](https://linux.die.net/man/1/enc) *\*4* *\*5* |
| `test` | builds the `test` binary, which runs all algorithm self-tests + some extended tests *\*4* *\*6* |
| `timing` | builds the `timing` binary, which can be used to measure timings for algorithms and modes *\*4* *\*6* |
| `bins` | builds `hashsum` *\*4* |
| `all_test` | builds `test`, `hashsum`, `ltcrypt`, `small`, `tv_gen`, `sizes` & `constants` *\*4* |

*\*4* also builds `library`

*\*5* broken build in some configurations, therefore not built by default

*\*6* requires define of one of `USE_GMP`, `USE_LTM` or `USE_TFM` (+ the appropriate MPI provider)

### Examples

You want to build the library as static library

make

You want to build the library as shared library

make -f makefile.shared

You have `libtommath` installed on your system and want to build a static library and the `test` binary to run the self-tests.

make CFLAGS="-DUSE_LTM -DLTM_DESC" EXTRALIBS="-ltommath" test

You have `tomsfastmath` installed on your system and want to build a shared library and all binaries

make -f makefile.shared CFLAGS="-DUSE_TFM -DTFM_DESC" EXTRALIBS="-ltfm" all demos

You have `gmp`, `libtommath` and `tomsfastmath` installed on your system and want to build a static library and the `timing` binary to measure timings against `gmp`.

make CFLAGS="-DUSE_GMP -DGMP_DESC -DLTM_DESC -DTFM_DESC" EXTRALIBS="-lgmp" timing

If you have `libtommath` in a non-standard location:

make CFLAGS="-DUSE_LTM -DLTM_DESC -I/opt/devel/ltm" EXTRALIBS="/opt/devel/ltm/libtommath.a" all

+ 3
- 0
ext/libtomcrypt/TODO View File

@@ -0,0 +1,3 @@
for 1.18
- document new ECC functions
- add test for new functions

+ 59
- 0
ext/libtomcrypt/build.sh View File

@@ -0,0 +1,59 @@
#!/bin/bash
echo "$1 ($2, $3)..."

make clean 1>/dev/null 2>/dev/null

echo -n "building..."

if [ -f /proc/cpuinfo ]
then
MAKE_JOBS=$(( ($(cat /proc/cpuinfo | grep -E '^processor[[:space:]]*:' | tail -n -1 | cut -d':' -f2) + 1) * 2 + 1 ))
else
MAKE_JOBS=8
fi

CFLAGS="$2 $CFLAGS $4" EXTRALIBS="$5" make -j$MAKE_JOBS -f $3 all_test 1>gcc_1.txt 2>gcc_2.txt
mret=$?
cnt=$(wc -l < gcc_2.txt)
# ignore 1 line since ar prints to stderr instead of stdout and ar is called for
# $(LIBNAME)
if [[ $mret -ne 0 ]] || [[ $cnt -gt 1 ]]; then
echo "build $1 failed! printing gcc_2.txt now for convenience"
cat gcc_2.txt
exit 1
fi

echo -n "testing..."

if [ -a test ] && [ -f test ] && [ -x test ]; then
((./test >test_std.txt 2>test_err.txt && ./tv_gen > tv.txt) && echo "$1 test passed." && echo "y" > testok.txt) || (echo "$1 test failed, look at test_err.txt" && exit 1)
if find *_tv.txt -type f 1>/dev/null 2>/dev/null ; then
for f in *_tv.txt; do
# check for lines starting with '<' ($f might be a subset of notes/$f)
difftroubles=$(diff -i -w -B $f notes/$f | grep '^<')
if [ -n "$difftroubles" ]; then
echo "FAILURE: $f"
diff -i -w -B $f notes/$f
echo "tv_gen $f failed" && rm -f testok.txt && exit 1
else
true
fi
done
fi
fi


if [ -a testok.txt ] && [ -f testok.txt ]; then
if [ "$LTC_COVERAGE" != "" ]; then
./coverage_more.sh > test_coverage_more.txt || exit 1
lcov_opts="--capture --no-external --directory src -q"
lcov_out=$(echo coverage_$1_$2_$3 | tr ' -=+' '_')".info"
lcov $lcov_opts --output-file $lcov_out
fi
exit 0
fi
exit 1

# ref: $Format:%D$
# git commit: $Format:%H$
# commit time: $Format:%ai$

+ 1621
- 0
ext/libtomcrypt/changes
File diff suppressed because it is too large
View File


+ 15
- 0
ext/libtomcrypt/check_source.sh View File

@@ -0,0 +1,15 @@
#!/bin/bash

# output version
bash printinfo.sh

make clean > /dev/null

echo "checking..."
./helper.pl --check-source --check-makefiles --check-defines|| exit 1

exit 0

# ref: $Format:%D$
# git commit: $Format:%H$
# commit time: $Format:%ai$

+ 51
- 0
ext/libtomcrypt/coverage.sh View File

@@ -0,0 +1,51 @@
#!/bin/bash

set -e

if [ "$TRAVIS_CI" == "private" ]; then
exit 0
fi

if [ "$#" != "5" ]; then
echo "Usage is: ${0} \"coverage\" \"<prepend CFLAGS>\" \"<makefile>\" \"<append CFLAGS>\" <math library to link to>"
echo "CC=gcc ${0} \"coverage\" \" \" \"makefile\" \"-DUSE_LTM -DLTM_DESC -I../libtommath\" ../libtommath/libtommath.a"
exit -1
fi

if [ -z "$(echo $CC | grep "gcc")" ]; then
echo "no gcc detected, early exit success"
exit 0
fi

if [ "$(echo $3 | grep -v 'makefile[.]')" == "" ]; then
echo "only run $0 for the regular makefile, early exit success"
exit 0
fi

# output version
bash printinfo.sh

bash build.sh " $1" " $2" " $3 COVERAGE=1" "$4" "$5"
if [ -a testok.txt ] && [ -f testok.txt ]; then
echo
else
echo
echo "Test failed"
exit 1
fi

./coverage_more.sh > test_coverage_more.txt || { rm -f testok.txt && exit 1 ; }

make lcov-single
# if this was executed as './coverage.sh ...' create coverage locally
if [[ "${0%% *}" == "./${0##*/}" ]]; then
make lcov-html
else
coveralls-lcov coverage.info
fi

exit 0

# ref: $Format:%D$
# git commit: $Format:%H$
# commit time: $Format:%ai$

+ 24
- 0
ext/libtomcrypt/coverage_more.sh View File

@@ -0,0 +1,24 @@
#!/bin/bash

set -e

./sizes
./constants

for i in $(for j in $(echo $(./hashsum -h | tail -n +3)); do echo $j; done | sort); do echo -n "$i: " && ./hashsum -a $i tests/test.key ; done > hashsum_tv.txt
difftroubles=$(diff -i -w -B hashsum_tv.txt notes/hashsum_tv.txt | grep '^<') || true
if [ -n "$difftroubles" ]; then
echo "FAILURE: hashsum_tv.tx"
diff -i -w -B hashsum_tv.txt notes/hashsum_tv.txt
echo "hashsum failed"
exit 1
else
echo "hashsum okay"
fi


exit 0

# ref: $Format:%D$
# git commit: $Format:%H$
# commit time: $Format:%ai$

+ 40
- 0
ext/libtomcrypt/coverity.sh View File

@@ -0,0 +1,40 @@
#!/bin/bash

if [ $# -lt 2 ]
then
echo "usage is: ${0##*/} <path to coverity scan> <extra compiler options>"
echo "e.g. \"${0##*/} \"/usr/local/bin/coverity\" \"-DLTM_DESC -I/path/to/libtommath/\"\""
exit -1
fi

PATH=$PATH:$1/bin

make clean
rm -r cov-int/

myCflags=""
myCflags="$myCflags -O2 ${2}"
myCflags="$myCflags -pipe -Werror -Wpointer-arith -Winit-self -Wextra -Wall -Wformat -Wformat-security"

CFLAGS="$myCflags" cov-build --dir cov-int make -f makefile.unix $MAKE_OPTS IGNORE_SPEED=1 1>gcc_1.txt

if [ $? -ne 0 ]
then
echo "make failed"
exit -1
fi

# zipup everything
tar caf libtomcrypt.lzma cov-int

mytoken=$(cat .coverity_token)
mymail=$(cat .coverity_mail)
myversion=$(git describe --dirty)

curl -k --form project=libtomcrypt \
--form token=${mytoken} \
--form email=${mymail} \
--form file=@libtomcrypt.lzma \
--form version=\"${myversion}\" \
--form description="\"libtomcrypt version ${myversion}\"" \
https://scan.coverity.com/builds?project=libtom%2Flibtomcrypt

+ 52
- 0
ext/libtomcrypt/demos/constants.c View File

@@ -0,0 +1,52 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#include "tomcrypt.h"

/**
@file demo_crypt_constants.c

Demo how to get various constants to dynamic languages
like Python

Larry Bugbee, February 2013
*/


int main(void) {
/* given a specific constant name, get and print its value */
char name[] = "CTR_COUNTER_BIG_ENDIAN";
int value;
char *names_list;
unsigned int names_list_len;

if (crypt_get_constant(name, &value) != 0)
exit(EXIT_FAILURE);
printf("\n %s is %d \n\n", name, value);

/* get and print the length of the names (and values) list */

if (crypt_list_all_constants(NULL, &names_list_len) != 0)
exit(EXIT_FAILURE);
printf(" need to allocate %u bytes \n\n", names_list_len);

/* get and print the names (and values) list */
if ((names_list = malloc(names_list_len)) == NULL)
exit(EXIT_FAILURE);
if (crypt_list_all_constants(names_list, &names_list_len) != 0)
exit(EXIT_FAILURE);
printf(" supported constants:\n\n%s\n\n", names_list);
free(names_list);

return 0;
}


/* ref: $Format:%D$ */
/* git commit: $Format:%H$ */
/* commit time: $Format:%ai$ */

+ 206
- 0
ext/libtomcrypt/demos/demo_dynamic.py View File

@@ -0,0 +1,206 @@


"""
demo_dynamic.py v1

This program demonstrates Python's use of the dynamic
language support additions to LTC, namely access to LTC
constants, struct and union sizes, and the binding of a
math package to LTC. Also provided are simple code
fragments to illustrate how one might write a Python
wrapper for LTC and how an app might call the wrapper.
This or a similar model should work for Ruby and other
dynamic languages.

This instance uses Python's ctypes and requires a single
.dylib linking together LTC and a math library. Building
a single .dylib is needed because LTC wants a fairly tight
relationship between itself and the mathlib. (ctypes can
load multiple .dylibs, but it does not support this level
of tight coupling between otherwise independent libraries.)

My .dylib was created on OSX with the following steps:

1- compile LTC to a .a static lib:
CFLAGS="-DLTM_DESC -DUSE_LTM" make

2- link LTC and LTM into a single .dylib:
ar2dylib_with tomcrypt tommath
where ar2dylib_with is a shell script that combines
the LTC .a with the LTM .dylib

Reminder: you don't need to bind in a math library unless
you are going to use LTC functions that depend
on a mathlib. For example, public key crypto
needs a mathlib; hashing and symmetric encryption
do not.

This code was written for Python 2.7.

Larry Bugbee
March 2014

"""


from ctypes import *
from ctypes.util import find_library


#---------------------------------------------------------------
# load the .dylib

libname = 'tomcrypt'
libpath = find_library(libname)

print
print(' demo_dynamic.py')
print
print(' path to library %s: %s' % (libname, libpath))

LTC = cdll.LoadLibrary(libpath)
print(' loaded: %s' % LTC)
print



#---------------------------------------------------------------
# get list of all supported constants followed by a list of all
# supported sizes. One alternative: these lists may be parsed
# and used as needed.

if 1:
print ' all supported constants and their values:'

# get size to allocate for constants output list
str_len = c_int(0)
ret = LTC.crypt_list_all_constants(None, byref(str_len))
print ' need to allocate %d bytes \n' % str_len.value

# allocate that size and get (name, size) pairs, each pair
# separated by a newline char.
names_sizes = c_buffer(str_len.value)
ret = LTC.crypt_list_all_constants(names_sizes, byref(str_len))
print names_sizes.value
print


if 1:
print ' all supported sizes:'

# get size to allocate for sizes output list
str_len = c_int(0)
ret = LTC.crypt_list_all_sizes(None, byref(str_len))
print ' need to allocate %d bytes \n' % str_len.value

# allocate that size and get (name, size) pairs, each pair
# separated by a newline char.
names_sizes = c_buffer(str_len.value)
ret = LTC.crypt_list_all_sizes(names_sizes, byref(str_len))
print names_sizes.value
print


#---------------------------------------------------------------
# get individually named constants and sizes

# print selected constants
if 1:
print '\n selected constants:'

names = [
'ENDIAN_LITTLE',
'ENDIAN_64BITWORD',
'PK_PUBLIC',
'MAX_RSA_SIZE',
'CTR_COUNTER_BIG_ENDIAN',
]
for name in names:
const_value = c_int(0)
rc = LTC.crypt_get_constant(name, byref(const_value))
value = const_value.value
print ' %-25s %d' % (name, value)

# print selected sizes
if 1:
print '\n selected sizes:'

names = [
'rijndael_key',
'rsa_key',
'symmetric_CTR',
'twofish_key',
'ecc_point',
'gcm_state',
'sha512_state',
]
for name in names:
size_value = c_int(0)
rc = LTC.crypt_get_size(name, byref(size_value))
value = size_value.value
print ' %-25s %d' % (name, value)


#---------------------------------------------------------------
#---------------------------------------------------------------
# ctypes getting a list of this build's supported algorithms
# and compiler switches

def get_named_string(lib, name):
return c_char_p.in_dll(lib, name).value

if 0:
print '\n%s' % ('-'*60)
print 'This is a string compiled into LTC showing compile '
print 'options and algorithms supported by this build \n'
print get_named_string(LTC, 'crypt_build_settings')
print



#---------------------------------------------------------------
#---------------------------------------------------------------
# here is an example of how a wrapper can make Python access
# more Pythonic

# - - - - - - - - - - - - -
# a wrapper fragment...

def _get_size(name):
size = c_int(0)
rc = LTC.crypt_get_size(name, byref(size))
return size.value

sha256_state_struct_size = _get_size('sha256_state')
sha512_state_struct_size = _get_size('sha512_state')

class SHA256(object):
def __init__(self):
self.state = c_buffer(sha256_state_struct_size)
LTC.sha256_init(byref(self.state))
def update(self, data):
LTC.sha256_process(byref(self.state), data, len(data))
def digest(self):
md = c_buffer(32)
LTC.sha256_done(byref(self.state), byref(md))
return md.raw

# - - - - - - - - - - - - -
# an app fragment...

# from wrapper import * # uncomment in real life

data = 'hello world'

sha256 = SHA256()
sha256.update(data)
md = sha256.digest()

template = '\n\n the SHA256 digest for "%s" is %s \n'
print template % (data, md.encode('hex'))



#---------------------------------------------------------------
#---------------------------------------------------------------
#---------------------------------------------------------------

+ 284
- 0
ext/libtomcrypt/demos/hashsum.c View File

@@ -0,0 +1,284 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/

/*
* Written by Daniel Richards <kyhwana@world-net.co.nz> 6/7/2002
* hash.c: This app uses libtomcrypt to hash either stdin or a file
* This file is Public Domain. No rights are reserved.
* Compile with 'gcc hashsum.c -o hashsum -ltomcrypt'
* This example isn't really big enough to warrent splitting into
* more functions ;)
*/

#include <tomcrypt.h>

#if _POSIX_C_SOURCE >= 200112L
#include <libgen.h>
#else
#define basename(x) x
#endif

#if !defined(PATH_MAX) && defined(_MSC_VER)
#include <windows.h>
#define PATH_MAX MAX_PATH
#endif

/* thanks http://stackoverflow.com/a/8198009 */
#define _base(x) ((x >= '0' && x <= '9') ? '0' : \
(x >= 'a' && x <= 'f') ? 'a' - 10 : \
(x >= 'A' && x <= 'F') ? 'A' - 10 : \
'\255')
#define HEXOF(x) (x - _base(x))

static char* hashsum;

static void die(int status)
{
unsigned long w, x;
FILE* o = status == EXIT_SUCCESS ? stdout : stderr;
fprintf(o, "usage: %s -a algorithm [-c] [file...]\n", hashsum);
fprintf(o, "Algorithms:\n");
w = 0;
for (x = 0; hash_descriptor[x].name != NULL; x++) {
w += fprintf(o, "%-14s", hash_descriptor[x].name);
if (w >= 70) {
fprintf(o, "\n");
w = 0;
}
}
if (w != 0) fprintf(o, "\n");
free(hashsum);
exit(status);
}

static void printf_hex(unsigned char* hash_buffer, unsigned long w)
{
unsigned long x;
for (x = 0; x < w; x++) {
printf("%02x",hash_buffer[x]);
}
}

static void check_file(int argn, int argc, char **argv)
{
int err, failed, invalid;
unsigned char is_buffer[MAXBLOCKSIZE], should_buffer[MAXBLOCKSIZE];
char buf[PATH_MAX + (MAXBLOCKSIZE * 3)];
/* iterate through all files */
while(argn < argc) {
char* s;
FILE* f = fopen(argv[argn], "rb");
if(f == NULL) {
int n = snprintf(buf, sizeof(buf), "%s: %s", hashsum, argv[argn]);
if (n > 0 && n < (int)sizeof(buf))
perror(buf);
else
perror(argv[argn]);
exit(EXIT_FAILURE);
}
failed = 0;
invalid = 0;
/* read the file line by line */
while((s = fgets(buf, sizeof(buf), f)) != NULL)
{
int tries, n;
unsigned long hash_len, w, x;
char* space = strstr(s, " ");
if (space == NULL) {
fprintf(stderr, "%s: no properly formatted checksum lines found\n", hashsum);
goto ERR;
}

hash_len = space - s;
hash_len /= 2;

/* convert the hex-string back to binary */
for (x = 0; x < hash_len; ++x) {
should_buffer[x] = HEXOF(s[x*2]) << 4 | HEXOF(s[x*2 + 1]);
}

space++;
if (*space != '*') {
fprintf(stderr, "%s: unsupported input mode '%c'\n", hashsum, *space);
goto ERR;
}
space++;

for (n = 0; n < (buf + sizeof(buf)) - space; ++n) {
if(iscntrl((int)space[n])) {
space[n] = '\0';
break;
}
}

/* try all hash algorithms that have the appropriate hash size */
tries = 0;
for (x = 0; hash_descriptor[x].name != NULL; ++x) {
if (hash_descriptor[x].hashsize == hash_len) {
tries++;
w = sizeof(is_buffer);
if ((err = hash_file(x, space, is_buffer, &w)) != CRYPT_OK) {
fprintf(stderr, "%s: File hash error: %s: %s\n", hashsum, space, error_to_string(err));
ERR:
fclose(f);
exit(EXIT_FAILURE);
}
if(XMEMCMP(should_buffer, is_buffer, w) == 0) {
printf("%s: OK\n", space);
break;
}
}
} /* for */
if (hash_descriptor[x].name == NULL) {
if(tries > 0) {
printf("%s: FAILED\n", space);
failed++;
}
else {
invalid++;
}
}
} /* while */
fclose(f);
if(invalid) {
fprintf(stderr, "%s: WARNING: %d %s is improperly formatted\n", hashsum, invalid, invalid > 1?"lines":"line");
}
if(failed) {
fprintf(stderr, "%s: WARNING: %d computed %s did NOT match\n", hashsum, failed, failed > 1?"checksums":"checksum");
}
argn++;
}
exit(EXIT_SUCCESS);
}

int main(int argc, char **argv)
{
int idxs[TAB_SIZE], idx, check, y, z, err, argn;
unsigned long w, x;
unsigned char hash_buffer[MAXBLOCKSIZE];

hashsum = strdup(basename(argv[0]));

/* You need to register algorithms before using them */
register_all_ciphers();
register_all_hashes();
if (argc > 1 && (strcmp("-h", argv[1]) == 0 || strcmp("--help", argv[1]) == 0)) {
die(EXIT_SUCCESS);
}
if (argc < 3) {
die(EXIT_FAILURE);
}

for (x = 0; x < sizeof(idxs)/sizeof(idxs[0]); ++x) {
idxs[x] = -2;
}
argn = 1;
check = 0;
idx = 0;

while(argn < argc){
if(strcmp("-a", argv[argn]) == 0) {
argn++;
if(argn < argc) {
idxs[idx] = find_hash(argv[argn]);
if (idxs[idx] == -1) {
struct {
const char* is;
const char* should;
} shasum_compat[] =
{
#ifdef LTC_SHA1
{ "1", sha1_desc.name },
#endif
#ifdef LTC_SHA224
{ "224", sha224_desc.name },
#endif
#ifdef LTC_SHA256
{ "256", sha256_desc.name },
#endif
#ifdef LTC_SHA384
{ "384", sha384_desc.name },
#endif
#ifdef LTC_SHA512
{ "512", sha512_desc.name },
#endif
#ifdef LTC_SHA512_224
{ "512224", sha512_224_desc.name },
#endif
#ifdef LTC_SHA512_256
{ "512256", sha512_256_desc.name },
#endif
{ NULL, NULL }
};
for (x = 0; shasum_compat[x].is != NULL; ++x) {
if(XSTRCMP(shasum_compat[x].is, argv[argn]) == 0) {
idxs[idx] = find_hash(shasum_compat[x].should);
break;
}
}
}
if (idxs[idx] == -1) {
fprintf(stderr, "%s: Unrecognized algorithm\n", hashsum);
die(EXIT_FAILURE);
}
idx++;
if ((size_t)idx >= sizeof(idxs)/sizeof(idxs[0])) {
fprintf(stderr, "%s: Too many '-a' options chosen\n", hashsum);
die(EXIT_FAILURE);
}
argn++;
continue;
}
else {
die(EXIT_FAILURE);
}
}
if(strcmp("-c", argv[argn]) == 0) {
check = 1;
argn++;
continue;
}
break;
}

if (check == 1) {
check_file(argn, argc, argv);
}

if (argc == argn) {
w = sizeof(hash_buffer);
if ((err = hash_filehandle(idxs[0], stdin, hash_buffer, &w)) != CRYPT_OK) {
fprintf(stderr, "%s: File hash error: %s\n", hashsum, error_to_string(err));
return EXIT_FAILURE;
} else {
for (x = 0; x < w; x++) {
printf("%02x",hash_buffer[x]);
}
printf(" *-\n");
}
} else {
for (z = argn; z < argc; z++) {
for (y = 0; y < idx; ++y) {
w = sizeof(hash_buffer);
if ((err = hash_file(idxs[y],argv[z],hash_buffer,&w)) != CRYPT_OK) {
fprintf(stderr, "%s: File hash error: %s\n", hashsum, error_to_string(err));
return EXIT_FAILURE;
} else {
printf_hex(hash_buffer, w);
printf(" *%s\n", argv[z]);
}
}
}
}
return EXIT_SUCCESS;
}

/* ref: $Format:%D$ */
/* git commit: $Format:%H$ */
/* commit time: $Format:%ai$ */

+ 204
- 0
ext/libtomcrypt/demos/ltcrypt.c View File

@@ -0,0 +1,204 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/

/* encrypt V1.1 Fri Oct 18 04:28:03 NZDT 2002 */
/* File de/encryption, using libtomcrypt */
/* Written by Daniel Richards <kyhwana@world-net.co.nz> */
/* Help from Tom St Denis with various bits */
/* This code is public domain, no rights reserved. */
/* Encrypts by default, -d flag enables decryption */
/* ie: ./encrypt blowfish story.txt story.ct */
/* ./encrypt -d blowfish story.ct story.pt */

#include <tomcrypt.h>

int usage(char *name)
{
int x;

printf("Usage encrypt: %s cipher infile outfile\n", name);
printf("Usage decrypt: %s -d cipher infile outfile\n", name);
printf("Usage test: %s -t cipher\nCiphers:\n", name);
for (x = 0; cipher_descriptor[x].name != NULL; x++) {
printf("%s\n",cipher_descriptor[x].name);
}
exit(1);
}

int main(int argc, char *argv[])
{
unsigned char plaintext[512],ciphertext[512];
unsigned char tmpkey[512], key[MAXBLOCKSIZE], IV[MAXBLOCKSIZE];
unsigned char inbuf[512]; /* i/o block size */
unsigned long outlen, y, ivsize, x, decrypt;
symmetric_CTR ctr;
int cipher_idx, hash_idx, ks;
char *infile, *outfile, *cipher;
prng_state prng;
FILE *fdin, *fdout;
int err;

/* register algs, so they can be printed */
register_all_ciphers();
register_all_hashes();

if (argc < 4) {
if ((argc > 2) && (!strcmp(argv[1], "-t"))) {
cipher = argv[2];
cipher_idx = find_cipher(cipher);
if (cipher_idx == -1) {
printf("Invalid cipher %s entered on command line.\n", cipher);
exit(-1);
} /* if */
if (cipher_descriptor[cipher_idx].test)
{
if (cipher_descriptor[cipher_idx].test() != CRYPT_OK)
{
printf("Error when testing cipher %s.\n", cipher);
exit(-1);
}
else
{
printf("Testing cipher %s succeeded.\n", cipher);
exit(0);
} /* if ... else */
} /* if */
}
return usage(argv[0]);
}

if (!strcmp(argv[1], "-d")) {
decrypt = 1;
cipher = argv[2];
infile = argv[3];
outfile = argv[4];
} else {
decrypt = 0;
cipher = argv[1];
infile = argv[2];
outfile = argv[3];
}

/* file handles setup */
fdin = fopen(infile,"rb");
if (fdin == NULL) {
perror("Can't open input for reading");
exit(-1);
}

fdout = fopen(outfile,"wb");
if (fdout == NULL) {
perror("Can't open output for writing");
exit(-1);
}

cipher_idx = find_cipher(cipher);
if (cipher_idx == -1) {
printf("Invalid cipher entered on command line.\n");
exit(-1);
}

hash_idx = find_hash("sha256");
if (hash_idx == -1) {
printf("LTC_SHA256 not found...?\n");
exit(-1);
}

ivsize = cipher_descriptor[cipher_idx].block_length;
ks = hash_descriptor[hash_idx].hashsize;
if (cipher_descriptor[cipher_idx].keysize(&ks) != CRYPT_OK) {
printf("Invalid keysize???\n");
exit(-1);
}

printf("\nEnter key: ");
if(fgets((char *)tmpkey,sizeof(tmpkey), stdin) == NULL)
exit(-1);
outlen = sizeof(key);
if ((err = hash_memory(hash_idx,tmpkey,strlen((char *)tmpkey),key,&outlen)) != CRYPT_OK) {
printf("Error hashing key: %s\n", error_to_string(err));
exit(-1);
}

if (decrypt) {
/* Need to read in IV */
if (fread(IV,1,ivsize,fdin) != ivsize) {
printf("Error reading IV from input.\n");
exit(-1);
}

if ((err = ctr_start(cipher_idx,IV,key,ks,0,CTR_COUNTER_LITTLE_ENDIAN,&ctr)) != CRYPT_OK) {
printf("ctr_start error: %s\n",error_to_string(err));
exit(-1);
}

/* IV done */
do {
y = fread(inbuf,1,sizeof(inbuf),fdin);

if ((err = ctr_decrypt(inbuf,plaintext,y,&ctr)) != CRYPT_OK) {
printf("ctr_decrypt error: %s\n", error_to_string(err));
exit(-1);
}

if (fwrite(plaintext,1,y,fdout) != y) {
printf("Error writing to file.\n");
exit(-1);
}
} while (y == sizeof(inbuf));
fclose(fdin);
fclose(fdout);

} else { /* encrypt */
/* Setup yarrow for random bytes for IV */

if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL)) != CRYPT_OK) {
printf("Error setting up PRNG, %s\n", error_to_string(err));
}

/* You can use rng_get_bytes on platforms that support it */
/* x = rng_get_bytes(IV,ivsize,NULL);*/
x = yarrow_read(IV,ivsize,&prng);
if (x != ivsize) {
printf("Error reading PRNG for IV required.\n");
exit(-1);
}

if (fwrite(IV,1,ivsize,fdout) != ivsize) {
printf("Error writing IV to output.\n");
exit(-1);
}

if ((err = ctr_start(cipher_idx,IV,key,ks,0,CTR_COUNTER_LITTLE_ENDIAN,&ctr)) != CRYPT_OK) {
printf("ctr_start error: %s\n",error_to_string(err));
exit(-1);
}

do {
y = fread(inbuf,1,sizeof(inbuf),fdin);

if ((err = ctr_encrypt(inbuf,ciphertext,y,&ctr)) != CRYPT_OK) {
printf("ctr_encrypt error: %s\n", error_to_string(err));
exit(-1);
}

if (fwrite(ciphertext,1,y,fdout) != y) {
printf("Error writing to output.\n");
exit(-1);
}
} while (y == sizeof(inbuf));
fclose(fdout);
fclose(fdin);
}
return 0;
}

/* ref: $Format:%D$ */
/* git commit: $Format:%H$ */
/* commit time: $Format:%ai$ */

+ 397
- 0
ext/libtomcrypt/demos/openssl-enc.c View File

@@ -0,0 +1,397 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/

/*
* Demo to do the rough equivalent of:
*
* openssl enc -aes-256-cbc -pass pass:foobar -in infile -out outfile -p
*
* Compilation:
*
* $(CC) -I /path/to/headers -L .../libs \
* -o openssl-enc \
* openssl-enc.c -ltomcrypt
*
* Usage:
*
* ./openssl-enc <enc|dec> infile outfile "passphrase" [salt]
*
* If provided, the salt must be EXACTLY a 16-char hex string.
*
* Demo is an example of:
*
* - (When decrypting) yanking salt out of the OpenSSL "Salted__..." header
* - OpenSSL-compatible key derivation (in OpenSSL's modified PKCS#5v1 approach)
* - Grabbing an Initialization Vector from the key generator
* - Performing simple block encryption using AES
* - PKCS#7-type padding (which hopefully can get ripped out of this demo and
* made a libtomcrypt thing someday).
*
* This program is free for all purposes without any express guarantee it
* works. If you really want to see a license here, assume the WTFPL :-)
*
* BJ Black, bblack@barracuda.com, https://wjblack.com
*
* BUGS:
* Passing a password on a command line is a HORRIBLE idea. Don't use
* this program for serious work!
*/

#include <tomcrypt.h>

#ifndef LTC_RIJNDAEL
#error Cannot compile this demo; Rijndael (AES) required
#endif
#ifndef LTC_CBC_MODE
#error Cannot compile this demo; CBC mode required
#endif
#ifndef LTC_PKCS_5
#error Cannot compile this demo; PKCS5 required
#endif
#ifndef LTC_RNG_GET_BYTES
#error Cannot compile this demo; random generator required
#endif
#ifndef LTC_MD5
#error Cannot compile this demo; MD5 required
#endif

/* OpenSSL by default only runs one hash round */
#define OPENSSL_ITERATIONS 1
/* Use aes-256-cbc, so 256 bits of key, 128 of IV */
#define KEY_LENGTH (256>>3)
#define IV_LENGTH (128>>3)
/* PKCS#5v1 requires exactly an 8-byte salt */
#define SALT_LENGTH 8
/* The header OpenSSL puts on an encrypted file */
static char salt_header[] = { 'S', 'a', 'l', 't', 'e', 'd', '_', '_' };

#include <errno.h>
#include <stdio.h>
#include <string.h>

/* A simple way to handle the possibility that a block may increase in size
after padding. */
union paddable {
unsigned char unpad[1024];
unsigned char pad[1024+MAXBLOCKSIZE];
};

/*
* Print usage and exit with a bad status (and perror() if any errno).
*
* Input: argv[0] and the error string
* Output: <no return>
* Side Effects: print messages and barf (does exit(3))
*/
void barf(char *pname, char *err)
{
printf("Usage: %s <enc|dec> infile outfile [salt]\n", pname);
printf("\n");
printf(" # encrypts infile->outfile, random salt\n");
printf(" %s enc infile outfile \"passphrase\"\n", pname);
printf("\n");
printf(" # encrypts infile->outfile, salt from cmdline\n");
printf(" %s enc infile outfile pass 0123456789abcdef\n", pname);
printf("\n");
printf(" # decrypts infile->outfile, pulls salt from infile\n");
printf(" %s dec infile outfile pass\n", pname);
printf("\n");
printf(" # decrypts infile->outfile, salt specified\n");
printf(" # (don't try to read the salt from infile)\n");
printf(" %s dec infile outfile pass 0123456789abcdef"
"\n", pname);
printf("\n");
printf("Application Error: %s\n", err);
if(errno)
perror(" System Error");
exit(-1);
}

/*
* Parse a salt value passed in on the cmdline.
*
* Input: string passed in and a buf to put it in (exactly 8 bytes!)
* Output: CRYPT_OK if parsed OK, CRYPT_ERROR if not
* Side Effects: none
*/
int parse_hex_salt(unsigned char *in, unsigned char *out)
{
int idx;
for(idx=0; idx<SALT_LENGTH; idx++)
if(sscanf((char*)in+idx*2, "%02hhx", out+idx) != 1)
return CRYPT_ERROR;
return CRYPT_OK;
}

/*
* Parse the Salted__[+8 bytes] from an OpenSSL-compatible file header.
*
* Input: file to read from and a to put the salt in (exactly 8 bytes!)
* Output: CRYPT_OK if parsed OK, CRYPT_ERROR if not
* Side Effects: infile's read pointer += 16
*/
int parse_openssl_header(FILE *in, unsigned char *out)
{
unsigned char tmp[SALT_LENGTH];
if(fread(tmp, 1, sizeof(tmp), in) != sizeof(tmp))
return CRYPT_ERROR;
if(memcmp(tmp, salt_header, sizeof(tmp)))
return CRYPT_ERROR;
if(fread(tmp, 1, sizeof(tmp), in) != sizeof(tmp))
return CRYPT_ERROR;
memcpy(out, tmp, sizeof(tmp));
return CRYPT_OK;
}

/*
* Dump a hexed stream of bytes (convenience func).
*
* Input: buf to read from, length
* Output: none
* Side Effects: bytes printed as a hex blob, no lf at the end
*/
void dump_bytes(unsigned char *in, unsigned long len)
{
unsigned long idx;
for(idx=0; idx<len; idx++)
printf("%02hhX", *(in+idx));
}

/*
* Pad or unpad a message using PKCS#7 padding.
* Padding will add 1-(blocksize) bytes and unpadding will remove that amount.
* Set is_padding to 1 to pad, 0 to unpad.
*
* Input: paddable buffer, size read, block length of cipher, mode
* Output: number of bytes after padding resp. after unpadding
* Side Effects: none
*/
size_t pkcs7_pad(union paddable *buf, size_t nb, int block_length,
int is_padding)
{
unsigned char padval;
off_t idx;

if(is_padding) {
/* We are PADDING this block (and therefore adding bytes) */
/* The pad value in PKCS#7 is the number of bytes remaining in
the block, so for a 16-byte block and 3 bytes left, it's
0x030303. In the oddball case where nb is an exact multiple
multiple of block_length, set the padval to blocksize (i.e.
add one full block) */
padval = (unsigned char) (block_length - (nb % block_length));
padval = padval ? padval : block_length;

memset(buf->pad+nb, padval, padval);
return nb+padval;
} else {
/* We are UNPADDING this block (and removing bytes)
We really just need to verify that the pad bytes are correct,
so start at the end of the string and work backwards. */

/* Figure out what the padlength should be by looking at the
last byte */
idx = nb-1;
padval = buf->pad[idx];

/* padval must be nonzero and <= block length */
if(padval <= 0 || padval > block_length)
return 0;

/* First byte's accounted for; do the rest */
idx--;

while(idx >= (off_t)(nb-padval))
if(buf->pad[idx] != padval)
return 0;
else
idx--;

/* If we got here, the pad checked out, so return a smaller
number of bytes than nb (basically where we left off+1) */
return idx+1;
}
}

/*
* Perform an encrypt/decrypt operation to/from files using AES+CBC+PKCS7 pad.
* Set encrypt to 1 to encrypt, 0 to decrypt.
*
* Input: in/out files, key, iv, and mode
* Output: CRYPT_OK if no error
* Side Effects: bytes slurped from infile, pushed to outfile, fds updated.
*/
int do_crypt(FILE *infd, FILE *outfd, unsigned char *key, unsigned char *iv,
int encrypt)
{
union paddable inbuf, outbuf;
int cipher, ret;
symmetric_CBC cbc;
size_t nb;

/* Register your cipher! */
cipher = register_cipher(&aes_desc);
if(cipher == -1)
return CRYPT_INVALID_CIPHER;

/* Start a CBC session with cipher/key/val params */
ret = cbc_start(cipher, iv, key, KEY_LENGTH, 0, &cbc);
if( ret != CRYPT_OK )
return -1;

do {
/* Get bytes from the source */
nb = fread(inbuf.unpad, 1, sizeof(inbuf.unpad), infd);
if(!nb)
return encrypt ? CRYPT_OK : CRYPT_ERROR;

/* Barf if we got a read error */
if(ferror(infd))
return CRYPT_ERROR;

if(encrypt) {
/* We're encrypting, so pad first (if at EOF) and then
crypt */
if(feof(infd))
nb = pkcs7_pad(&inbuf, nb,
aes_desc.block_length, 1);

ret = cbc_encrypt(inbuf.pad, outbuf.pad, nb, &cbc);
if(ret != CRYPT_OK)
return ret;

} else {
/* We're decrypting, so decrypt and then unpad if at
EOF */
ret = cbc_decrypt(inbuf.unpad, outbuf.unpad, nb, &cbc);
if( ret != CRYPT_OK )
return ret;

if( feof(infd) )
nb = pkcs7_pad(&outbuf, nb,
aes_desc.block_length, 0);
if(nb == 0)
/* The file didn't decrypt correctly */
return CRYPT_ERROR;

}

/* Push bytes to outfile */
if(fwrite(outbuf.unpad, 1, nb, outfd) != nb)
return CRYPT_ERROR;

} while(!feof(infd));

/* Close up */
cbc_done(&cbc);

return CRYPT_OK;
}

/* Convenience macro for the various barfable places below */
#define BARF(a) { \
if(infd) fclose(infd); \
if(outfd) { fclose(outfd); remove(argv[3]); } \
barf(argv[0], a); \
}
/*
* The main routine. Mostly validate cmdline params, open files, run the KDF,
* and do the crypt.
*/
int main(int argc, char *argv[]) {
unsigned char salt[SALT_LENGTH];
FILE *infd = NULL, *outfd = NULL;
int encrypt = -1;
int hash = -1;
int ret;
unsigned char keyiv[KEY_LENGTH + IV_LENGTH];
unsigned long keyivlen = (KEY_LENGTH + IV_LENGTH);
unsigned char *key, *iv;

/* Check proper number of cmdline args */
if(argc < 5 || argc > 6)
BARF("Invalid number of arguments");

/* Check proper mode of operation */
if (!strncmp(argv[1], "enc", 3))
encrypt = 1;
else if(!strncmp(argv[1], "dec", 3))
encrypt = 0;
else
BARF("Bad command name");

/* Check we can open infile/outfile */
infd = fopen(argv[2], "rb");
if(infd == NULL)
BARF("Could not open infile");
outfd = fopen(argv[3], "wb");
if(outfd == NULL)
BARF("Could not open outfile");

/* Get the salt from wherever */
if(argc == 6) {
/* User-provided */
if(parse_hex_salt((unsigned char*) argv[5], salt) != CRYPT_OK)
BARF("Bad user-specified salt");
} else if(!strncmp(argv[1], "enc", 3)) {
/* Encrypting; get from RNG */
if(rng_get_bytes(salt, sizeof(salt), NULL) != sizeof(salt))
BARF("Not enough random data");
} else {
/* Parse from infile (decrypt only) */
if(parse_openssl_header(infd, salt) != CRYPT_OK)
BARF("Invalid OpenSSL header in infile");
}

/* Fetch the MD5 hasher for PKCS#5 */
hash = register_hash(&md5_desc);
if(hash == -1)
BARF("Could not register MD5 hash");

/* Set things to a sane initial state */
zeromem(keyiv, sizeof(keyiv));
key = keyiv + 0; /* key comes first */
iv = keyiv + KEY_LENGTH; /* iv comes next */

/* Run the key derivation from the provided passphrase. This gets us
the key and iv. */
ret = pkcs_5_alg1_openssl((unsigned char*)argv[4], strlen(argv[4]), salt,
OPENSSL_ITERATIONS, hash, keyiv, &keyivlen );
if(ret != CRYPT_OK)
BARF("Could not derive key/iv from passphrase");

/* Display the salt/key/iv like OpenSSL cmdline does when -p */
printf("salt="); dump_bytes(salt, sizeof(salt)); printf("\n");
printf("key="); dump_bytes(key, KEY_LENGTH); printf("\n");
printf("iv ="); dump_bytes(iv, IV_LENGTH ); printf("\n");

/* If we're encrypting, write the salt header as OpenSSL does */
if(!strncmp(argv[1], "enc", 3)) {
if(fwrite(salt_header, 1, sizeof(salt_header), outfd) !=
sizeof(salt_header) )
BARF("Error writing salt header to outfile");
if(fwrite(salt, 1, sizeof(salt), outfd) != sizeof(salt))
BARF("Error writing salt to outfile");
}

/* At this point, the files are open, the salt has been figured out,
and we're ready to pump data through crypt. */

/* Do the crypt operation */
if(do_crypt(infd, outfd, key, iv, encrypt) != CRYPT_OK)
BARF("Error during crypt operation");

/* Clean up */
fclose(infd); fclose(outfd);
return 0;
}

/* ref: $Format:%D$ */
/* git commit: $Format:%H$ */
/* commit time: $Format:%ai$ */

+ 45
- 0
ext/libtomcrypt/demos/sizes.c View File

@@ -0,0 +1,45 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#include "tomcrypt.h"

/**
@file demo_crypt_sizes.c

Demo how to get various sizes to dynamic languages
like Python - Larry Bugbee, February 2013
*/


int main(void) {

/* given a specific size name, get and print its size */
char name[] = "ecc_key";
unsigned int size;
char *sizes_list;
unsigned int sizes_list_len;
if(crypt_get_size(name, &size) != 0)
exit(EXIT_FAILURE);
printf("\n size of '%s' is %u \n\n", name, size);

/* get and print the length of the names (and sizes) list */
if(crypt_list_all_sizes(NULL, &sizes_list_len) != 0)
exit(EXIT_FAILURE);
printf(" need to allocate %u bytes \n\n", sizes_list_len);

/* get and print the names (and sizes) list */
sizes_list = malloc(sizes_list_len);
if(crypt_list_all_sizes(sizes_list, &sizes_list_len) != 0)
exit(EXIT_FAILURE);
printf(" supported sizes:\n\n%s\n\n", sizes_list);
return 0;
}

/* ref: $Format:%D$ */
/* git commit: $Format:%H$ */
/* commit time: $Format:%ai$ */

+ 22
- 0
ext/libtomcrypt/demos/small.c View File

@@ -0,0 +1,22 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
/* small demo app that just includes a cipher/hash/prng */
#include <tomcrypt.h>

int main(void)
{
register_cipher(&rijndael_enc_desc);
register_prng(&yarrow_desc);
register_hash(&sha256_desc);
return 0;
}

/* ref: $Format:%D$ */
/* git commit: $Format:%H$ */
/* commit time: $Format:%ai$ */

+ 1456
- 0
ext/libtomcrypt/demos/timing.c
File diff suppressed because it is too large
View File


+ 797
- 0
ext/libtomcrypt/demos/tv_gen.c View File

@@ -0,0 +1,797 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#include <tomcrypt.h>

void hash_gen(void)
{
unsigned char md[MAXBLOCKSIZE], *buf;
unsigned long outlen, x, y, z;
FILE *out;
int err;

out = fopen("hash_tv.txt", "w");
if (out == NULL) {
perror("can't open hash_tv");
}

fprintf(out, "Hash Test Vectors:\n\nThese are the hashes of nn bytes '00 01 02 03 .. (nn-1)'\n\n");
for (x = 0; hash_descriptor[x].name != NULL; x++) {
buf = XMALLOC(2 * hash_descriptor[x].blocksize + 1);
if (buf == NULL) {
perror("can't alloc mem");
exit(EXIT_FAILURE);
}
fprintf(out, "Hash: %s\n", hash_descriptor[x].name);
for (y = 0; y <= (hash_descriptor[x].blocksize * 2); y++) {
for (z = 0; z < y; z++) {
buf[z] = (unsigned char)(z & 255);
}
outlen = sizeof(md);
if ((err = hash_memory(x, buf, y, md, &outlen)) != CRYPT_OK) {
printf("hash_memory error: %s\n", error_to_string(err));
exit(EXIT_FAILURE);
}
fprintf(out, "%3lu: ", y);
for (z = 0; z < outlen; z++) {
fprintf(out, "%02X", md[z]);
}
fprintf(out, "\n");
}
fprintf(out, "\n");
XFREE(buf);
}
fclose(out);
}

void cipher_gen(void)
{
unsigned char *key, pt[MAXBLOCKSIZE];
unsigned long x, y, z, w;
int err, kl, lastkl;
FILE *out;
symmetric_key skey;

out = fopen("cipher_tv.txt", "w");

fprintf(out,
"Cipher Test Vectors\n\nThese are test encryptions with key of nn bytes '00 01 02 03 .. (nn-1)' and original PT of the same style.\n"
"The output of step N is used as the key and plaintext for step N+1 (key bytes repeated as required to fill the key)\n\n");

for (x = 0; cipher_descriptor[x].name != NULL; x++) {
fprintf(out, "Cipher: %s\n", cipher_descriptor[x].name);

/* three modes, smallest, medium, large keys */
lastkl = 10000;
for (y = 0; y < 3; y++) {
switch (y) {
case 0: kl = cipher_descriptor[x].min_key_length; break;
case 1: kl = (cipher_descriptor[x].min_key_length + cipher_descriptor[x].max_key_length)/2; break;
case 2: kl = cipher_descriptor[x].max_key_length; break;
}
if ((err = cipher_descriptor[x].keysize(&kl)) != CRYPT_OK) {
printf("keysize error: %s\n", error_to_string(err));
exit(EXIT_FAILURE);
}
if (kl == lastkl) break;
lastkl = kl;
fprintf(out, "Key Size: %d bytes\n", kl);

key = XMALLOC(kl);
if (key == NULL) {
perror("can't malloc memory");
exit(EXIT_FAILURE);
}

for (z = 0; (int)z < kl; z++) {
key[z] = (unsigned char)z;
}
if ((err = cipher_descriptor[x].setup(key, kl, 0, &skey)) != CRYPT_OK) {
printf("setup error: %s\n", error_to_string(err));
exit(EXIT_FAILURE);
}

for (z = 0; (int)z < cipher_descriptor[x].block_length; z++) {
pt[z] = (unsigned char)z;
}
for (w = 0; w < 50; w++) {
cipher_descriptor[x].ecb_encrypt(pt, pt, &skey);
fprintf(out, "%2lu: ", w);
for (z = 0; (int)z < cipher_descriptor[x].block_length; z++) {
fprintf(out, "%02X", pt[z]);
}
fprintf(out, "\n");

/* reschedule a new key */
for (z = 0; z < (unsigned long)kl; z++) {
key[z] = pt[z % cipher_descriptor[x].block_length];
}
if ((err = cipher_descriptor[x].setup(key, kl, 0, &skey)) != CRYPT_OK) {
printf("cipher setup2 error: %s\n", error_to_string(err));
exit(EXIT_FAILURE);
}
}
fprintf(out, "\n");
XFREE(key);
}
fprintf(out, "\n");
}
fclose(out);
}

void hmac_gen(void)
{
unsigned char key[MAXBLOCKSIZE], output[MAXBLOCKSIZE], *input;
int x, y, z, err;
FILE *out;
unsigned long len;

out = fopen("hmac_tv.txt", "w");

fprintf(out,
"HMAC Tests. In these tests messages of N bytes long (00,01,02,...,NN-1) are HMACed. The initial key is\n"
"of the same format (the same length as the HASH output size). The HMAC key in step N+1 is the HMAC output of\n"
"step N.\n\n");

for (x = 0; hash_descriptor[x].name != NULL; x++) {
fprintf(out, "HMAC-%s\n", hash_descriptor[x].name);

/* initial key */
for (y = 0; y < (int)hash_descriptor[x].hashsize; y++) {
key[y] = (y&255);
}

input = XMALLOC(hash_descriptor[x].blocksize * 2 + 1);
if (input == NULL) {
perror("Can't malloc memory");
exit(EXIT_FAILURE);
}

for (y = 0; y <= (int)(hash_descriptor[x].blocksize * 2); y++) {
for (z = 0; z < y; z++) {
input[z] = (unsigned char)(z & 255);
}
len = sizeof(output);
if ((err = hmac_memory(x, key, hash_descriptor[x].hashsize, input, y, output, &len)) != CRYPT_OK) {
printf("Error hmacing: %s\n", error_to_string(err));
exit(EXIT_FAILURE);
}
fprintf(out, "%3d: ", y);
for (z = 0; z <(int) len; z++) {
fprintf(out, "%02X", output[z]);
}
fprintf(out, "\n");

/* forward the key */
memcpy(key, output, hash_descriptor[x].hashsize);
}
XFREE(input);
fprintf(out, "\n");
}
fclose(out);
}

void omac_gen(void)
{
#ifdef LTC_OMAC
unsigned char key[MAXBLOCKSIZE], output[MAXBLOCKSIZE], input[MAXBLOCKSIZE*2+2];
int err, x, y, z, kl;
FILE *out;
unsigned long len;

out = fopen("omac_tv.txt", "w");

fprintf(out,
"OMAC Tests. In these tests messages of N bytes long (00,01,02,...,NN-1) are OMAC'ed. The initial key is\n"
"of the same format (length specified per cipher). The OMAC key in step N+1 is the OMAC output of\n"
"step N (repeated as required to fill the array).\n\n");

for (x = 0; cipher_descriptor[x].name != NULL; x++) {
kl = cipher_descriptor[x].block_length;

/* skip ciphers which do not have 64 or 128 bit block sizes */
if (kl != 8 && kl != 16) continue;

if (cipher_descriptor[x].keysize(&kl) != CRYPT_OK) {
kl = cipher_descriptor[x].max_key_length;
}
fprintf(out, "OMAC-%s (%d byte key)\n", cipher_descriptor[x].name, kl);

/* initial key/block */
for (y = 0; y < kl; y++) {
key[y] = (y & 255);
}

for (y = 0; y <= (int)(cipher_descriptor[x].block_length*2); y++) {
for (z = 0; z < y; z++) {
input[z] = (unsigned char)(z & 255);
}
len = sizeof(output);
if ((err = omac_memory(x, key, kl, input, y, output, &len)) != CRYPT_OK) {
printf("Error omacing: %s\n", error_to_string(err));
exit(EXIT_FAILURE);
}
fprintf(out, "%3d: ", y);
for (z = 0; z <(int)len; z++) {
fprintf(out, "%02X", output[z]);
}
fprintf(out, "\n");

/* forward the key */
for (z = 0; z < kl; z++) {
key[z] = output[z % len];
}
}
fprintf(out, "\n");
}
fclose(out);
#endif
}

void pmac_gen(void)
{
#ifdef LTC_PMAC
unsigned char key[MAXBLOCKSIZE], output[MAXBLOCKSIZE], input[MAXBLOCKSIZE*2+2];
int err, x, y, z, kl;
FILE *out;
unsigned long len;

out = fopen("pmac_tv.txt", "w");

fprintf(out,
"PMAC Tests. In these tests messages of N bytes long (00,01,02,...,NN-1) are PMAC'ed. The initial key is\n"
"of the same format (length specified per cipher). The PMAC key in step N+1 is the PMAC output of\n"
"step N (repeated as required to fill the array).\n\n");

for (x = 0; cipher_descriptor[x].name != NULL; x++) {
kl = cipher_descriptor[x].block_length;

/* skip ciphers which do not have 64 or 128 bit block sizes */
if (kl != 8 && kl != 16) continue;

if (cipher_descriptor[x].keysize(&kl) != CRYPT_OK) {
kl = cipher_descriptor[x].max_key_length;
}
fprintf(out, "PMAC-%s (%d byte key)\n", cipher_descriptor[x].name, kl);

/* initial key/block */