Giter Club home page Giter Club logo

libtom / libtomcrypt Goto Github PK

View Code? Open in Web Editor NEW
1.5K 111.0 449.0 22.31 MB

LibTomCrypt is a fairly comprehensive, modular and portable cryptographic toolkit that provides developers with a vast array of well known published block ciphers, one-way hash functions, chaining modes, pseudo-random number generators, public key cryptography and a plethora of other routines.

Home Page: https://www.libtom.net

License: Other

Shell 0.35% C 97.63% Python 0.12% Perl 0.36% Makefile 0.67% Java 0.19% CMake 0.67%
libtomcrypt cryptography c encryption

libtomcrypt's Introduction

libtomcrypt

Previously the git repository contained doc/crypt.pdf for detailed documentation. This was changed and the file is now only available from the tarball of the appropriate version or from the page https://github.com/libtom/libtomcrypt/releases .

Project Status

Travis CI

master: Build Status Coverage Status

develop: Build Status Coverage Status

AppVeyor

master: Build status

develop: Build status

Coverity

Coverity Scan Build Status

ABI Laboratory

API/ABI changes: check here

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.

If you have something bigger to submit, feel free to contact us beforehand. Then we can give you write access to this repo, so you can open your PR based on this repo and we can easier follow the rebase-before-merge approach we're using (or even do the rebase ourself).

Reviews

We're using Pull Request reviews to make sure that the code is in line with the existing code base.

Please have a look here to get an idea of the approach.

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)
GMP_DESC enable gmp as MPI provider *1
LTM_DESC enable libtommath as MPI provider *1
TFM_DESC enable tomsfastmath 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 makefiles provided. Please choose the one that fits best for you.

makefile use-case
makefile builds a static library (GNU Make required)
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 makefiles 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, but with support for all hash-algorithms included in the library *4
ltcrypt builds the ltcrypt binary, implementing something similar to 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 *4 *5
test builds the test binary, which runs all algorithm self-tests + some extended tests *4
timing builds the timing binary, which can be used to measure timings for algorithms and modes *4
bins builds hashsum *4
all_test builds test, hashsum, ltcrypt, small, tv_gen, sizes & constants *4
docs builds the developer documentation doc/crypt.pdf
install installs the library and header files *7 *8
install_bins installs the binaries created by the bins target *7 *8
install_docs installs the documentation created by the docs target *7 *8
install_test installs the test-app created by the test target *7 *8
install_all installs everything (i.e. library, bins, docs and test) *8
uninstall uninstalls the library and header files

*4 also builds library

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

*7 also builds the necessary artifact(s) before installing it

*8 also have a look at the 'Installation' section of this file

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

Installation

There exist several install make-targets which are described in the table above.

These targets support the standard ways (c.f. [GNU], [FreeBSD]) to modify the installation path via the following set of variables:

DESTDIR
PREFIX
LIBPATH
INCPATH
DATAPATH
BINPATH

The entire set of the variables is only supported in makefile, makefile.shared and makefile.unix.

In case you have to use one of the other makefiles, check in the file which variables are supported.

Examples

You want to install the static library to the default paths

make install

You want to install the shared library to a special path and use it from this path

make -f makefile.shared PREFIX=/opt/special/path

Have a look at the developer documentation, [GNU] or [FreeBSD] to get a detailed explanation of all the variables.

CMake support

The project provides support for the CMake build system.

git clone https://github.com/libtom/libtomcrypt.git
mkdir -p libtomcrypt/build
cd libtomcrypt/build
cmake ..
make -j$(nproc)

More details around building with CMake can be found in the developer documentation.

libtomcrypt's People

Contributors

apjanke avatar assarbad avatar atomicmooseca avatar buggywhip avatar ccbrown avatar cneveux avatar compnerd avatar diamondo25 avatar fperrad avatar jonathanherzog avatar karel-m avatar ksherlock avatar mudzot avatar pattop avatar pghmcfc avatar ppelleti avatar rmw42 avatar rswindell avatar ryancdotorg avatar sebastianv89 avatar sjaeckel avatar souajih avatar stapelberg avatar timgates42 avatar ulikoehler avatar ulikos avatar werew avatar ycaibb avatar yoshizaki-sni avatar zeromus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

libtomcrypt's Issues

compiling the demos encrypt.c

I cant compile the demos. I was able to get test.c to work, with some modifications of the makefile
EXTRALIBS="-ltfm"
CFLAGS +=-DTFM_DESC -DUSE_TFM

but I can not compile encrypt.c.

Can somebody give me a hint?

Thanks, and sorry if this is not the right way to ask.

DER should check EOL

der_decode_sequence_ex currently does a break, when it sees a LTC_ASN1_EOL.
But shouldn't it check if the input data is really at its end?

I came to this over dsa_verify_hash. This function accepts signatures that are too long.
If you are using documents with inline signatures the signature has to be stripped out
before calculating the hash. But if the signature is not stripped out while processing the file means that it is possible to modify the file content by appending to the signature.

Testcase might look like this:

#include <tomcrypt.h>

int main( int, char** )
{
  unsigned char buf[10];
  unsigned long buflen = sizeof(buf);
  int b = 1;
  der_encode_sequence_multi( buf, &buflen,
                             LTC_ASN1_BOOLEAN, 1UL, &b,
                             LTC_ASN1_EOL, 0UL, NULL );
  buf[buflen] = 'A';
  buflen += 1;
  int res = der_decode_sequence_multi( buf, buflen,
                                       LTC_ASN1_BOOLEAN, 1UL, &b,
                                       LTC_ASN1_EOL, 0UL, NULL );
  return res == CRYPT_OK ? 1 : 0;
}

Compile error if LTC_DER is defined but not LTC_RSA

Defining LTC_DER but not LTC_RSA will lead to this compile error:

src/pk/asn1/der/sequence/der_decode_subject_public_key_info.c: In function 'der_decode_subject_public_key_info':
src/pk/asn1/der/sequence/der_decode_subject_public_key_info.c:57:24: error: 'MAX_RSA_SIZE' undeclared (first use in this function)
tmpbuf = XCALLOC(1, MAX_RSA_SIZE*8);

Xcode4, libtomcrypt, LLVM, asm (unknown version of libtomcrypt)

Good insert time zone here everyone. I represent the StepMania 5/StepMania sm-ssc group from Google Code, and I am trying to work on bringing our project up to date for Xcode 4 on the Mac OS X side. Our project uses libtommath and libtomcrypt. Unfortunately, I do not know what version it is, which makes this issue a little hard to figure out.

The old environment we used, Xcode 3, used GCC 4.0 for historical reasons. With the move to Xcode 4, we wish to take advantage of a faster, better compiler: specifically, LLVM 2.0 (also known as Clang). Unfortunately, that better, faster compiler is not working due to this one small issue.

In tomcrypt_macros.h, there are two sets of ROLc and RORc static inline functions that both contain asm code. The core part of one of them is as follows:

static inline __attribute__((always_inline)) unsigned ROLc(unsigned word, const int i)
{
   asm ("roll %2,%0"
      :"=r" (word)
      :"0" (word),"I" (i));
   return word;
}

The compiler complains on aes.c, md5.c, and sha1.c of this message:

fatal error: error in backend: Invalid operand for inline asm constraint 'I'!

That function, and three others just like it, are the only occasions where there is the 'I' constraint.

If we try to use GCC 4.2 for libtomcrypt and Clang for the rest of our libraries (including libtommath), this eventually comes up on linking.

Ld ../sm-ssc.app/Contents/MacOS/sm-ssc normal i386
    cd /Users/wolfman2000/Repositories/sm-ssc/Xcode
    setenv MACOSX_DEPLOYMENT_TARGET 10.5
    /Developer/usr/bin/clang++ -arch i386 -isysroot /Developer/SDKs/MacOSX10.5.sdk
 -L/Users/wolfman2000/Repositories/sm-ssc/Xcode/..
 -L/Users/wolfman2000/Repositories/sm-ssc/Xcode/build/Debug
 -L/Users/wolfman2000/Repositories/sm-ssc/Xcode/Libraries
 -L/Users/wolfman2000/Repositories/sm-ssc/Xcode/../extern/mad-0.15.1b/msvc++/Release
 -F/Users/wolfman2000/Repositories/sm-ssc/Xcode/..
 -filelist /Users/wolfman2000/Repositories/sm-ssc/Xcode/build/stepmania_xcode4.build/Debug/stepmania.build/Objects-normal/i386/sm-ssc.LinkFileList
 -mmacosx-version-min=10.5 -dead_strip -no_dead_strip_inits_and_terms
 -framework Cocoa -framework Carbon -framework IOKit
 -framework QuickTime -framework OpenGL -framework CoreFoundation
 -framework AudioToolbox -framework AudioUnit -framework CoreAudio
 -framework vecLib -ljpeg_link -logg_link -ltheora_link -lvorbis_link
 -llua-5.1 -ltomcrypt -ltommath -lz_link -lffmpeg_link -lmad-sm5
 -lpng-1.5.1sm0.1 -lglew -lpcre -o /Users/wolfman2000/Repositories/sm-ssc/Xcode/../sm-ssc.app/Contents/MacOS/sm-ssc

ld: illegal text reloc to 
__ZSt7find_ifIN9__gnu_cxx17__normal_iteratorIPN9StdString7CStdStrIcEESt6vectorIS4_SaIS4_EEEEPFbRKS4_EET_SE_SE_T0_St26random_access_iterator_tag from /Users/wolfman2000/Repositories/sm-ssc/Xcode/build/stepmania_xcode4.build
/Debug/stepmania.build/Objects-normal/i386/RageUtil.o in 
__ZSt7find_ifIN9__gnu_cxx17__normal_iteratorIPN9StdString7CStdStrIcEESt6vectorIS4_SaIS4_EEEEPFbRKS4_EET_SE_SE_T0_St26random_access_iterator_tag for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Command /Developer/usr/bin/clang++ failed with exit code 1

I admit I am at a loss as to how to properly solve this.

The code we use for libtomcrypt is included in our repository (Mercurial required). We haven't moved it to our externs yet, so it's located in src/libtomcrypt/src. The spcific branch that I am trying to make work is the XCode4 branch, but I believe any attempts at compiling libtomcrypt via Clang will fail, not just my end. If requested, I will upload just the libtomcrypt part at the location of your choice.

Jason "Wolfman2000" Felds

undefined behavior in anubis.c

The shift left by 24 at lines 934 and 1051 of anubis.c execute undefined behavior when the high bit of the byte loaded from the key array is set. In C99/C11 is it not permitted to shift a signed integer left in such a way that a 1 bit is moved into, out of, or through the sign bit. An easy fix would be to cast the unsigned char to unsigned int before shifting left by 24.

Conflict while using yarrow_start and find_cipher("aes")

#include <stdio.h>
#include <tomcrypt.h>
int main()
{
    int idx;
    prng_state prng;

    register_prng(&yarrow_desc);
    yarrow_start(&prng);

    register_cipher(&aes_desc);
    idx = find_cipher("aes");
    printf("idx=%d\n", idx);
    return 0;
}

This program will output idx = -1
if without yarrow_start() or
find_cipher() runs before yarrow_start() or
use other Cipher Descriptors,
it will be OK.
I think there must be a conflict between the yarrow_start and aes_desc, but I cannot find the reason.

My computer is Thinkpad T430u,
OS is Ubuntu14.04
tomcrypt version is 1.17

Thanks.

clang-analyzer clean?

Could stand to run clang over it and clean up the warnings. Most have to do with the fact that clang doesn't realize that crypt_argchk() never returns.

I think you should add the attribute to it e.g

__attribute__((noreturn));

Camellia from libtomcrypt fails with some test vectors from openssl

This is the failing test vector taken from openssl (openssl-1.0.1e/test/evptests.txt):

CAMELLIA-256-ECB
key=603DEB1015CA71BE2B73AEF0857D77811F352C073B6108D72D9810A30914DFF4
plaintext=F69F2445DF4F9B17AD2B417BE66C3710
ciphertext=7960109FB6DC42947FCFE59EA3C5EB6B

Interesting is that some of the other openssl's camellia test vectors pass.

But maybe I am just doing something wrong.

Karel

ecc_verify_hash_raw fails when not using Shamir method and provided hash is all zeros

The math for handling the ECC verify with a hash with null characters, such as {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} and hashlen = 20. This results in an invalid signature verification (v != r). This only happens if the traditional (non Shamir) method is used to calculate "u1_mG + u2_mQ = mG".

This happens when calling "ecc_verify_hash_raw" and not using Shamir method (ecc_mul2add == NULL) and provided hash is all zeros.

Has anyone seen this or have any idea how to resolve the math?

ltc_ecc_mul2add.c integer sign issue

I got the following compiler warning:

"src/ltc/pk/ecc/ltc_ecc_mul2add.c", line 137: warning #2068-D: integer
          conversion resulted in a change of sign
    for (x = -1;; ) {

The code in question:

043  unsigned       bitbufA, bitbufB, lenA, lenB, len, x, y, nA, nB, nibble;
...
136  /* for every byte of the multiplicands */
137  for (x = -1;; ) {
138     /* grab a nibble */
139     if (++nibble == 4) {
140        ++x; if (x == len) break;
141        bitbufA = tA[x];
142        bitbufB = tB[x];
143        nibble  = 0;
144     }

It seems that we are assigning -1 to unsigned integer.

I have not investigated yet what would be the best fix.

--Karel

kseed test vectors failing

My kseed test vectors appear to have spontaneously started failing.

Disclaimers:

  • I am embedding it into a Python module and haven't yet tested with the built in testing tools;
  • I am using a slightly older version of libtomcrypt (from before its transfer to GitHub).

What I do know:

  • I have not made any changes to LTC or my project since the tests were passing;
  • I checked out historical versions and they fail now as well;
  • Travis CI does not have a problem (the Python2.6 fail is my bad);
  • I have two machines on OS X 10.7.5 which both fail the test, and another on 10.6.8 which does not fail the test.

I intend to update to the latest version of LTC, and run the tests directly without embedding them into Python, but thought I might as well get the ball rolling in case somebody was experiencing the same issue.

DH primes are couple of bits longer

This is related to PR #111 but I think it is worth a separate issue.

As @lkinley noticed in another issue DCIT/perl-CryptX#4 DH primes p in dh_static.c are longer than one would expect - here is the summary:

DH-768 real bits:784
DH-1024 real bits:1036
DH-1280 real bits:1288
DH-1536 real bits:1540
DH-1792 real bits:1792
DH-2048 real bits:2072
DH-2560 real bits:2576
DH-3072 real bits:3080
DH-4096 real bits:4116

By real bits I mean bits without any leading zeroes.

Was there any reason in the past why p values were chosen that long?

DER: `der_decode_sequence_flexi` segfaults on malformed input

My apologies if I am misunderstanding how this should work, but it seems that der_decode_sequence_flexi segfaults on trivially malformed input.

test.c:

#include <string.h>
#include "tomcrypt.h"

int main(int argc, char **argv) {

    unsigned char *malformed = "malformed";
    unsigned long inlen = strlen(malformed);
    ltc_asn1_list *list = NULL;

    return der_decode_sequence_flexi(malformed, &inlen, &list);

}

GDB output:

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000020
der_sequence_free (in=<value temporarily unavailable, due to optimizations>) at src/pk/asn1/der/sequence/der_sequence_free.c:29
29     while (in->prev != NULL || in->parent != NULL) {

128-bit AES CTR mode - decryptes only first block

I am using OPTEE_OS TEE Internal API which uses libtomcrypt below it. I am wondering, what kind of errors could cause only the first block (16 bytes) to be decrypted correctly?

I am unfamiliar with block ciphers such as AES. So should I be focusing on the 128-bit key (maybe I passed it in wrong? Although in that case, how would I have been able to decrypt even the first 128 bits), IV?

P.S. I used libtomcrypt directly and it worked fine. I must have passed in something wrong to the API that uses libtomcrypt, just wondering if the features of this error is unique enough to narrow it down for me to see what went wrong.

Build failed on Windows

I'm trying to build using Visual Studio and I'm getting the following error:

Cannot open include file: 'tommath.h': No such file or directory.

This error is happening on ltm_desc.c file.

possible issue in ecc_ansi_x963_export

Hi,
gnutls had a bug on ECC X9.63 coding code that was originally based in libtomcrypt. The issue is described at [0]. I re-read libtomcrypt's implementation at:
https://github.com/libtom/libtomcrypt/blob/develop/src/pk/ecc/ecc_ansi_x963_export.c

and I'm not sure if it is vulnerable as it depends on other implicit assumptions of the library which I may not know well. If a certificate which contains x and y ECC parameters that exceed the size of the curve are somehow imported into an ecc_key structure, a stack overflow will occur in ecc_ansi_x963_export() at the mp_to_unsigned_bin() call.

A fix would be to check mp_unsigned_bin_size(key->pubkey.x), and mp_unsigned_bin_size(key->pubkey.y) to match numlen.

[0]. https://bugzilla.redhat.com/show_bug.cgi?id=1161443

release needed - soon

it's been 3 years since this tomcrypt fork exists, and afaik there hasn't been any release.

i fear that if the development continues at this pace, libtomcrypt will be rendered obsolete soon.

from the outside it looks dead, so new software will probably not be written against it anymore, and chances that security researchers test a library that's not been updated since 4 years are little.

so if you really want to keep this project alive, you better start merging patches into master and pushing out releases soon.

RSA decoding

I've generated the following informations on a PHP server with CRYPT_RSA(1024 bit), but I'm not able to decode it with libtomcrypt. Import of the Key seems to be work. The decoding of the "encoded message" fails with libtomcrypt. The "base64encode/decode" stuff has been done in my application. Can anyone help?

Key from PHP server (base64coded, PEM, DER):
-----BEGIN RSA PRIVATE KEY-----
MIICWAIBAAKBgI+swEE0lguXZSV2L6AZoDBxDzDO9UjB1uHjkIWa7y0BkYItM+dJ
V7kZzSb4mFIrdDdmg46AB8rzIziEDBu87EBuBGPbaCm/pQ0jTPUo3ALJBeKi9Pha
UviQ+FYOqablixuyztK1axmgB2K8gL5oNhwQUjOp3KUt98bzcvuB+9SbAgMBAAEC
gYAj8lfjuJF18voGhmxiBSdUF2Vyk8VA3+awe6w0EVCYFRVf2Ylr66i8Eh2HC5mo
rWCVX9u4coYAnBaK1FbnNbxx/ePEPwd8XzIyuGscdCcl6pLQD3wIcTvWPyD5pWJ2
BzLUVk1LpnS14tIvQqcR/BMu9kU9kUXEgALNTxamZ1GHyQJA083GwLqzrKWgmZON
hoB6c21nX1pUTkdAOTQtJyEaFA4HAfv07ujh29XOyMK7ta6oopuVj4iCfHVvaGJb
VU9JXQJAraehmpSNh4F6dG5nYVpUTUdBOjQtJyEaFA0HAPrz7efg2tPNxsC5s6ym
oJmTjIZ/eXNsZl9ZU0xFPzgyKyUeVwJAtoetFGUR+OSX/iIyIkrQvG75Wix/YSJ4
T5QOoZ0eW1Ana+dWExpxosGkvlFL8Wv++nu4rYTIZzfRdhTlfySgJQJAYFda4c6+
wknELSo/MpSRppn8hxUBY+8Kb8tWcmXHxNpbNixBwp2TqSoE+56YbGMF/9RYdGc7
wGnVFSDRPHyIWwJAI+hXXhs9T81ZafgmDzRRbDHBahKoRqo0ntdhNMWburdteyd+
X2ipaW9WkY1rxgHEoj71Qm0YoO+CIz3ZGHnfWg==
-----END RSA PRIVATE KEY-----

Message:
12345678901234567890123456789012345678901234567890123456789012345678901234567890

Encoded message on PHP server (base64coded):
T3m6OsqIjyHtN744T6CIZO/ZZ6jLKt/rJd8da86OlTyk4u0nmFBckpAq139a0M8CeakcFXCPADSo3EPrpWoq/XBCtayDFcW5KFLxHYuFD9SOiH/6LNHBF448G/5U+n1h//k0IY/JXqsPVstFDfeGy7Vrkz0vtK/30hzLuKJdH40=

Decoded message on PHP server:
12345678901234567890123456789012345678901234567890123456789012345678901234567890

Possible bug in ecc_sign_hash

ECDSA algorithm fails to crop input hash to key length in ecc_sign_hash_raw()

The docs says:
With ECC if you try to sign a hash that is bigger than your ECC key
you can run into problems. The math will still work, and in effect the
signature will still work. With ECC keys the strength of the signature
is limited by the size of the hash, or the size of they key, whichever is
smaller. For example, if you sign with SHA256 and an ECC-192 key,
you in effect have 96–bits of security.
The library will not warn you if you make this mistake, so it is
important to check yourself before using the signatures.

The "math" will not really work. Compare the signature when the input is cropped (as defined in the specs) - the r is the same (assuming k is the same), but s values will not be congruent modulo n. So the "math" will only work if the validation is also done using TomCrypt.

Thus the input length should be validated or the input should be cropped to the key size.

GMP_DESC

tomcrypt_math.h refers to GMP_DESC which has a number of other references throughout the project. tomcrypt_custom.h refers to GPM_DESC which has no other references and looks like a typo.

rsa_encrypt_key function on RSA keys of size 3072 and higher

Let me preface this with the fact that I've pulled my hair out for the past 3 days trying to find a solution for this.

The problem I face is that the the rsa_encrypt_key function returns CRYPT_ERROR half the time when using RSA keys of size (3072 / 8) or (4096 / 8). I have literally ripped the example code from the manual, changed the buffer sizes of pt2 and out to 4096 * 8, changed the key to (4096 / 8, 65537), and it still gives me this seemingly 50/50 chance to return CRYPT_OK.

I have even tried this on a statically generated random number, and looped the rsa_encrypt_key function on it at the rate of 5 times per second, and the result is still roughly 50/50, either 0 or 1. I am literally baffled by this. I suspect this is the result of pkcs_1_oaep_encode, which is called internally from rsa_encrypt_key, as when I simply use rsa_exptmod on a static random number, it gives a consistent result of 0.

What is strange is that all is good and well when the RSA key used is of size 2048 or lower, as was shown in the manual's example. However, the description for rsa_make_key clearly states that it should work for keys up to 512 bytes long, yet this does not seem to be the case.

mem_neq

mem_neq is a constant time comparison function, but it leaks information on the secret data that is being compared in the value that is returned.

MULTI2 decrypt is broken when using non default number of rounds

Decrypt function related to MULTI2 does not work correctly in the situation when the cipher is initialized with non standard number of rounds (default is 128). Decrypt works correctly only for number of rounds is multiple of 4 (or something like that).

See enclosed patch which works fine on my testsuite using rounds from 1 to 555

--- a/libtomcrypt-src/ciphers/multi2.c
+++ b/libtomcrypt-src/ciphers/multi2.c
@@ -94,8 +94,8 @@ static void encrypt(ulong32 *p, int N, ulong32 *uk)
 static void decrypt(ulong32 *p, int N, ulong32 *uk)
 {
    int n, t;
-   for (t = 4*((N&1)^1), n = N; ;  ) {
-      switch (n >= 4 ? 4 : 0) {
+   for (t = 4*(((N-1)>>2)&1), n = N; ;  ) {
+      switch (n<=4 ? n : ((n-1)%4)+1) {
          case 4: pi4(p, uk+t); --n;
          case 3: pi3(p, uk+t); --n;
          case 2: pi2(p, uk+t); --n;

der_decode_raw_bit_string.c redefinition of macro "setbit"

I have experienced the following compiler warning (on HP-UX@Itanium/IA64):

"src/ltc/pk/asn1/der/bit/der_decode_raw_bit_string.c", line 21: warning #2047-D: 
          incompatible redefinition of macro "setbit" (declared at line 426 of
          "/usr/include/sys/param.h")
  #define setbit(v, n)    (v=((unsigned char)(v) | (1U << (unsigned char)(n))))

Perhaps we should change it to ltcsetbit or something like this.

Feature request: Serpent

This library is really brilliant. I have made some speed tests against other common libraries and this one is really perfect. It would be really nice to implement the Serpent algorithm. After all, it's considered as maybe the safest one.

xcode valid compiler warning

libtomcrypt-1.17/src/pk/asn1/der/sequence/der_decode_sequence_ex.c:55:15: Variable 'blksize' is used uninitialized whenever 'if' condition is false

technically any value of in[x] > 129 would cause blksize to be uninitialized (skipping the if and the else if), and therefore the next line outside that if/else if
if (x + blksize > inlen) {
would have undefined results.

i'm not sure if values of in[x] > 129 are even possible in this code, but it would be good to clarify.

camellia.c const is meaningless on cast type

I have experienced the following compiler warning:

"src/ltc/ciphers/camellia.c", line 193: warning #2191-D: type qualifier is
          meaningless on cast type
     U = D ^ ROR(U, (const int)8);
                     ^

Why not just use: U = D ^ ROR(U, 8); ?

Importing Binary Private Key To RSA_KEY

I currently have all the parameters to an RSA key, but find it impossible to import them to the rsa_key parameter. For instance, in C# I simply do this:

        RSACryptoServiceProvider Key = new RSACryptoServiceProvider();
        RSAParameters parameters = new RSAParameters();
        reader.Seek(0x28C);
        parameters.Exponent = reader.ReadBytes(0x4);
        reader.Seek(0x8, SeekOrigin.Current);
        parameters.Modulus = Conversions.FlipBytesBy8(reader.ReadBytes(0x80));
        parameters.P = Conversions.FlipBytesBy8(reader.ReadBytes(0x40));
        parameters.Q = Conversions.FlipBytesBy8(reader.ReadBytes(0x40));
        parameters.DP = Conversions.FlipBytesBy8(reader.ReadBytes(0x40));
        parameters.DQ = Conversions.FlipBytesBy8(reader.ReadBytes(0x40));
        parameters.InverseQ = Conversions.FlipBytesBy8(reader.ReadBytes(0x40));
        parameters.D = new byte[0x80];
        Key.ImportParameters(parameters);

But in C, it's not possible to just set the void* parameters, since I'm assuming they use some sort of big integer type that I cannot find. I would like to some how change the data to whatever type of format rsa_import uses.

RSA public key decrypt failed

I just change the rsa_test.c:

len2 = sizeof(tmp);
DO(rsa_export(tmp, &len2, PK_PRIVATE, &key));
DO(rsa_import(tmp, len2, &pk));
len2 = sizeof(tmp);
DO(rsa_export(tmp, &len2, PK_PUBLIC, &key));
DO(rsa_import(tmp, len2, &sk));

encrypt use private key:
DO(rsa_encrypt_key(in, rsa_msgsize, out, &len, NULL, 0, &yarrow_prng, prng_idx, hash_idx, &pk));

decrypt use public key:
DO(rsa_decrypt_key(out, len, tmp, &len2, NULL, 0, hash_idx, &stat, &key));

then the test failed, and promot is: A private PK key is required.

does anyone help me ?

Attached: CMake build file

Hi

first of all I want to say: Thanks for that cool library. It is also very well documented :)

Since I'm a big fan of CMake, that makes building for different systems and with different compilers very easy, I created a CMakeLists.txt file.

Maybe someone else find this useful, that's why I just want to attach it to this text:
CMakeLists.txt

I have tested it with MSVC2015 (Windows 64bit), GCC 4.9 (Linux64) and Android NDK r10e. It builds libtomcrypt as static library. On windows it shows some linker warnings at linking stage, but I think this is not an issue (object files without external symbols).

There are a lot of compilers and systems out there, where this CMakeLists.txt has not been tested with, but I think it is at least a starting point for other users, that want to use libtomcrypt together with CMake.

Have a lot of fun with it :)
BR

Please create tag(s)

Do you mind creating a new tag so Homebrew can get the fixes that let it run on El Capitan? Just need a new tag created here on GitHub.

Error: operand size mismatch for `movq'

tomcrypt does not build on x32, as seen at:

http://buildd.debian-ports.org/status/fetch.php?pkg=libtomcrypt&arch=x32&ver=1.17-3.2&stamp=1361157947

libtool: compile: gcc -c -I./src/headers/ -Wall -Wsign-compare -W -Wshadow -DLTC_SOURCE -O3 -funroll-loops -fomit-frame-pointer -c src/encauth/gcm/gcm_gf_mult.c -fPIC -DPIC -o src/encauth/gcm/.libs/gcm_gf_mult.o
src/encauth/gcm/gcm_gf_mult.c: Assembler messages:
src/encauth/gcm/gcm_gf_mult.c:134: Error: operand size mismatch for movq' src/encauth/gcm/gcm_gf_mult.c:135: Error: incorrect register%eax' used with q' suffix src/encauth/gcm/gcm_gf_mult.c:134: Error: operand type mismatch formovq'
src/encauth/gcm/gcm_gf_mult.c:135: Error: incorrect register %r11d' used withq' suffix
src/encauth/gcm/gcm_gf_mult.c:198: Error: incorrect register %r9d' used withq' suffix
src/encauth/gcm/gcm_gf_mult.c:199: Error: operand type mismatch for movq' src/encauth/gcm/gcm_gf_mult.c:200: Error: incorrect register%r9d' used with q' suffix src/encauth/gcm/gcm_gf_mult.c:198: Error: incorrect register%edx' used with q' suffix src/encauth/gcm/gcm_gf_mult.c:199: Error: operand type mismatch formovq'
src/encauth/gcm/gcm_gf_mult.c:200: Error: incorrect register %edx' used withq' suffix
src/encauth/gcm/gcm_gf_mult.c:198: Error: incorrect register %edi' used withq' suffix
src/encauth/gcm/gcm_gf_mult.c:199: Error: operand type mismatch for movq' src/encauth/gcm/gcm_gf_mult.c:200: Error: incorrect register%edi' used with q' suffix src/encauth/gcm/gcm_gf_mult.c:198: Error: incorrect register%ecx' used with q' suffix src/encauth/gcm/gcm_gf_mult.c:199: Error: operand type mismatch formovq'
src/encauth/gcm/gcm_gf_mult.c:200: Error: incorrect register %ecx' used withq' suffix
make[1]: *** [src/encauth/gcm/gcm_gf_mult.o] Error 1
make[1]: Leaving directory `/build/buildd-libtomcrypt_1.17-3.2-x32-uQH4LL/libtomcrypt-1.17'

minor documentation error

The pdf doc on page 45 (using pdf pages numbers) the call to ccm_memory has the argument position of ct and pt backwards. If 'ct' is replaced by 'pt' and vice versa, the function will decrypt it. Otherwise, you will get garbage.

Build failed on OS X 10.10, 10.11

The last libtomcrypt release, 0.42.0, fails to build on OS X 10.10 Yosemite and OS X 10.11.

[~/tmp/libtom/libtomcrypt-1.17]
$ uname -a
Darwin spiffy-elcap.local 15.0.0 Darwin Kernel Version 15.0.0: Tue Sep 22 20:33:10 PDT 2015; root:xnu-3247.10.11.1.1~1/RELEASE_X86_64 x86_64
[~/tmp/libtom/libtomcrypt-1.17]
$ make
cc -c -I./testprof/ -I./src/headers/ -Wall -Wsign-compare -W -Wshadow -Wno-unused-parameter -DLTC_SOURCE -O3 -funroll-loops -fomit-frame-pointer -DENCRYPT_ONLY -c src/ciphers/aes/aes.c -o src/ciphers/aes/aes_enc.o
In file included from src/ciphers/aes/aes.c:33:
In file included from ./src/headers/tomcrypt.h:67:
./src/headers/tomcrypt_macros.h:269:24: error: constraint 'I' expects an integer constant expression
      :"0" (word),"I" (i));
                       ^
./src/headers/tomcrypt_macros.h:277:24: error: constraint 'I' expects an integer constant expression
      :"0" (word),"I" (i));
                       ^
./src/headers/tomcrypt_macros.h:368:24: error: constraint 'J' expects an integer constant expression
      :"0" (word),"J" (i));
                       ^
./src/headers/tomcrypt_macros.h:376:24: error: constraint 'J' expects an integer constant expression
      :"0" (word),"J" (i));
                       ^
4 errors generated.
make: *** [src/ciphers/aes/aes_enc.o] Error 1
[✘ ~/tmp/libtom/libtomcrypt-1.17]
$

It appears to be fixed in the development head: building from a clone of the GitHub repo succeeds on 10.11.

Encountered this with the Homebrew formula for libtomcrypt, which is currently failing on 10.10 and 10.11. Homebrew/legacy-homebrew#43906

Could we get a release to fix this?

Pi functions incorrect in ltc's Noekeon

I believe that libTomCrypt's implementation of Noekeon is incorrect. (There is only one test vector for Noekeon in LTC. Where did that test vector come from, and has LTC's Noekeon been tested for interoperation with any other implementation?)

According to the Noekeon spec (available at gro.noekeon.org), the Pi1 and Pi2 functions operate on a[1], a[2], and a[3]. (In the notation used by libTomCrypt, which uses scalar variables instead of an array, that would be b, c, and d.)

However, libTomCrypt's PI1 and PI2 operate on a, c, and d. (Which, in the array notation from the Noekeon paper, would be a[0], a[2], and a[3].)

I've done some testing, and libTomCrypt's Noekeon as it currently is does not match the result's of BouncyCastle's Noekeon. But, if I change LTC's Pi functions to match the Noekeon paper, then it does produce the same results as BouncyCastle.

some compiler do not like `static inline` functions in

In dh_static.h we have:

static inline void packet_store_header (unsigned char *dst, int section, int subsection)
...
static inline int packet_valid_header (unsigned char *src, int section, int subsection)

As I have mentioned in #88 these static inline declaration cannot be compiled with HP C/aC++ compiler at HP-UX.

Apart from that it also cannot be compiled with MS Visual Studio 2008

d:\git\libtomcrypt.fork\src\pk\dh\dh_static.h(72) : error C2054: expected '(' to follow 'inline'
d:\git\libtomcrypt.fork\src\pk\dh\dh_static.h(73) : error C2085: 'packet_store_header' : not in formal parameter list
d:\git\libtomcrypt.fork\src\pk\dh\dh_static.h(73) : error C2143: syntax error : missing ';' before '{'
d:\git\libtomcrypt.fork\src\pk\dh\dh_static.h(86) : error C2054: expected '(' to follow 'inline'
d:\git\libtomcrypt.fork\src\pk\dh\dh_static.h(87) : error C2085: 'packet_valid_header' : not in formal parameter list
d:\git\libtomcrypt.fork\src\pk\dh\dh_static.h(87) : error C2143: syntax error : missing ';' before '{'

I am not sure whether performance gains of static inline are so significant.

ECC public key validation stucks in ltc_ecc_map

ECDSA ceriticom[http://cs.ucsb.edu/~koc/ccs130h/notes/ecdsa-cert.pdf] reference
says ECDSA public key (or private key) has to be validated by checking list below

Q : public key to validate
n: order of domain parameter
O: point at infinity

  1. Check that Q ≠ O
  2. ..
  3. ..
  4. Check that nQ = O

so I was calculate nQ using ltc_ecc_mulmod(n, Q, result, modulus, 1)
but it hangs.
here is the code(looked up ecc_test() codes)

   void     *modulus, *order;
   ecc_point  *Q, *Result;
   int i, err, primality;    
       /* ECC-224 */
 i=4;
       /* read modulus */
if ((err = mp_read_radix(modulus, (char *)ltc_ecc_sets[i].prime, 16)) != CRYPT_OK)   { goto done; }
       /* read order */
if ((err = mp_read_radix(order, (char *)ltc_ecc_sets[i].order, 16)) != CRYPT_OK)     { goto done; }

       /* read Q */
       if ((err = mp_read_radix(Q->x, (char *)"EA3745501BBC6A70BBFDD8AEEDB18CF5073C6DC9AA7CBB5915170D60", 16)) != C
RYPT_OK)         { goto done; }       
       if ((err = mp_read_radix(Q->y, (char *)"6C9CB8E68AABFEC989CAC5E2326E0448B7E69C3E56039BA21A44FDAC", 16)) != C
RYPT_OK)         { goto done; }       
       mp_set(Q->z, 1);

       /* calculate nQ */
       if ((err = ltc_mp.ecc_ptmul(order, Q, Result, modulus, 1)) != CRYPT_OK)                  { goto done; }

used curve is(from src/pk/ecc/ecc.c)
LTC_ECC224
P="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"
B="B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"
n="FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"
Gx="B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"
Gy="BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"

used public key parameter is (It is correct key !! has to be validate)
Qx = EA3745501BBC6A70BBFDD8AEEDB18CF5073C6DC9AA7CBB5915170D60
Qy = 6C9CB8E68AABFEC989CAC5E2326E0448B7E69C3E56039BA21A44FDAC

I compiled libtomcrypt using libtommath library(both are static compiled).
build flags was
CFLAGS="-DLTM_DESC -I ../libtommath/" EXTRALIBS="-L. -ltommath" make
CFLAGS="-DLTM_DESC -I ../libtommath/" EXTRALIBS="-L. -ltommath" make test

Module seems to be stuck at ltc_ecc_map. but I don't know why.
Help me if you got anything clue.

and I got another question
Is there anything method that ECC point is at infinity?

my thinking was if Qz==0 then point is at infinity (look at the openssl is_point_at_infinity).
I want to know whether it corrects.

thanks.

ECC improvements

Hi,

I would like to propose a set of changes to ECC part of libtomcrypt. I have already implemented all proposed changes in my something-like-fork of libtomcrypt which is available https://github.com/DCIT/perl-CryptX/tree/master/src/ltc

1/ Support for curves y^2 = x^3 + a*x + b

Currently libtomcrypt supports only y^2 = x^3 - 3*x + b.

Support for general case required changes to ltc_ecc_projective_dbl_point(), ltc_ecc_projective_add_point() and ltc_ecc_is_point() as you can see in my repo (please note that I have moved is_point function into a separate file ltc_ecc_is_point.c). Extending ltc_ecc_set_type + other small changes were also necessary.

2/ Support for compressed public keys

Already existing function ecc_ansi_x963_export() allows you to export EC public key in a format defined by X9.63 but only supports 'uncompressed' form.

I have added support for exporting compressed EC public keys (which was easy) as well as for import. The import part was a bit tricky as it was necessary to add mp_sqrtmod_prime to libtommath.

As I wanted to keep old interface I have created new functions:

NOTE: The new functions ecc_import_raw() / ecc_export_raw() also support import/export of private key (raw octects)

My implementation of mp_sqrtmod_prime (based on Tonelli–Shanks algorithm) is available here:

3/ DER format compatible with openssl

To support importing/exporting keys in DER format compatible with openssl we need to support the following:

Again, I wanted to keep old interface so I have created new functions:

A small trouble was with adding support for OPTIONAL items in ASN.1 sequences. A big trouble was with private keys which uses ASN.1 context specific tags which are not supported by current libtomcrypt. This part is more a hack/workaround than a systematic support but fully follow ASN.1 specification is not easy.

See the changes at https://github.com/DCIT/perl-CryptX/commits/master/src/ltc/pk/asn1

As my changes to libtomcrypt + libtommath are are quite huge I am not sending them as a pull request. However if you find it worth to be included in upstream libtomcrypt I can fork develop branch a port my changes (I mean those you will agree with) into it.

Any feedback welcome.

Karel

ccm_memory

About the libtom implementation of authenticated encryption mode CCM:

According to the NIST specification of CCM, the authentication tag is part of the ciphertext. In order to decrypt, this full ciphertext must be decrypted, resulting in a "plaintext" tag. The tag must then be recomputed upon the plaintext and compared with the decrypted value. However, upon decryption in the libtom implementation, the ciphertext is decrypted, and a tag is computed upon the header and (decrypted) plaintext. This is then re-encrypted, so that the caller of the function must compare the resulting (encryped) tag with the received (encrypted) tag.

The NIST specification specifies that "only the error message INVALID is returned" when the decryption-verification fails. In that case "the payload P and the MAC T shall not be revealed" and that "the implementation shall ensure that an unauthorized party cannot distinguish whether the error message results from [invalid message format] or from [authentication failure], for example, from the timing of the error message."

There are several fixes (I think), for example removing the tag parameter from the function and let it be part of the ciphertext parameter (as it should be according to the specification). Verification of authentication can then be done inside the function ccm_memory. Of course, this would break compatibility with the existing implementation, so I'm not sure if that is what you want.

Tests for macros

Tests for the LOAD, STORE and Rotate macros shall be written.
e.g. Codewarrior Compiler for Freescale Coldfire doesn't handle correctly the 64bit store operations.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.