diff --git a/Configure b/Configure index beab5dea..44cccee4 100755 --- a/Configure +++ b/Configure @@ -312,7 +312,8 @@ $config{sdirs} = [ "evp", "asn1", "pem", "x509", "x509v3", "conf", "txt_db", "pkcs7", "pkcs12", "comp", "ocsp", "ui", "cms", "ts", "srp", "cmac", "ct", "async", "kdf", "sm3", "sms4", "kdf2", "ecies", "ffx", "sm2", "paillier", "cpk", "otp", "gmapi", "ec2", - "bfibe", "bb1ibe", "sm9", "saf", "sdf", "skf", "sof", "zuc" + "bfibe", "bb1ibe", "sm9", "saf", "sdf", "skf", "sof", "zuc", + "serpent", "speck" ]; # Known TLS and DTLS protocols @@ -406,8 +407,34 @@ my @disablables = ( "weak-ssl-ciphers", "zlib", "zlib-dynamic", - "sm3", "sms4", "kdf2", "ecies", "ffx", "sm2", "paillier", "cpk", "otp", "gmapi", "ec2", - "bfibe", "bb1ibe", "sm9", "saf", "sdf", "skf", "sof", "zuc" + "sm3", + "sms4", + "kdf2", + "ecies", + "ffx", + "sm2", + "paillier", + "cpk", + "otp", + "gmapi", + "ec2", + "bfibe", + "bb1ibe", + "sm9", + "saf", + "sdf", + "skf", + "sof", + "zuc", + "aes", + "sha", + "md5", + "rsa", + "pem", + "pkcs7", + "pkcs12", + "serpent", + "speck", ); foreach my $proto ((@tls, @dtls)) { @@ -444,6 +471,14 @@ our %disabled = ( # "what" => "comment" "weak-ssl-ciphers" => "default", "zlib" => "default", "zlib-dynamic" => "default", + "zuc" => "default", + "sm9" => "default", + "bfibe" => "default", + "bb1ibe" => "default", + "saf" => "default", + "sof" => "default", + "serpent" => "default", + # "speck" => "default", ); # Note: => pair form used for aesthetics, not to truly make a hash table diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..c205274a --- /dev/null +++ b/LICENSE @@ -0,0 +1,113 @@ + + LICENSE ISSUES + ============== + + The GmSSL toolkit stays under a double license, i.e. both the conditions of + the GmSSL License and the original OpenSSL license apply to the toolkit. + See below for the actual license texts. + +/* ==================================================================== + * Copyright (c) 2014 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + + OpenSSL License + --------------- + +/* ==================================================================== + * Copyright (c) 1998-2017 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ diff --git a/README.md b/README.md index 748ab87b..84c7d6c5 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ GmSSL是一个开源的密码工具箱,支持SM2/SM3/SM4/SM9等国密(国家 ```sh $ gmssl pkey -pubout -in signkey.pem -out vrfykey.pem - $ gmssl pkeyutl -verify -pkeyopt ec_sign_algor:sm2 -inkey vrfykey.pem \ + $ gmssl pkeyutl -verify -pkeyopt ec_sign_algor:sm2 -pubin -inkey vrfykey.pem \ -in -sigfile .sig ``` diff --git a/crypto/asn1/asn1_err.c b/crypto/asn1/asn1_err.c index 97c3dec9..fee67563 100644 --- a/crypto/asn1/asn1_err.c +++ b/crypto/asn1/asn1_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy @@ -95,6 +95,7 @@ static ERR_STRING_DATA ASN1_str_functs[] = { {ERR_FUNC(ASN1_F_I2D_ASN1_BIO_STREAM), "i2d_ASN1_bio_stream"}, {ERR_FUNC(ASN1_F_I2D_DSA_PUBKEY), "i2d_DSA_PUBKEY"}, {ERR_FUNC(ASN1_F_I2D_EC_PUBKEY), "i2d_EC_PUBKEY"}, + {ERR_FUNC(ASN1_F_I2D_PAILLIER_PUBKEY), "i2d_PAILLIER_PUBKEY"}, {ERR_FUNC(ASN1_F_I2D_PRIVATEKEY), "i2d_PrivateKey"}, {ERR_FUNC(ASN1_F_I2D_PUBLICKEY), "i2d_PublicKey"}, {ERR_FUNC(ASN1_F_I2D_RSA_PUBKEY), "i2d_RSA_PUBKEY"}, diff --git a/crypto/evp/c_allc.c b/crypto/evp/c_allc.c index ffef9c0c..2e8ff3c0 100644 --- a/crypto/evp/c_allc.c +++ b/crypto/evp/c_allc.c @@ -123,6 +123,7 @@ void openssl_add_all_ciphers_int(void) EVP_add_cipher_alias(SN_rc5_cbc, "RC5"); #endif +#ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_ecb()); EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_128_cfb()); @@ -131,9 +132,9 @@ void openssl_add_all_ciphers_int(void) EVP_add_cipher(EVP_aes_128_ofb()); EVP_add_cipher(EVP_aes_128_ctr()); EVP_add_cipher(EVP_aes_128_gcm()); -#ifndef OPENSSL_NO_OCB +# ifndef OPENSSL_NO_OCB EVP_add_cipher(EVP_aes_128_ocb()); -#endif +# endif EVP_add_cipher(EVP_aes_128_xts()); EVP_add_cipher(EVP_aes_128_ccm()); EVP_add_cipher(EVP_aes_128_wrap()); @@ -149,9 +150,9 @@ void openssl_add_all_ciphers_int(void) EVP_add_cipher(EVP_aes_192_ofb()); EVP_add_cipher(EVP_aes_192_ctr()); EVP_add_cipher(EVP_aes_192_gcm()); -#ifndef OPENSSL_NO_OCB +# ifndef OPENSSL_NO_OCB EVP_add_cipher(EVP_aes_192_ocb()); -#endif +# endif EVP_add_cipher(EVP_aes_192_ccm()); EVP_add_cipher(EVP_aes_192_wrap()); EVP_add_cipher_alias(SN_id_aes192_wrap, "aes192-wrap"); @@ -166,9 +167,9 @@ void openssl_add_all_ciphers_int(void) EVP_add_cipher(EVP_aes_256_ofb()); EVP_add_cipher(EVP_aes_256_ctr()); EVP_add_cipher(EVP_aes_256_gcm()); -#ifndef OPENSSL_NO_OCB +# ifndef OPENSSL_NO_OCB EVP_add_cipher(EVP_aes_256_ocb()); -#endif +# endif EVP_add_cipher(EVP_aes_256_xts()); EVP_add_cipher(EVP_aes_256_ccm()); EVP_add_cipher(EVP_aes_256_wrap()); @@ -180,6 +181,7 @@ void openssl_add_all_ciphers_int(void) EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1()); EVP_add_cipher(EVP_aes_128_cbc_hmac_sha256()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha256()); +#endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_ecb()); @@ -216,6 +218,7 @@ void openssl_add_all_ciphers_int(void) # ifndef OPENSSL_NO_POLY1305 EVP_add_cipher(EVP_chacha20_poly1305()); # endif +#endif #ifndef OPENSSL_NO_SMS4 EVP_add_cipher(EVP_sms4_ecb()); @@ -236,6 +239,4 @@ void openssl_add_all_ciphers_int(void) EVP_add_cipher_alias(SN_sms4_cbc,"SMS4"); EVP_add_cipher_alias(SN_sms4_cbc,"sms4"); #endif - -#endif } diff --git a/crypto/evp/c_alld.c b/crypto/evp/c_alld.c index a66dae25..5430fb39 100644 --- a/crypto/evp/c_alld.c +++ b/crypto/evp/c_alld.c @@ -24,9 +24,11 @@ void openssl_add_all_digests_int(void) EVP_add_digest_alias(SN_md5, "ssl3-md5"); EVP_add_digest(EVP_md5_sha1()); #endif +#ifndef OPENSSL_NO_SHA1 EVP_add_digest(EVP_sha1()); EVP_add_digest_alias(SN_sha1, "ssl3-sha1"); EVP_add_digest_alias(SN_sha1WithRSAEncryption, SN_sha1WithRSA); +#endif #if !defined(OPENSSL_NO_MDC2) && !defined(OPENSSL_NO_DES) EVP_add_digest(EVP_mdc2()); #endif @@ -35,10 +37,12 @@ void openssl_add_all_digests_int(void) EVP_add_digest_alias(SN_ripemd160, "ripemd"); EVP_add_digest_alias(SN_ripemd160, "rmd160"); #endif +#ifndef OPENSSL_NO_SHA1 EVP_add_digest(EVP_sha224()); EVP_add_digest(EVP_sha256()); EVP_add_digest(EVP_sha384()); EVP_add_digest(EVP_sha512()); +#endif #ifndef OPENSSL_NO_WHIRLPOOL EVP_add_digest(EVP_whirlpool()); #endif diff --git a/crypto/evp/e_aes.c b/crypto/evp/e_aes.c index 619c6f85..482b26cb 100644 --- a/crypto/evp/e_aes.c +++ b/crypto/evp/e_aes.c @@ -8,6 +8,9 @@ */ #include +#ifdef OPENSSL_NO_AES +NON_EMPTY_TRANSLATION_UNIT +#else #include #include #include @@ -2698,3 +2701,4 @@ BLOCK_CIPHER_custom(NID_aes, 192, 16, 12, ocb, OCB, BLOCK_CIPHER_custom(NID_aes, 256, 16, 12, ocb, OCB, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) #endif /* OPENSSL_NO_OCB */ +#endif diff --git a/crypto/evp/e_aes_cbc_hmac_sha1.c b/crypto/evp/e_aes_cbc_hmac_sha1.c index 52c7c744..407b2b54 100644 --- a/crypto/evp/e_aes_cbc_hmac_sha1.c +++ b/crypto/evp/e_aes_cbc_hmac_sha1.c @@ -8,6 +8,9 @@ */ #include +#ifdef OPENSSL_NO_AES +NON_EMPTY_TRANSLATION_UNIT +#else #include #include @@ -955,3 +958,4 @@ const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void) return NULL; } #endif +#endif diff --git a/crypto/evp/e_aes_cbc_hmac_sha256.c b/crypto/evp/e_aes_cbc_hmac_sha256.c index 5a92e0b8..6d814131 100644 --- a/crypto/evp/e_aes_cbc_hmac_sha256.c +++ b/crypto/evp/e_aes_cbc_hmac_sha256.c @@ -8,6 +8,9 @@ */ #include +#ifdef OPENSSL_NO_AES +NON_EMPTY_TRANSLATION_UNIT +#else #include #include @@ -937,3 +940,4 @@ const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void) return NULL; } #endif +#endif diff --git a/crypto/evp/evp_err.c b/crypto/evp/evp_err.c index 639ad522..a7ab3483 100644 --- a/crypto/evp/evp_err.c +++ b/crypto/evp/evp_err.c @@ -68,6 +68,7 @@ static ERR_STRING_DATA EVP_str_functs[] = { {ERR_FUNC(EVP_F_EVP_PKEY_GET0_DSA), "EVP_PKEY_get0_DSA"}, {ERR_FUNC(EVP_F_EVP_PKEY_GET0_EC_KEY), "EVP_PKEY_get0_EC_KEY"}, {ERR_FUNC(EVP_F_EVP_PKEY_GET0_HMAC), "EVP_PKEY_get0_hmac"}, + {ERR_FUNC(EVP_F_EVP_PKEY_GET0_PAILLIER), "EVP_PKEY_get0_PAILLIER"}, {ERR_FUNC(EVP_F_EVP_PKEY_GET0_RSA), "EVP_PKEY_get0_RSA"}, {ERR_FUNC(EVP_F_EVP_PKEY_KEYGEN), "EVP_PKEY_keygen"}, {ERR_FUNC(EVP_F_EVP_PKEY_KEYGEN_INIT), "EVP_PKEY_keygen_init"}, @@ -118,6 +119,7 @@ static ERR_STRING_DATA EVP_str_reasons[] = { {ERR_REASON(EVP_R_EXPECTING_A_DH_KEY), "expecting a dh key"}, {ERR_REASON(EVP_R_EXPECTING_A_DSA_KEY), "expecting a dsa key"}, {ERR_REASON(EVP_R_EXPECTING_A_EC_KEY), "expecting a ec key"}, + {ERR_REASON(EVP_R_EXPECTING_A_PAILLIER), "expecting a paillier"}, {ERR_REASON(EVP_R_FIPS_MODE_NOT_SUPPORTED), "fips mode not supported"}, {ERR_REASON(EVP_R_ILLEGAL_SCRYPT_PARAMETERS), "illegal scrypt parameters"}, diff --git a/crypto/evp/m_sha1.c b/crypto/evp/m_sha1.c index 8f30077a..df8e5aad 100644 --- a/crypto/evp/m_sha1.c +++ b/crypto/evp/m_sha1.c @@ -10,6 +10,8 @@ #include #include "internal/cryptlib.h" +#ifndef OPENSSL_NO_SHA1 + #include #include #include @@ -231,3 +233,4 @@ const EVP_MD *EVP_sha512(void) { return (&sha512_md); } +#endif diff --git a/crypto/evp/p_lib.c b/crypto/evp/p_lib.c index 98286205..9b5d2947 100644 --- a/crypto/evp/p_lib.c +++ b/crypto/evp/p_lib.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include "internal/asn1_int.h" @@ -331,6 +332,34 @@ EC_KEY *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey) } #endif +#ifndef OPENSSL_NO_PAILLIER + +int EVP_PKEY_set1_PAILLIER(EVP_PKEY *pkey, PAILLIER *key) +{ + int ret = EVP_PKEY_assign_PAILLIER(pkey, key); + if (ret) + PAILLIER_up_ref(key); + return ret; +} + +PAILLIER *EVP_PKEY_get0_PAILLIER(EVP_PKEY *pkey) +{ + if (pkey->type != EVP_PKEY_PAILLIER) { + EVPerr(EVP_F_EVP_PKEY_GET0_PAILLIER, EVP_R_EXPECTING_A_PAILLIER); + return NULL; + } + return pkey->pkey.paillier; +} + +PAILLIER *EVP_PKEY_get1_PAILLIER(EVP_PKEY *pkey) +{ + PAILLIER *ret = EVP_PKEY_get0_PAILLIER(pkey); + if (ret != NULL) + PAILLIER_up_ref(ret); + return ret; +} +#endif + #ifndef OPENSSL_NO_DH int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *key) diff --git a/crypto/include/internal/evp_int.h b/crypto/include/internal/evp_int.h index c9ef5827..fd4c2695 100644 --- a/crypto/include/internal/evp_int.h +++ b/crypto/include/internal/evp_int.h @@ -369,6 +369,9 @@ struct evp_pkey_st { # endif # ifndef OPENSSL_NO_EC struct ec_key_st *ec; /* ECC */ +# endif +# ifndef OPENSSL_NO_PAILLIER + struct paillier_st *paillier; # endif } pkey; int save_parameters; diff --git a/crypto/paillier/pai_asn1.c b/crypto/paillier/pai_asn1.c index 3e5bcc6f..650ee866 100644 --- a/crypto/paillier/pai_asn1.c +++ b/crypto/paillier/pai_asn1.c @@ -70,15 +70,15 @@ static int paillier_cb(int operation, ASN1_VALUE **pval, return 1; } -ASN1_SEQUENCE_cb(PAILLIER_PRIVATE_KEY, paillier_cb) = { +ASN1_SEQUENCE_cb(PaillierPrivateKey, paillier_cb) = { ASN1_SIMPLE(PAILLIER, n, BIGNUM), ASN1_SIMPLE(PAILLIER, lambda, BIGNUM), ASN1_SIMPLE(PAILLIER, x, BIGNUM) -} ASN1_SEQUENCE_END_cb(PAILLIER, PAILLIER_PRIVATE_KEY) +} ASN1_SEQUENCE_END_cb(PAILLIER, PaillierPrivateKey) -ASN1_SEQUENCE_cb(PAILLIER_PUBLIC_KEY, paillier_cb) = { +ASN1_SEQUENCE_cb(PaillierPublicKey, paillier_cb) = { ASN1_SIMPLE(PAILLIER, n, BIGNUM) -} ASN1_SEQUENCE_END_cb(PAILLIER, PAILLIER_PUBLIC_KEY) +} ASN1_SEQUENCE_END_cb(PAILLIER, PaillierPublicKey) -IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(PAILLIER, PAILLIER_PRIVATE_KEY, PAILLIER_PRIVATE_KEY) -IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(PAILLIER, PAILLIER_PUBLIC_KEY, PAILLIER_PUBLIC_KEY) +IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(PAILLIER, PaillierPrivateKey, PaillierPrivateKey) +IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(PAILLIER, PaillierPublicKey, PaillierPublicKey) diff --git a/crypto/paillier/pai_lcl.h b/crypto/paillier/pai_lcl.h index 4fe78f1d..1f62827a 100644 --- a/crypto/paillier/pai_lcl.h +++ b/crypto/paillier/pai_lcl.h @@ -50,6 +50,8 @@ #ifndef HEADER_PAI_LCL_H #define HEADER_PAI_LCL_H +#include "e_os.h" + struct paillier_st { int bits; BIGNUM *n; /* public key */ @@ -57,6 +59,11 @@ struct paillier_st { BIGNUM *n_squared; /* online */ BIGNUM *n_plusone; /* online */ BIGNUM *x; /* online */ + + int references; + int flags; + CRYPTO_EX_DATA ex_data; + CRYPTO_RWLOCK *lock; }; #endif diff --git a/crypto/paillier/pai_lib.c b/crypto/paillier/pai_lib.c index 6b6b68be..df44844d 100644 --- a/crypto/paillier/pai_lib.c +++ b/crypto/paillier/pai_lib.c @@ -145,6 +145,8 @@ int PAILLIER_generate_key(PAILLIER *key, int bits) } while (0); + ret = 1; + end: BN_clear_free(p); BN_clear_free(q); @@ -345,3 +347,14 @@ end: return 0; } +int PAILLIER_up_ref(PAILLIER *r) +{ + int i; + + if (CRYPTO_atomic_add(&r->references, 1, &i, r->lock) <= 0) + return 0; + + REF_PRINT_COUNT("PAILLIER", r); + REF_ASSERT_ISNT(i < 2); + return ((i > 1) ? 1 : 0); +} diff --git a/crypto/pem/build.info b/crypto/pem/build.info index 357b3283..bd79026e 100644 --- a/crypto/pem/build.info +++ b/crypto/pem/build.info @@ -1,4 +1,5 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ pem_sign.c pem_info.c pem_lib.c pem_all.c pem_err.c \ - pem_x509.c pem_xaux.c pem_oth.c pem_pk8.c pem_pkey.c pvkfmt.c + pem_x509.c pem_xaux.c pem_oth.c pem_pk8.c pem_pkey.c pvkfmt.c \ + pem3.c diff --git a/crypto/pem/pem3.c b/crypto/pem/pem3.c new file mode 100644 index 00000000..0fecbc5d --- /dev/null +++ b/crypto/pem/pem3.c @@ -0,0 +1,108 @@ +/* ==================================================================== + * Copyright (c) 2014 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#include +#include "internal/cryptlib.h" +#include +#include +#include +#include +#include +#include +#include + +/* +extern PAILLIER *EVP_PKEY_get1_PAILLIER(EVP_PKEY *key); +extern int i2d_PAILLIER_PUBKEY(PAILLIER *a, unsigned char **p); +extern PAILLIER *d2i_PAILLIER_PUBKEY(PAILLIER **a, const unsigned char **p, long len); +*/ + +#ifndef OPENSSL_NO_PAILLIER +static PAILLIER *pkey_get_paillier(EVP_PKEY *key, PAILLIER **paillier) +{ + PAILLIER *rtmp; + if (!key) + return NULL; + rtmp = EVP_PKEY_get1_PAILLIER(key); + EVP_PKEY_free(key); + if (!rtmp) + return NULL; + if (paillier) { + PAILLIER_free(*paillier); + *paillier = rtmp; + } + return rtmp; +} + +PAILLIER *PEM_read_bio_PaillierPrivateKey(BIO *bp, PAILLIER **paillier, + pem_password_cb *cb, void *u) +{ + EVP_PKEY *pktmp; + pktmp = PEM_read_bio_PrivateKey(bp, NULL, cb, u); + return pkey_get_paillier(pktmp, paillier); +} + +# ifndef OPENSSL_NO_STDIO +PAILLIER *PEM_read_PaillierPrivateKey(FILE *fp, PAILLIER **paillier, + pem_password_cb *cb, void *u) +{ + EVP_PKEY *pktmp; + pktmp = PEM_read_PrivateKey(fp, NULL, cb, u); + return pkey_get_paillier(pktmp, paillier); +} + +# endif + +IMPLEMENT_PEM_write_cb_const(PaillierPrivateKey, PAILLIER, PEM_STRING_PAILLIER, + PaillierPrivateKey) +IMPLEMENT_PEM_rw_const(PaillierPublicKey, PAILLIER, PEM_STRING_PAILLIER_PUBLIC, + PaillierPublicKey) +IMPLEMENT_PEM_rw(PAILLIER_PUBKEY, PAILLIER, PEM_STRING_PUBLIC, PAILLIER_PUBKEY) + +#endif diff --git a/crypto/saf/saf_ec.c b/crypto/saf/saf_ec.c index bfff7992..fe8b4f5e 100644 --- a/crypto/saf/saf_ec.c +++ b/crypto/saf/saf_ec.c @@ -622,5 +622,3 @@ int SAF_EccVerifySignFile( { return SAR_OK; } - - diff --git a/crypto/serpent/build.info b/crypto/serpent/build.info new file mode 100644 index 00000000..eee86dc9 --- /dev/null +++ b/crypto/serpent/build.info @@ -0,0 +1,2 @@ +LIBS=../../libcrypto +SOURCE[../../libcrypto]=serpent.c diff --git a/crypto/serpent/serpent.c b/crypto/serpent/serpent.c new file mode 100644 index 00000000..f0f00026 --- /dev/null +++ b/crypto/serpent/serpent.c @@ -0,0 +1,319 @@ +/* This is an implementation of the encryption algorithm: */ +/* Serpent by Ross Anderson, Eli Biham and Lars Knudsen */ +/* which is a candidate algorithm in the Advanced Encryption Standard */ +/* programme of the US National Institute of Standards and Technology. */ +/* Copyright in this implementation is held by Dou Qinglin. but I */ +/* hereby give permission for its free direct or derivative use subject */ +/* to acknowledgment of its origin and compliance with any conditions */ +/* that the originators of the algorithm place on its exploitation. */ + +#include +#include +#include + +#define IN +#define OUT +void linear(IN unsigned long int *li_0,IN unsigned long int *li_1,IN unsigned long int *li_2,IN unsigned long int *li_3,OUT unsigned long int *lo_0,OUT unsigned long int *lo_1,OUT unsigned long int *lo_2,OUT unsigned long int *lo_3); +void IP(IN unsigned long int *ip_i0,IN unsigned long int *ip_i1,IN unsigned long int *ip_i2,IN unsigned long int *ip_i3,OUT unsigned long int *ip_o0,OUT unsigned long int *ip_o1,OUT unsigned long int *ip_o2,OUT unsigned long int *ip_o3); +void FP(IN unsigned long int *fp_i0,IN unsigned long int *fp_i1,IN unsigned long int *fp_i2,IN unsigned long int *fp_i3,OUT unsigned long int *fp_o0,OUT unsigned long int *fp_o1,OUT unsigned long int *fp_o2,OUT unsigned long int *fp_o3); + +volatile unsigned long int takbit_in0,takbit_in1,takbit_in2,takbit_in3; + +unsigned char takebit(unsigned char bit_num){ + unsigned char bit_out; + if (bit_num< 32) bit_out = ((takbit_in0<< bit_num )&0x80000000)>>31; + else if (bit_num< 64) bit_out = ((takbit_in1<<(bit_num-32))&0x80000000)>>31; + else if (bit_num< 96) bit_out = ((takbit_in2<<(bit_num-64))&0x80000000)>>31; + else if (bit_num< 128) bit_out = ((takbit_in3<<(bit_num-96))&0x80000000)>>31; + else ; + return (bit_out & 0x00000001); +} + +//sbox involking func, each block use 1 sbox 32 times by involking this func for 4 times +unsigned long int sb(char sb_num,unsigned long int sb_in_long){ + char sb_i[8]; + char sb_o[8]; + unsigned long int sb_out_long; + char cnt; +//data div, 32bit input divide into 8 parts, each 4bit + sb_i[0] = (sb_in_long>>28) & 0x0f; // 0~3f + sb_i[1] = (sb_in_long>>24) & 0x0f; // 4~7 + sb_i[2] = (sb_in_long>>20) & 0x0f; // 8~11 + sb_i[3] = (sb_in_long>>16) & 0x0f; // 12~15 + sb_i[4] = (sb_in_long>>12) & 0x0f; // 16~19 + sb_i[5] = (sb_in_long>> 8) & 0x0f; // 20~23 + sb_i[6] = (sb_in_long>> 4) & 0x0f; // 24~27 + sb_i[7] = (sb_in_long ) & 0x0f; // 28~31 + //judge which sbox to use,and get 8 outputs of 8 independent + switch (sb_num) + { + case 0: for (cnt = 0; cnt < 8; cnt++) sb_o[cnt] = sb0(sb_i[cnt] );break; + case 1: for (cnt = 0; cnt < 8; cnt++) sb_o[cnt] = sb1(sb_i[cnt] );break; + case 2: for (cnt = 0; cnt < 8; cnt++) sb_o[cnt] = sb2(sb_i[cnt] );break; + case 3: for (cnt = 0; cnt < 8; cnt++) sb_o[cnt] = sb3(sb_i[cnt] );break; + case 4: for (cnt = 0; cnt < 8; cnt++) sb_o[cnt] = sb4(sb_i[cnt] );break; + case 5: for (cnt = 0; cnt < 8; cnt++) sb_o[cnt] = sb5(sb_i[cnt] );break; + case 6: for (cnt = 0; cnt < 8; cnt++) sb_o[cnt] = sb6(sb_i[cnt] );break; + case 7: for (cnt = 0; cnt < 8; cnt++) sb_o[cnt] = sb7(sb_i[cnt] );break; + default: for (cnt = 0; cnt < 8; cnt++) sb_o[cnt] = 0x0; break; + } + //combine the sbox output together + sb_out_long = (sb_o[0]<<28) + (sb_o[1]<<24) + (sb_o[2]<<20) + (sb_o[3]<<16) + (sb_o[4]<<12) + (sb_o[5]<<8) + (sb_o[6]<<4) + sb_o[7]; + + return sb_out_long; +} + +//define the sbox0~7 un-linear logic +char sb0(char sb0_in){ + char sb0_o; + switch (sb0_in){ + case 0x0: sb0_o= 3 ;break; + case 0x1: sb0_o= 8 ;break; + case 0x2: sb0_o= 15;break; + case 0x3: sb0_o= 1 ;break; + case 0x4: sb0_o= 10;break; + case 0x5: sb0_o= 6 ;break; + case 0x6: sb0_o= 5 ;break; + case 0x7: sb0_o= 11;break; + case 0x8: sb0_o= 14;break; + case 0x9: sb0_o= 13;break; + case 0xA: sb0_o= 4 ;break; + case 0xB: sb0_o= 2 ;break; + case 0xC: sb0_o= 7 ;break; + case 0xD: sb0_o= 0 ;break; + case 0xE: sb0_o= 9 ;break; + case 0xF: sb0_o= 12;break; + default: sb0_o= 0 ;break; + } + return sb0_o; +} + +char sb1(char sb1_in){ + char sb1_o; + switch (sb1_in){ + case 0x0: sb1_o= 15;break; + case 0x1: sb1_o= 12;break; + case 0x2: sb1_o= 2 ;break; + case 0x3: sb1_o= 7 ;break; + case 0x4: sb1_o= 9 ;break; + case 0x5: sb1_o= 0 ;break; + case 0x6: sb1_o= 5 ;break; + case 0x7: sb1_o= 10;break; + case 0x8: sb1_o= 1 ;break; + case 0x9: sb1_o= 11;break; + case 0xA: sb1_o= 14;break; + case 0xB: sb1_o= 8 ;break; + case 0xC: sb1_o= 6 ;break; + case 0xD: sb1_o= 13;break; + case 0xE: sb1_o= 3 ;break; + case 0xF: sb1_o= 4 ;break; + default: sb1_o= 0 ;break; + } + return sb1_o; +} + +char sb2(char sb2_in){ + char sb2_o; + switch (sb2_in){ + case 0x0: sb2_o= 8 ;break; + case 0x1: sb2_o= 6 ;break; + case 0x2: sb2_o= 7 ;break; + case 0x3: sb2_o= 9 ;break; + case 0x4: sb2_o= 3 ;break; + case 0x5: sb2_o= 12;break; + case 0x6: sb2_o= 10;break; + case 0x7: sb2_o= 15;break; + case 0x8: sb2_o= 13;break; + case 0x9: sb2_o= 1 ;break; + case 0xA: sb2_o= 14;break; + case 0xB: sb2_o= 4 ;break; + case 0xC: sb2_o= 0 ;break; + case 0xD: sb2_o= 11;break; + case 0xE: sb2_o= 5 ;break; + case 0xF: sb2_o= 2 ;break; + default: sb2_o= 0 ;break; + } + return sb2_o; +} + +char sb3(char sb3_in){ + char sb3_o; + switch (sb3_in){ + case 0x0: sb3_o= 0 ;break; + case 0x1: sb3_o= 15;break; + case 0x2: sb3_o= 11;break; + case 0x3: sb3_o= 8 ;break; + case 0x4: sb3_o= 12;break; + case 0x5: sb3_o= 9 ;break; + case 0x6: sb3_o= 6 ;break; + case 0x7: sb3_o= 3 ;break; + case 0x8: sb3_o= 13;break; + case 0x9: sb3_o= 1 ;break; + case 0xA: sb3_o= 2 ;break; + case 0xB: sb3_o= 4 ;break; + case 0xC: sb3_o= 10;break; + case 0xD: sb3_o= 7 ;break; + case 0xE: sb3_o= 5 ;break; + case 0xF: sb3_o= 14;break; + default: sb3_o= 0 ;break; + } + return sb3_o; +} + +char sb4(char sb4_in){ + char sb4_o; + switch (sb4_in){ + case 0x0: sb4_o= 1 ;break; + case 0x1: sb4_o= 15;break; + case 0x2: sb4_o= 8 ;break; + case 0x3: sb4_o= 3 ;break; + case 0x4: sb4_o= 12;break; + case 0x5: sb4_o= 0 ;break; + case 0x6: sb4_o= 11;break; + case 0x7: sb4_o= 6 ;break; + case 0x8: sb4_o= 2 ;break; + case 0x9: sb4_o= 5 ;break; + case 0xA: sb4_o= 4 ;break; + case 0xB: sb4_o= 10;break; + case 0xC: sb4_o= 9 ;break; + case 0xD: sb4_o= 14;break; + case 0xE: sb4_o= 7 ;break; + case 0xF: sb4_o= 13;break; + default: sb4_o= 0; break; + } + return sb4_o; +} + +char sb5(char sb5_in){ + char sb5_o; + switch (sb5_in){ + case 0x0: sb5_o= 15;break; + case 0x1: sb5_o= 5 ;break; + case 0x2: sb5_o= 2 ;break; + case 0x3: sb5_o= 11;break; + case 0x4: sb5_o= 4 ;break; + case 0x5: sb5_o= 10;break; + case 0x6: sb5_o= 9 ;break; + case 0x7: sb5_o= 12;break; + case 0x8: sb5_o= 0 ;break; + case 0x9: sb5_o= 3 ;break; + case 0xA: sb5_o= 14;break; + case 0xB: sb5_o= 8 ;break; + case 0xC: sb5_o= 13;break; + case 0xD: sb5_o= 6 ;break; + case 0xE: sb5_o= 7 ;break; + case 0xF: sb5_o= 1 ;break; + default: sb5_o= 0; break; + } + return sb5_o; +} + +char sb6(char sb6_in){ + char sb6_o; + switch (sb6_in){ + case 0x0: sb6_o= 7 ;break; + case 0x1: sb6_o= 2 ;break; + case 0x2: sb6_o= 12;break; + case 0x3: sb6_o= 5 ;break; + case 0x4: sb6_o= 8 ;break; + case 0x5: sb6_o= 4 ;break; + case 0x6: sb6_o= 6 ;break; + case 0x7: sb6_o= 11;break; + case 0x8: sb6_o= 14;break; + case 0x9: sb6_o= 9 ;break; + case 0xA: sb6_o= 1 ;break; + case 0xB: sb6_o= 15;break; + case 0xC: sb6_o= 13;break; + case 0xD: sb6_o= 3 ;break; + case 0xE: sb6_o= 10;break; + case 0xF: sb6_o= 0 ;break; + default: sb6_o= 0 ;break; + } + return sb6_o; +} + +char sb7(char sb7_in){ + char sb7_o; + switch (sb7_in){ + case 0x0: sb7_o= 1 ;break; + case 0x1: sb7_o= 13;break; + case 0x2: sb7_o= 15;break; + case 0x3: sb7_o= 0 ;break; + case 0x4: sb7_o= 14;break; + case 0x5: sb7_o= 8 ;break; + case 0x6: sb7_o= 2 ;break; + case 0x7: sb7_o= 11;break; + case 0x8: sb7_o= 7 ;break; + case 0x9: sb7_o= 4 ;break; + case 0xA: sb7_o= 12;break; + case 0xB: sb7_o= 10;break; + case 0xC: sb7_o= 9 ;break; + case 0xD: sb7_o= 3 ;break; + case 0xE: sb7_o= 5 ;break; + case 0xF: sb7_o= 6 ;break; + default: sb7_o= 0 ;break; + } + return sb7_o; +} + +//initial permutation +void IP(IN unsigned long int *ip_i0,IN unsigned long int *ip_i1,IN unsigned long int *ip_i2,IN unsigned long int *ip_i3,OUT unsigned long int *ip_o0,OUT unsigned long int *ip_o1,OUT unsigned long int *ip_o2,OUT unsigned long int *ip_o3){ + unsigned long int tmp_0,tmp_1,tmp_2,tmp_3; + takbit_in0 = *ip_i0; + takbit_in1 = *ip_i1; + takbit_in2 = *ip_i2; + takbit_in3 = *ip_i3; + //execute takbit function + tmp_0 = (takebit(120)<<31) + (takebit( 88)<<30) + (takebit( 56)<<29) + (takebit( 24)<<28) + (takebit(121)<<27) + (takebit( 89)<<26) + (takebit( 57)<<25) + (takebit( 25)<<24) + (takebit(122)<<23) + (takebit( 90)<<22) + (takebit( 58)<<21) + (takebit( 26)<<20) + (takebit(123)<<19) + (takebit( 91)<<18) + (takebit( 59)<<17) + (takebit( 27)<<16) + (takebit(124)<<15) + (takebit( 92)<<14) + (takebit( 60)<<13) + (takebit( 28)<<12) + (takebit(125)<<11) + (takebit( 93)<<10) + (takebit( 61)<<9 ) + (takebit( 29)<<8 ) + (takebit(126)<<7 ) + (takebit( 94)<<6 ) + (takebit( 62)<<5 ) + (takebit( 30)<<4 ) + (takebit(127)<<3 ) + (takebit( 95)<<2 ) + (takebit( 63)<<1 ) + (takebit( 31) ); + tmp_1 = (takebit(112)<<31) + (takebit( 80)<<30) + (takebit( 48)<<29) + (takebit( 16)<<28) + (takebit(113)<<27) + (takebit( 81)<<26) + (takebit( 49)<<25) + (takebit( 17)<<24) + (takebit(114)<<23) + (takebit( 82)<<22) + (takebit( 50)<<21) + (takebit( 18)<<20) + (takebit(115)<<19) + (takebit( 83)<<18) + (takebit( 51)<<17) + (takebit( 19)<<16) + (takebit(116)<<15) + (takebit( 84)<<14) + (takebit( 52)<<13) + (takebit( 20)<<12) + (takebit(117)<<11) + (takebit( 85)<<10) + (takebit( 53)<<9 ) + (takebit( 21)<<8 ) + (takebit(118)<<7 ) + (takebit( 86)<<6 ) + (takebit( 54)<<5 ) + (takebit( 22)<<4 ) + (takebit(119)<<3 ) + (takebit( 87)<<2 ) + (takebit( 55)<<1 ) + (takebit( 23) ); + tmp_2 = (takebit(104)<<31) + (takebit( 72)<<30) + (takebit( 40)<<29) + (takebit( 8)<<28) + (takebit(105)<<27) + (takebit( 73)<<26) + (takebit( 41)<<25) + (takebit( 9)<<24) + (takebit(106)<<23) + (takebit( 74)<<22) + (takebit( 42)<<21) + (takebit( 10)<<20) + (takebit(107)<<19) + (takebit( 75)<<18) + (takebit( 43)<<17) + (takebit( 11)<<16) + (takebit(108)<<15) + (takebit( 76)<<14) + (takebit( 44)<<13) + (takebit( 12)<<12) + (takebit(109)<<11) + (takebit( 77)<<10) + (takebit( 45)<<9 ) + (takebit( 13)<<8 ) + (takebit(110)<<7 ) + (takebit( 78)<<6 ) + (takebit( 46)<<5 ) + (takebit( 14)<<4 ) + (takebit(111)<<3 ) + (takebit( 79)<<2 ) + (takebit( 47)<<1 ) + (takebit( 15) ); + tmp_3 = (takebit( 96)<<31) + (takebit( 64)<<30) + (takebit( 32)<<29) + (takebit( 0)<<28) + (takebit( 97)<<27) + (takebit( 65)<<26) + (takebit( 33)<<25) + (takebit( 1)<<24) + (takebit( 98)<<23) + (takebit( 66)<<22) + (takebit( 34)<<21) + (takebit( 2)<<20) + (takebit( 99)<<19) + (takebit( 67)<<18) + (takebit( 35)<<17) + (takebit( 3)<<16) + (takebit(100)<<15) + (takebit( 68)<<14) + (takebit( 36)<<13) + (takebit( 4)<<12) + (takebit(101)<<11) + (takebit( 69)<<10) + (takebit( 37)<<9 ) + (takebit( 5)<<8 ) + (takebit(102)<<7 ) + (takebit( 70)<<6 ) + (takebit( 38)<<5 ) + (takebit( 6)<<4 ) + (takebit(103)<<3 ) + (takebit( 71)<<2 ) + (takebit( 39)<<1 ) + (takebit( 7) ); + //write data to sb_in[] + *ip_o0 = tmp_0; + *ip_o1 = tmp_1; + *ip_o2 = tmp_2; + *ip_o3 = tmp_3; +} + +//initial permutation +void FP(IN unsigned long int *fp_i0,IN unsigned long int *fp_i1,IN unsigned long int *fp_i2,IN unsigned long int *fp_i3,OUT unsigned long int *fp_o0,OUT unsigned long int *fp_o1,OUT unsigned long int *fp_o2,OUT unsigned long int *fp_o3){ + unsigned long int tmp_0,tmp_1,tmp_2,tmp_3; + takbit_in0 = *fp_i0; + takbit_in1 = *fp_i1; + takbit_in2 = *fp_i2; + takbit_in3 = *fp_i3; + //execute takbit function + tmp_3 = (takebit(96)<<31) + (takebit(100 )<<30) + (takebit(104 )<<29) + (takebit(108 )<<28) + (takebit(112 )<<27) + (takebit(116 )<<26) + (takebit(120 )<<25) + (takebit(124 )<<24) + (takebit(64)<<23) + (takebit(68 )<<22) + (takebit(72 )<<21) + (takebit(76 )<<20) + (takebit(80 )<<19) + (takebit(84 )<<18) + (takebit(88 )<<17) + (takebit(92 )<<16) + (takebit(32)<<15) + (takebit(36 )<<14) + (takebit(40 )<<13) + (takebit(44 )<<12) + (takebit(48 )<<11) + (takebit(52 )<<10) + (takebit(56 )<<9) + (takebit(60 )<<8) + (takebit(0 )<<7) + (takebit( 4 )<<6) + (takebit( 8 )<<5) + (takebit(12 )<<4) + (takebit(16 )<<3) + (takebit(20 )<<2) + (takebit(24 )<<1) + takebit(28 ); + tmp_2 = (takebit(97)<<31) + (takebit(101 )<<30) + (takebit(105 )<<29) + (takebit(109 )<<28) + (takebit(113 )<<27) + (takebit(117 )<<26) + (takebit(121 )<<25) + (takebit(125 )<<24) + (takebit(65)<<23) + (takebit(69 )<<22) + (takebit(73 )<<21) + (takebit(77 )<<20) + (takebit(81 )<<19) + (takebit(85 )<<18) + (takebit(89 )<<17) + (takebit(93 )<<16) + (takebit(33)<<15) + (takebit(37 )<<14) + (takebit(41 )<<13) + (takebit(45 )<<12) + (takebit(49 )<<11) + (takebit(53 )<<10) + (takebit(57 )<<9) + (takebit(61 )<<8) + (takebit(1 )<<7) + (takebit( 5 )<<6) + (takebit( 9 )<<5) + (takebit(13 )<<4) + (takebit(17 )<<3) + (takebit(21 )<<2) + (takebit(25 )<<1) + takebit(29 ); + tmp_1 = (takebit(98)<<31) + (takebit(102 )<<30) + (takebit(106 )<<29) + (takebit(110 )<<28) + (takebit(114 )<<27) + (takebit(118 )<<26) + (takebit(122 )<<25) + (takebit(126 )<<24) + (takebit(66)<<23) + (takebit(70 )<<22) + (takebit(74 )<<21) + (takebit(78 )<<20) + (takebit(82 )<<19) + (takebit(86 )<<18) + (takebit(90 )<<17) + (takebit(94 )<<16) + (takebit(34)<<15) + (takebit(38 )<<14) + (takebit(42 )<<13) + (takebit(46 )<<12) + (takebit(50 )<<11) + (takebit(54 )<<10) + (takebit(58 )<<9) + (takebit(62 )<<8) + (takebit(2 )<<7) + (takebit( 6 )<<6) + (takebit(10 )<<5) + (takebit(14 )<<4) + (takebit(18 )<<3) + (takebit(22 )<<2) + (takebit(26 )<<1) + takebit(30 ); + tmp_0 = (takebit(99)<<31) + (takebit(103 )<<30) + (takebit(107 )<<29) + (takebit(111 )<<28) + (takebit(115 )<<27) + (takebit(119 )<<26) + (takebit(123 )<<25) + (takebit(127 )<<24) + (takebit(67)<<23) + (takebit(71 )<<22) + (takebit(75 )<<21) + (takebit(79 )<<20) + (takebit(83 )<<19) + (takebit(87 )<<18) + (takebit(91 )<<17) + (takebit(95 )<<16) + (takebit(35)<<15) + (takebit(39 )<<14) + (takebit(43 )<<13) + (takebit(47 )<<12) + (takebit(51 )<<11) + (takebit(55 )<<10) + (takebit(59 )<<9) + (takebit(63 )<<8) + (takebit(3 )<<7) + (takebit( 7 )<<6) + (takebit(11 )<<5) + (takebit(15 )<<4) + (takebit(19 )<<3) + (takebit(23 )<<2) + (takebit(27 )<<1) + takebit(31 ); + //data out + *fp_o0 = tmp_0; + *fp_o1 = tmp_1; + *fp_o2 = tmp_2; + *fp_o3 = tmp_3; +} + +void linear(IN unsigned long int *li_0,IN unsigned long int *li_1,IN unsigned long int *li_2,IN unsigned long int *li_3,OUT unsigned long int *lo_0,OUT unsigned long int *lo_1,OUT unsigned long int *lo_2,OUT unsigned long int *lo_3){ + unsigned long int tmp_0,tmp_1,tmp_2,tmp_3; + tmp_0 = *li_0; + tmp_1 = *li_1; + tmp_2 = *li_2; + tmp_3 = *li_3; + + tmp_0 = rotl(tmp_0, 13); + tmp_2 = rotl(tmp_2, 3); + tmp_1 = tmp_1 ^ tmp_0 ^ tmp_2; + tmp_3 = tmp_3 ^ tmp_2 ^ (tmp_0 << 3); + tmp_1 = rotl(tmp_1, 1); + tmp_3 = rotl(tmp_3, 7); + tmp_0 = tmp_0 ^ tmp_1 ^ tmp_3; + tmp_2 = tmp_2 ^ tmp_3 ^ (tmp_1 << 7); + tmp_0 = rotl(tmp_0, 5); + tmp_2 = rotl(tmp_2, 22); + + *lo_0 = tmp_0; + *lo_1 = tmp_1; + *lo_2 = tmp_2; + *lo_3 = tmp_3; +} diff --git a/crypto/serpent/serpent.d.tmp b/crypto/serpent/serpent.d.tmp new file mode 100644 index 00000000..b65b5bff --- /dev/null +++ b/crypto/serpent/serpent.d.tmp @@ -0,0 +1,2 @@ +crypto/serpent/serpent.o: crypto/serpent/serpent.c \ + include/openssl/serpent.h diff --git a/crypto/sm2/sm2_enc.c b/crypto/sm2/sm2_enc.c index b1584ed6..0c74c830 100644 --- a/crypto/sm2/sm2_enc.c +++ b/crypto/sm2/sm2_enc.c @@ -238,7 +238,7 @@ SM2_CIPHERTEXT_VALUE *SM2_CIPHERTEXT_VALUE_decode( goto end; } - if (buflen <= fixlen) { + if (buflen <= (size_t)fixlen) { ECerr(EC_F_SM2_CIPHERTEXT_VALUE_DECODE, EC_R_BUFFER_TOO_SMALL); goto end; } @@ -260,7 +260,7 @@ SM2_CIPHERTEXT_VALUE *SM2_CIPHERTEXT_VALUE_decode( //FIXME ptlen = fixlen - SM2_ENC_PARAMS_mactag_size(params); #endif - ptlen = fixlen; //FIXME + ptlen = (int)fixlen; //FIXME if (!EC_POINT_oct2point(ec_group, ret->ephem_point, buf, ptlen, bn_ctx)) { ECerr(EC_F_SM2_CIPHERTEXT_VALUE_DECODE, EC_R_OCT2POINT_FAILED); goto end; @@ -290,7 +290,7 @@ int SM2_CIPHERTEXT_VALUE_print(BIO *out, const EC_GROUP *ec_group, int ret = 0; char *hex = NULL; BN_CTX *ctx = BN_CTX_new(); - int i; + size_t i; if (!ctx) { goto end; @@ -382,7 +382,7 @@ SM2_CIPHERTEXT_VALUE *SM2_do_encrypt(const SM2_ENC_PARAMS *params, unsigned int dgstlen; int mactag_size; size_t len; - int i; + size_t i; if (!ec_group || !pub_key) { ECerr(EC_F_SM2_DO_ENCRYPT, EC_R_INVALID_EC_KEY); @@ -513,7 +513,7 @@ SM2_CIPHERTEXT_VALUE *SM2_do_encrypt(const SM2_ENC_PARAMS *params, } /* GmSSL specific: reduce mactag size */ - if (mactag_size > dgstlen) { + if (mactag_size > dgstlen) { ECerr(EC_F_SM2_DO_ENCRYPT, EC_R_ERROR); goto end; } @@ -554,7 +554,7 @@ int SM2_decrypt(const SM2_ENC_PARAMS *params, ECerr(EC_F_SM2_DECRYPT, EC_R_ERROR); goto end; } - if (inlen <= len) { + if (inlen <= len) { ECerr(EC_F_SM2_DECRYPT, EC_R_ERROR); goto end; } @@ -673,7 +673,7 @@ int SM2_do_decrypt(const SM2_ENC_PARAMS *params, /* B5: compute M = C2 xor t */ - for (i = 0; i < cv->ciphertext_size; i++) { + for (i = 0; i < cv->ciphertext_size; i++) { out[i] ^= cv->ciphertext[i]; } *outlen = cv->ciphertext_size; @@ -704,7 +704,7 @@ int SM2_do_decrypt(const SM2_ENC_PARAMS *params, } /* GmSSL specific */ - if (mactag_size > maclen) { + if (mactag_size > (int)maclen) { ECerr(EC_F_SM2_DO_DECRYPT, EC_R_ERROR); goto end; } @@ -742,4 +742,3 @@ int SM2_decrypt_with_recommended(const unsigned char *in, size_t inlen, SM2_ENC_PARAMS_init_with_recommended(¶ms); return SM2_decrypt(¶ms, in, inlen, out, outlen, ec_key); } - diff --git a/crypto/sm2/sm2_kap.c b/crypto/sm2/sm2_kap.c index 0e9dedf9..03a00a5e 100644 --- a/crypto/sm2/sm2_kap.c +++ b/crypto/sm2/sm2_kap.c @@ -60,6 +60,7 @@ int SM2_KAP_CTX_init(SM2_KAP_CTX *ctx, { int ret = 0; int w; + size_t len; if (!ctx || !ec_key || !remote_pubkey) { ECerr(EC_F_SM2_KAP_CTX_INIT, ERR_R_PASSED_NULL_PARAMETER); @@ -87,22 +88,26 @@ int SM2_KAP_CTX_init(SM2_KAP_CTX *ctx, goto end; } + len = ctx->id_dgstlen; if (!SM2_compute_id_digest(ctx->id_dgst_md, id, idlen, - ctx->id_dgst, &ctx->id_dgstlen, ec_key)) { + ctx->id_dgst, &len, ec_key)) { ECerr(EC_F_SM2_KAP_CTX_INIT, 0); goto end; } + ctx->id_dgstlen = len; if (!(ctx->ec_key = EC_KEY_dup(ec_key))) { ECerr(EC_F_SM2_KAP_CTX_INIT, ERR_R_EC_LIB); goto end; } + len = ctx->remote_id_dgstlen; if (!SM2_compute_id_digest(ctx->id_dgst_md, rid, ridlen, - ctx->remote_id_dgst, &ctx->remote_id_dgstlen, remote_pubkey)) { + ctx->remote_id_dgst, &len, remote_pubkey)) { ECerr(EC_F_SM2_KAP_CTX_INIT, 0); goto end; } + ctx->remote_id_dgstlen = len; if (!(ctx->remote_pubkey = EC_KEY_dup(remote_pubkey))) { ECerr(EC_F_SM2_KAP_CTX_INIT, 0); diff --git a/crypto/sm9/sm9_enc.c b/crypto/sm9/sm9_enc.c index 94c51aeb..bd7c7178 100644 --- a/crypto/sm9/sm9_enc.c +++ b/crypto/sm9/sm9_enc.c @@ -431,7 +431,7 @@ int SM9_unwrap_key(SM9PublicParameters *mpk, size_t keylen, } /* is outkey is all zero, return failed */ - for (i = 0; (i < keylen) && (outkey[i] == 0); i++) { + for (i = 0; (i < keylen) && (outkey[i] == 0); i++) { } if (i == keylen) { SM9err(SM9_F_SM9_UNWRAP_KEY, ERR_R_EC_LIB); @@ -630,7 +630,7 @@ static int SM9EncParameters_decrypt(const SM9EncParameters *encparams, /* output iv */ iv = in; ivlen = EVP_CIPHER_iv_length(encparams->enc_cipher); - if (inlen <= ivlen) { + if (inlen <= (size_t)ivlen) { SM9err(SM9_F_SM9ENCPARAMETERS_DECRYPT, SM9_R_INVALID_CIPHERTEXT); goto end; } @@ -948,7 +948,7 @@ int SM9_do_decrypt(SM9PublicParameters *mpk, const SM9EncParameters *encparams, *outlen = in->c2->length; return 1; } - if (*outlen < in->c2->length) { + if (*outlen < in->c2->length) { SM9err(SM9_F_SM9_DO_DECRYPT, SM9_R_BUFFER_TOO_SMALL); return 0; } @@ -1065,7 +1065,7 @@ int SM9_decrypt(SM9PublicParameters *mpk, const SM9EncParameters *encparams, return 0; } - p = ∈ + p = in; if (!(c = d2i_SM9Ciphertext(NULL, &p, inlen))) { SM9err(SM9_F_SM9_DECRYPT, ERR_R_SM9_LIB); goto end; diff --git a/crypto/sm9/sm9_sign.c b/crypto/sm9/sm9_sign.c index 0c48cc4d..039186a3 100644 --- a/crypto/sm9/sm9_sign.c +++ b/crypto/sm9/sm9_sign.c @@ -457,7 +457,7 @@ int SM9_sign(SM9PublicParameters *mpk, const unsigned char *dgst, return 0; } - p = &sig; + p = sig; if (i2d_SM9Signature(sigobj, &p) < 0) { SM9err(SM9_F_SM9_SIGN, ERR_R_SM9_LIB); goto end; @@ -493,10 +493,10 @@ int SM9_verify(SM9PublicParameters *mpk, const unsigned char *dgst, return 0; } - p = &sig; + p = sig; if (!(sigobj = d2i_SM9Signature(NULL, &p, siglen))) { SM9err(SM9_F_SM9_VERIFY, ERR_R_SM9_LIB); - return 0; + goto end; } ret = SM9_do_verify(mpk, dgst, dgstlen, sigobj, id, idlen); @@ -504,6 +504,5 @@ int SM9_verify(SM9PublicParameters *mpk, const unsigned char *dgst, end: SM9Signature_free(sigobj); - return 0; + return ret; } - diff --git a/crypto/speck/build.info b/crypto/speck/build.info new file mode 100644 index 00000000..f3cc909c --- /dev/null +++ b/crypto/speck/build.info @@ -0,0 +1,2 @@ +LIBS=../../libcrypto +SOURCE[../../libcrypto]=speck.c diff --git a/crypto/speck/speck.c b/crypto/speck/speck.c new file mode 100644 index 00000000..c717d394 --- /dev/null +++ b/crypto/speck/speck.c @@ -0,0 +1,60 @@ +#include + +#define ROR(x, r) ((x >> r) | (x << ((sizeof(SPECK_TYPE) * 8) - r)))//循环右移 +#define ROL(x, r) ((x << r) | (x >> ((sizeof(SPECK_TYPE) * 8) - r)))//循环左移 + +#ifdef SPECK_32_64 +#define R(x, y, k) (x = ROR(x, 7), x += y, x ^= k, y = ROL(y, 2), y ^= x) +#define RR(x, y, k) (y ^= x, y = ROR(y, 2), x ^= k, x -= y, x = ROL(x, 7)) +#else +#define R(x, y, k) (x = ROR(x, 8), x += y, x ^= k, y = ROL(y, 3), y ^= x) +#define RR(x, y, k) (y ^= x, y = ROR(y, 3), x ^= k, x -= y, x = ROL(x, 8)) +#endif + +void speck_set_encrypt_key(speck_key_t *key, const unsigned char *user_key) +{ + int i; + for (i = 0; i < num_word; i++) + { + if (user_key[i] == '\0') + break; + key->rk[i] = user_key[i]; + } + int j = 0; + for (; i < num_word; i++) + { + key->rk[i] = user_key[j++]; + } +} +void speck_expand(SPECK_TYPE const K[ SPECK_KEY_LEN], SPECK_TYPE S[ SPECK_ROUNDS]) +{ + SPECK_TYPE i, b = K[0]; + SPECK_TYPE a[SPECK_KEY_LEN - 1]; + for (i = 0; i < (SPECK_KEY_LEN - 1); i++) + { + a[i] = K[i + 1]; + } + S[0] = b; + for (i = 0; i < SPECK_ROUNDS - 1; i++) { + R(a[i % (SPECK_KEY_LEN - 1)], b, i); + S[i + 1] = b; + } +} +void speck_encrypt(SPECK_TYPE const pt[ 2], SPECK_TYPE ct[ 2], SPECK_TYPE const K[ SPECK_ROUNDS]) +{ + SPECK_TYPE i; + ct[0] = pt[0]; ct[1] = pt[1]; + for (i = 0; i < SPECK_ROUNDS; i++){ + R(ct[1], ct[0], K[i]); + } +} + +void speck_decrypt(SPECK_TYPE const ct[ 2], SPECK_TYPE pt[ 2], SPECK_TYPE const K[ SPECK_ROUNDS]) +{ + SPECK_TYPE i; + pt[0] = ct[0]; pt[1] = ct[1]; + + for (i = 0; i < SPECK_ROUNDS; i++){ + RR(pt[1], pt[0], K[(SPECK_ROUNDS - 1) - i]); + } +} diff --git a/crypto/x509/x_pubkey.c b/crypto/x509/x_pubkey.c index cc692834..16ed7f8e 100644 --- a/crypto/x509/x_pubkey.c +++ b/crypto/x509/x_pubkey.c @@ -16,6 +16,7 @@ #include "internal/x509_int.h" #include #include +#include struct X509_pubkey_st { X509_ALGOR *algor; @@ -255,6 +256,46 @@ int i2d_RSA_PUBKEY(RSA *a, unsigned char **pp) } #endif +#ifndef OPENSSL_NO_PAILLIER +PAILLIER *d2i_PAILLIER_PUBKEY(PAILLIER **a, const unsigned char **pp, long length) +{ + EVP_PKEY *pkey; + PAILLIER *key; + const unsigned char *q; + q = *pp; + pkey = d2i_PUBKEY(NULL, &q, length); + if (!pkey) + return NULL; + key = EVP_PKEY_get1_PAILLIER(pkey); + EVP_PKEY_free(pkey); + if (!key) + return NULL; + *pp = q; + if (a) { + PAILLIER_free(*a); + *a = key; + } + return key; +} + +int i2d_PAILLIER_PUBKEY(PAILLIER *a, unsigned char **pp) +{ + EVP_PKEY *pktmp; + int ret; + if (!a) + return 0; + pktmp = EVP_PKEY_new(); + if (pktmp == NULL) { + ASN1err(ASN1_F_I2D_PAILLIER_PUBKEY, ERR_R_MALLOC_FAILURE); + return 0; + } + EVP_PKEY_set1_PAILLIER(pktmp, a); + ret = i2d_PUBKEY(pktmp, pp); + EVP_PKEY_free(pktmp); + return ret; +} +#endif + #ifndef OPENSSL_NO_DSA DSA *d2i_DSA_PUBKEY(DSA **a, const unsigned char **pp, long length) { diff --git a/engines/e_avx2.c b/engines/e_avx2.c index b227241c..6d5403c4 100644 --- a/engines/e_avx2.c +++ b/engines/e_avx2.c @@ -53,6 +53,8 @@ #include #include +#if (defined(__x86_64) || defined(__x86_64__)) && defined(OPENSSL_CPUID_OBJ) +#endif static const char *avx2_id = "avx2"; static const char *avx2_name = "ENGINE with Intel AVX2 Intructions"; @@ -81,8 +83,6 @@ static int avx2_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) return 1; } -/****************************************************************************/ - static int avx2_cipher_nids[] = {NID_sms4_ecb, NID_sms4_ctr, 0}; static int avx2_num_ciphers = OSSL_NELEM(avx2_cipher_nids) - 1; @@ -282,12 +282,18 @@ static ENGINE *engine_avx2(void) void engine_load_avx2_int(void) { - ENGINE *eng = NULL; - if (!(eng = engine_avx2())) { - return; + extern unsigned int OPENSSL_ia32cap_P[]; + + if (OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) { + ENGINE *toadd = ENGINE_rdrand(); + ENGINE *eng = NULL; + if (!(eng = engine_avx2())) { + return; + } + ENGINE_add(eng); + ENGINE_free(eng); + ERR_clear_error(); } - ENGINE_add(eng); - ENGINE_free(eng); - ERR_clear_error(); } + #endif /* OPENSSL_NO_DYNAMIC_ENGINE */ diff --git a/engines/zeromem/cba_ecdh_engine.c b/engines/zeromem/cba_ecdh_engine.c new file mode 100755 index 00000000..cd0ad63c --- /dev/null +++ b/engines/zeromem/cba_ecdh_engine.c @@ -0,0 +1,265 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_RSA +#include +#endif +#include +#include +#include "ec2m_kern.h" + +struct ecdh_method +{ + const char *name; + int (*compute_key)(void *key, size_t outlen, const EC_POINT *pub_key, EC_KEY *ecdh, + void *(*KDF)(const void *in, size_t inlen, void *out, size_t *outlen)); + int flags; + char *app_data; +}; + + +#ifndef OPENSSL_NO_HW + +/* the header file of vender */ +//#include "hwdevice.h" + +/* Constants used when creating the ENGINE */ +static const char *engine_hwdev_id = "cba_ecdh"; +static const char *engine_hwdev_name = "cold boot resistant ECDH"; +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +/* Compatibility hack, the dynamic library uses this form in the path */ +static const char *engine_hwdev_id_alt = "cba_ecdh"; +#endif + +static int compute_key(void *out, size_t outlen, + const EC_POINT *pub_key, EC_KEY *ecdh, + void *(*KDF)(const void *in, size_t inlen, void *out, size_t *outlen)) +{ + const EC_GROUP* group; + int ret; + + group = EC_KEY_get0_group(ecdh); + + // only use our solution if the curve name is SECT163K1 + if (EC_GROUP_get_curve_name(group) == NID_sect163k1) { + const BIGNUM* rkey; + BN_CTX *ctx; + BIGNUM* x, *y; + mm256_point_t p, q; + mm_256 mkey; + int r; + + ctx = BN_CTX_new(); + BN_CTX_start(ctx); + + x = BN_CTX_get(ctx); + y = BN_CTX_get(ctx); + + rkey = EC_KEY_get0_private_key(ecdh); + memset(&mkey, 0, sizeof(mkey)); + memcpy(&mkey, rkey->d, sizeof(rkey->d[0]) * rkey->top); + ec2m_import_key(&mkey); + + r = EC_POINT_get_affine_coordinates_GF2m(group, pub_key, x, y, ctx); + memset(&p, 0, sizeof(p)); + memcpy(&p.x, x->d, sizeof(x->d[0]) * x->top); + memcpy(&p.y, y->d, sizeof(y->d[0]) * y->top); + p.z.iv[0] = 1; + + r = ec2m_private_operation(&p, &q); + if (r < 0) { + fprintf(stderr, "invalid result: %d\n", r); + } + + int xlen = (163 + 7) / 8; + if (KDF != 0) + { + if (KDF(&q.x, xlen, out, &outlen) == NULL) + { + return -1; + } + ret = outlen; + } + else + { + /* no KDF, just copy as much as we can */ + if (outlen > xlen) + outlen = xlen; + memcpy(out, &q.x, outlen); + ret = outlen; + } + + BN_CTX_end(ctx); + BN_CTX_free(ctx); + + } else { + // use the default method + const ECDH_METHOD* meth = ECDH_OpenSSL(); + return meth->compute_key(out, outlen, pub_key, ecdh, KDF); + } + + return ret; +} + +static ECDH_METHOD ecdh_meth = { + "CBA resistant ECDH method", + compute_key, + 0, + NULL +}; + +static int hwdev_destroy(ENGINE *e) +{ + fprintf(stderr, "arrive at hwdev_destroy\n"); + return 1; +} + +static int hwdev_init(ENGINE *e) +{ + fprintf(stderr, "arrive at hwdev_init\n"); + ec2m_kern_init(); + return 1; +} + +static int hwdev_finish(ENGINE *e) +{ + fprintf(stderr, "arrive at hwdev_finish\n"); + ec2m_kern_clean(); + return 1; +} + +/* The definitions for control commands specific to this engine */ +#define HWDEV_CMD_INIT (ENGINE_CMD_BASE) +#define HWDEV_CMD_EXIT (ENGINE_CMD_BASE + 1) +#define HWDEV_CMD_TEST (ENGINE_CMD_BASE + 2) +static const ENGINE_CMD_DEFN hwdev_cmd_defns[] = { + {HWDEV_CMD_INIT, + "INIT", + "init the hardware device before using", + ENGINE_CMD_FLAG_STRING}, /* may be the password */ + {HWDEV_CMD_EXIT, + "EXIT", + "exit the hardware device after using", + ENGINE_CMD_FLAG_NO_INPUT}, + {HWDEV_CMD_TEST, + "TEST", + "run the test case of the hardware device", + ENGINE_CMD_FLAG_NUMERIC}, /* may be the number of test case */ + {0, NULL, NULL, 0} + }; + +/* This internal function is used by ENGINE_chil() and possibly by the + * "dynamic" ENGINE support too */ +static int hwdev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) +{ + int to_return = 1; + + switch(cmd) { + case HWDEV_CMD_INIT: + fprintf(stderr, "arrive at HWDEV_CMD_INIT, password: %s\n", + (const char *)p); + break; + case HWDEV_CMD_EXIT: + fprintf(stderr, "arrive at HWDEV_CMD_EXIT, no parameters\n"); + break; + case HWDEV_CMD_TEST: + fprintf(stderr, "arrive at HWDEV_CMD_TEST, case id: %ld\n", + i); + break; + /* The command isn't understood by this engine */ + default: + to_return = 0; + break; + } + + return to_return; +} + +static EVP_PKEY *hwdev_load_privkey(ENGINE *eng, const char *key_id, + UI_METHOD *ui_method, void *callback_data) +{ + fprintf(stderr, "arrive at hwdev_load_privkey\n"); + EVP_PKEY *res = NULL; + + return res; +} + +static EVP_PKEY *hwdev_load_pubkey(ENGINE *eng, const char *key_id, + UI_METHOD *ui_method, void *callback_data) +{ + fprintf(stderr, "arrive at hwdev_load_pubkey\n"); + EVP_PKEY *res = NULL; + + return res; +} + +static int bind_helper(ENGINE *e) +{ + fprintf(stderr, "arrive at bind_helper\n"); + if(!ENGINE_set_id(e, engine_hwdev_id) || + !ENGINE_set_name(e, engine_hwdev_name) || + !ENGINE_set_ECDH(e, &ecdh_meth) || + !ENGINE_set_destroy_function(e, hwdev_destroy) || + !ENGINE_set_init_function(e, hwdev_init) || + !ENGINE_set_finish_function(e, hwdev_finish) || + !ENGINE_set_ctrl_function(e, hwdev_ctrl) || + !ENGINE_set_load_privkey_function(e, hwdev_load_privkey) || + !ENGINE_set_load_pubkey_function(e, hwdev_load_pubkey) || + !ENGINE_set_cmd_defns(e, hwdev_cmd_defns)) + return 0; + + return 1; +} + +static ENGINE *engine_hwdev(void) +{ + fprintf(stderr, "arrive at engine_test\n"); + ENGINE *ret = ENGINE_new(); + if(!ret) { + return NULL; + } + + if(!bind_helper(ret)) { + ENGINE_free(ret); + return NULL; + } + + return ret; +} + +void ENGINE_load_test(void) +{ + fprintf(stderr, "arrive at ENGINE_load_test\n"); + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_hwdev(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); +} +//#endif + + +/* This stuff is needed if this ENGINE is being compiled into a self-contained + * shared-library. */ +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +static int bind_fn(ENGINE *e, const char *id) +{ + fprintf(stderr, "arrive at bind_fn\n"); + if(id && (strcmp(id, engine_hwdev_id) != 0) && + (strcmp(id, engine_hwdev_id_alt) != 0)) + return 0; + if(!bind_helper(e)) + return 0; + return 1; +} +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_fn) +#endif /* OPENSSL_NO_DYNAMIC_ENGINE */ + +#endif /* !OPENSSL_NO_HW */ diff --git a/engines/zeromem/ec.h b/engines/zeromem/ec.h new file mode 100755 index 00000000..10afc4b3 --- /dev/null +++ b/engines/zeromem/ec.h @@ -0,0 +1,49 @@ +#ifndef _EC_H_ +#define _EC_H_ + +#ifdef EC_DEV +#include +#else +#include +#endif +//extern unsigned int sqr_table[1 << 16]; + +typedef struct _struct_mm_128{ + union{ + float fv[4]; + double dv[2]; + uint64_t iv[2]; + uint8_t bv[16]; + }; +} mm_128; + +typedef struct _struct_mm_256{ + union{ + float fv[8]; + double dv[4]; + uint64_t iv[4]; + uint8_t bv[32]; + }; +} mm_256; + +typedef struct { + mm_256 x; + mm_256 y; + mm_256 z; +} mm256_point_t; + +extern void gf2_add(mm_256* a, mm_256* b, mm_256* r); +extern void gf2_mul(mm_256* a, mm_256* b, mm_256* r1, mm_256* r2); +extern void gf2_mod(mm_256* a1, mm_256* a2, mm_256* r); +extern void gf2_sqr(mm_256* a, mm_256* r1, mm_256* r2); +extern void gf2_mod_mul(mm_256* a, mm_256* b, mm_256* r); +extern void gf2_mod_sqr(mm_256* a, mm_256* r); +extern void gf2m_inv(mm_256* a, mm_256 *r); +extern void gf2m_inv_asm(mm_256* a, mm_256 *r); + +extern void gf2_point_dbl(mm256_point_t* pa, mm256_point_t* pr, int a, int b); +extern void gf2_point_add(mm256_point_t* pa, mm256_point_t* pb, mm256_point_t* pr, int a, int b); +extern void gf2_point_mul(mm256_point_t* p, mm_256* k, mm256_point_t* q, int a, int b); +extern void gf2_point_mul_with_preset_key(mm256_point_t* p, mm256_point_t* q, int a, int b); + +#endif diff --git a/engines/zeromem/ec2m_kern.c b/engines/zeromem/ec2m_kern.c new file mode 100755 index 00000000..5e439e2d --- /dev/null +++ b/engines/zeromem/ec2m_kern.c @@ -0,0 +1,174 @@ +#include "ec2m_kern.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "util.h" + +int sock_fd; + +int init_netlink(int unit, int portId){ + struct sockaddr_nl src_addr; + sock_fd=socket(PF_NETLINK, SOCK_RAW, unit); + if(sock_fd<0) + return -1; + + memset(&src_addr, 0, sizeof(src_addr)); + src_addr.nl_family = AF_NETLINK; + src_addr.nl_pid = portId; /* self pid */ + /* interested in group 1<<0 */ + bind(sock_fd, (struct sockaddr*)&src_addr, + sizeof(src_addr)); //绑定netlink + + if(sock_fd < 0) + return -1; + + return 0; +} + +int send_request(const int func, const void* msg, int mlen) +{ + struct nlmsghdr *nlh = NULL; + struct iovec iov; + struct msghdr mhdr; + struct sockaddr_nl dest_addr; + struct ec2m_request_st req; + const int len = mlen + sizeof(struct ec2m_request_st); + + req.func = func; + req.len = len; + + memset(&dest_addr, 0, sizeof(dest_addr)); + dest_addr.nl_family = AF_NETLINK; + dest_addr.nl_pid = 0; /* For Linux Kernel */ + dest_addr.nl_groups = 0; /* unicast */ + + memset(&mhdr, 0, sizeof(mhdr)); + nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(len)); + memset(nlh, 0, NLMSG_SPACE(len)); + nlh->nlmsg_len = NLMSG_SPACE(len); + nlh->nlmsg_pid = getpid(); + + nlh->nlmsg_flags = 0; + + memcpy((void*)NLMSG_DATA(nlh), &req, sizeof(req)); + memcpy((void*)NLMSG_DATA(nlh) + sizeof(req), msg, mlen); + + iov.iov_base = (void *)nlh; + iov.iov_len = nlh->nlmsg_len; + + mhdr.msg_name = (void *)&dest_addr; + mhdr.msg_namelen = sizeof(dest_addr); + mhdr.msg_iov = &iov; + mhdr.msg_iovlen = 1; + + sendmsg(sock_fd,&mhdr,0); //通过netlink发送消息 + + + return OK; +} + +int recv_response(void* buf, int len) +{ + struct ec2m_response_st resp; + struct nlmsghdr *nlh = NULL; + struct iovec iov; + struct msghdr mhdr; + struct sockaddr_nl dest_addr; + int buflen; + + memset(&dest_addr, 0, sizeof(dest_addr)); + dest_addr.nl_family = AF_NETLINK; + dest_addr.nl_pid = 0; /* For Linux Kernel */ + dest_addr.nl_groups = 0; /* unicast */ + + memset(&mhdr, 0, sizeof(mhdr)); + nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD)); + memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD)); + nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD); + nlh->nlmsg_pid = getpid(); + nlh->nlmsg_flags = 0; + + iov.iov_base = (void *)nlh; + iov.iov_len = nlh->nlmsg_len; + + mhdr.msg_name = (void *)&dest_addr; + mhdr.msg_namelen = sizeof(dest_addr); + mhdr.msg_iov = &iov; + mhdr.msg_iovlen = 1; + + buflen = recvmsg(sock_fd, &mhdr, 0); + if(buflen < 0){ + fprintf(stderr, "invalid retval of recvmsg %d\n", buflen); + + return buflen; + } + + buflen -= NLMSG_HDRLEN; + assert(buflen >= sizeof(resp)); + memcpy(&resp, NLMSG_DATA(nlh), sizeof(resp)); + buflen -= sizeof(resp); + assert(buflen == len); + + if (buflen > 0 && buf != NULL) { + memcpy(buf, NLMSG_DATA(nlh) + sizeof(resp), buflen); + } + /* printf("resp: %d, len: %d\n", resp.result, buflen); */ + + return resp.result; +} + +int ec2m_kern_init() +{ + int r; + + r = init_netlink(NETLINK_ECC, getpid()); + + if (r < 0) + return r; + + return 0; +} + +void ec2m_kern_clean() +{ + close(sock_fd); +} + + +int ec2m_import_key(mm_256* key) +{ + int r; + + /* printf("key: %016lx%016lx%016lx\n", key->iv[2], key->iv[1], key->iv[0]); */ + r = send_request(REQ_IMPORT_KEY, key, sizeof(mm_256)); + if (r < 0) + return r; + + r = recv_response(NULL, 0); + if (r < 0) + return r; + + + return 0; + +} + +int ec2m_private_operation(mm256_point_t*p, mm256_point_t*q) +{ + int r; + + r = send_request(REQ_PRIVATE_OP, p, sizeof(mm256_point_t)); + if (r < 0) + return r; + + r = recv_response(q, sizeof(mm256_point_t)); + if (r < 0) + return r; + + return 0; +} diff --git a/engines/zeromem/ec2m_kern.h b/engines/zeromem/ec2m_kern.h new file mode 100755 index 00000000..6b1b6be0 --- /dev/null +++ b/engines/zeromem/ec2m_kern.h @@ -0,0 +1,36 @@ +#ifndef _EC2M_KERN_H_ +#define _EC2M_KERN_H_ + +#define NETLINK_ECC 31 +#define MAX_PAYLOAD 1024 + +#define REQ_IMPORT_KEY 1 +#define REQ_PRIVATE_OP 2 + +#define OK 0 +#define FAIL -1 + +#ifdef __KERNEL__ +#include +#else +#include +#endif +#include "ec.h" + +struct ec2m_request_st { + int func; + int len; +}; + +struct ec2m_response_st +{ + int result; +}; + +extern int ec2m_kern_init(void); +extern void ec2m_kern_clean(void); + +extern int ec2m_import_key(mm_256 *key); +extern int ec2m_private_operation(mm256_point_t*p, mm256_point_t*q); + +#endif diff --git a/engines/zeromem/ec_inv.c b/engines/zeromem/ec_inv.c new file mode 100755 index 00000000..7b18c3ab --- /dev/null +++ b/engines/zeromem/ec_inv.c @@ -0,0 +1,104 @@ +#include "ec.h" +#include "string.h" +#include "stdio.h" + +int is_one(mm_256* a) +{ + int i; + if (a->iv[0] != 1) + return 0; + + for (i = 1; i < 4; i++) { + if (a->iv[i] != 0) + return 0; + } + + return 1; + +} + +void shift_right(mm_256* a) +{ + int i; + + for (i = 0; i < 3; i++) { + a->iv[i] = (a->iv[i] >> 1) | (a->iv[i + 1] << 63); + } + a->iv[3] >>= 1; +} + +void add(mm_256* a, mm_256*b) +{ + int i; + + for (i = 0; i < 4; i++) { + b->iv[i] = b->iv[i] ^ a->iv[i]; + } +} + +int deg(mm_256* a) +{ + int cnt = 0; + int i; + uint64_t c; + + for (i = 3; i >= 0; i--) { + if (a->iv[i] != 0) { + break; + } + } + cnt = i * 64; + c = a->iv[i]; + while (c != 0) { + cnt ++; + c >>= 1; + } + return cnt; +} + +void gf2m_inv(mm_256* a, mm_256 *r) +{ + mm_256 b, c, u, v, f, t; + + // b = 1 + memset(&b, 0, sizeof(b)); + b.iv[0] = 1; + // c = 0 + memset(&c, 0, sizeof(c)); + // u = a + u = *a; + // v = f + memset(&v, 0, sizeof(v)); + memset(&f, 0, sizeof(f)); + f.bv[0] = 0xc9; + f.bv[20] = 0x8; + v = f; + + while (1) { + while ((u.bv[0] & 0x1) == 0) { + shift_right(&u); + + if ((b.iv[0] & 0x1) != 0) { + add(&f, &b); + } + shift_right(&b); + } + if (is_one(&u)) + break; + + if (deg(&u) < deg(&v)) { + t = u; + u = v; + v = t; + + t = b; + b = c; + c = t; + } + add(&v, &u); + add(&c, &b); + /* break; */ + } + + *r = b; +} diff --git a/engines/zeromem/ec_main.c b/engines/zeromem/ec_main.c new file mode 100755 index 00000000..7b8cf0fe --- /dev/null +++ b/engines/zeromem/ec_main.c @@ -0,0 +1,37 @@ +#include +#include +#include +#include "ec.h" +#include "test.h" + +int main(int argc, char** argv){ + /* + int i; + + for(i = 0; i < argc; i++){ + printf("arg %d: %s\n", i, argv[i]); + } + */ + + char* cmd = argv[1]; + if(!initDomainParameters(argc, argv)){ + return 1; + } + if(strcmp(cmd, "testFieldArithmetic") == 0){ + return testFieldArithmetic(); + } else if(strcmp(cmd, "testPointArithmetic") == 0){ + return testPointArithmetic(); + } else if(strcmp(cmd, "testAES") == 0){ + return testAES(); + } else if(strcmp(cmd, "benchmark_ec2") == 0){ + return benchmark_EC2(); + } else if(strcmp(cmd, "testKernelEc2m") == 0){ + return testKernelEc2m(); + } else if(strcmp(cmd, "testMisc") == 0){ + return testMisc(); + } else if(strcmp(cmd, "testCycles") == 0){ + return benchmark_cycles(); + } + + return 1; +} diff --git a/engines/zeromem/engine/myengine.c b/engines/zeromem/engine/myengine.c new file mode 100755 index 00000000..3879b4d0 --- /dev/null +++ b/engines/zeromem/engine/myengine.c @@ -0,0 +1,260 @@ +#include +#include +#include +#include +#include +#include +#include +#include "myengine.h" +#include "../ec.h" +#include "../util.h" + +int get_affine(const EC_GROUP* group, const EC_POINT* point, BIGNUM* x, BIGNUM* y, BN_CTX *ctx){ + int ret = 0; + if(EC_POINT_is_at_infinity(group, point)){ + return 0; + } + if(x == NULL || y == NULL) + return 0; + if(BN_cmp(&point->Z, BN_value_one()) == 0){ + if(!BN_copy(x, &point->X) || !BN_copy(y, &point->Y)) + return 0; + BN_set_negative(x, 0); + BN_set_negative(y, 0); + } else { + BIGNUM* z = BN_new(); + if(!BN_GF2m_mod_inv(z, &point->Z, &group->field, ctx)){ + printf("could not get the inv\n"); + return 0; + } + if(!BN_GF2m_mod_mul(x, &point->X, z, &group->field, ctx)){ + return 0; + } + if(!BN_GF2m_mod_sqr(z, z, &group->field, ctx)){ + return 0; + } + if(!BN_GF2m_mod_mul(y, &point->Y, z, &group->field, ctx)){ + return 0; + } + } + return 1; +} + +static int my_ecdh_compute_key(void *out, size_t outlen, const EC_POINT *pub_key, + EC_KEY *ecdh, void *(*KDF)(const void *in, size_t inlen, void *out, size_t *outlen)) +{ + BN_CTX *ctx; + EC_POINT *tmp=NULL; + BIGNUM *x=NULL, *y=NULL; + const BIGNUM *priv_key; + const EC_GROUP* group; + int ret= -1; + size_t buflen, len; + unsigned char *buf=NULL; + mm256_point_t mPK; + mm_256 mUK; + mm256_point_t mR; + + group = EC_KEY_get0_group(ecdh); + printf("curve_name: %d, field type: %d, degree: %d, a: %x, b: %x\n", EC_GROUP_get_curve_name(group), EC_METHOD_get_field_type(EC_GROUP_method_of(group)), EC_GROUP_get_degree(group), BN_get_word(&group->a), BN_get_word(&group->b)); + + // compute with the syscall only when the filetype is NID_X9_62_characteristic_two_field and the degree is 163 + if (!( + EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_characteristic_two_field + && EC_GROUP_get_degree(group) == 163 + )) + { + ECDH_METHOD* temp = ECDH_get_default_method(); + return temp->compute_key(out, len, pub_key, ecdh, KDF); + } + + if (outlen > INT_MAX) + { + ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_MALLOC_FAILURE); /* sort of, anyway */ + return -1; + } + + if ((ctx = BN_CTX_new()) == NULL) goto err; + BN_CTX_start(ctx); + x = BN_CTX_get(ctx); + y = BN_CTX_get(ctx); + + priv_key = EC_KEY_get0_private_key(ecdh); + if (priv_key == NULL) + { + ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_NO_PRIVATE_VALUE); + goto err; + } + + if ((tmp=EC_POINT_new(group)) == NULL) + { + ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_MALLOC_FAILURE); + goto err; + } + + bn_to_mm256(priv_key, &mUK); + + printf("%s\n", BN_bn2hex(priv_key)); + + print_mm_256(&mUK); + printf("\n"); + + EC_POINT_to_mm_point(pub_key, &mPK); + + print_EC_POINT(pub_key); + printf("\n"); + print_mm_point(&mPK); + printf("\n"); + + init_sqr_table(); + + gf2_point_mul(&mPK, &mUK, &mR, BN_get_word(&group->a), BN_get_word(&group->b)); + print_mm_point(&mR); + printf("\n"); + + if (!EC_POINT_mul(group, tmp, NULL, pub_key, priv_key, ctx)) + { + ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE); + goto err; + } + print_EC_POINT(tmp); + printf("\n"); + + + if (!get_affine(group, tmp, x, y, ctx)) + { + ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE); + goto err; + } + + buflen = (EC_GROUP_get_degree(group) + 7)/8; + len = BN_num_bytes(x); + if (len > buflen) + { + ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_INTERNAL_ERROR); + goto err; + } + if ((buf = OPENSSL_malloc(buflen)) == NULL) + { + ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_MALLOC_FAILURE); + goto err; + } + + memset(buf, 0, buflen - len); + if (len != (size_t)BN_bn2bin(x, buf + buflen - len)) + { + ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_BN_LIB); + goto err; + } + + if (KDF != 0) + { + if (KDF(buf, buflen, out, &outlen) == NULL) + { + ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_KDF_FAILED); + goto err; + } + ret = outlen; + } + else + { + /* no KDF, just copy as much as we can */ + if (outlen > buflen) + outlen = buflen; + memcpy(out, buf, outlen); + ret = outlen; + } + printf("ECC compute key done!\n"); + err: + if (tmp) EC_POINT_free(tmp); + if (ctx) BN_CTX_end(ctx); + if (ctx) BN_CTX_free(ctx); + if (buf) OPENSSL_free(buf); + return(ret); + + + /* if(1){ */ + /* ECDH_METHOD* temp = ECDH_get_default_method(); */ + /* return temp->compute_key(out, len, pub_key, ecdh, KDF); */ + /* } */ + /* return 1; */ +} + +/**************************************************************************** + * Functions to handle the engine * +*****************************************************************************/ + +static int bind_my(ENGINE *e) +{ + //const RSA_METHOD *meth1; + if(!ENGINE_set_id(e, engine_my_id) + || !ENGINE_set_name(e, engine_my_name) + || !ENGINE_set_ECDH(e, &my_ecdh) + //|| !ENGINE_set_ciphers(e, my_ciphers) + //|| !ENGINE_set_digests(e, my_digests) + || !ENGINE_set_destroy_function(e, my_destroy) + || !ENGINE_set_init_function(e, my_init) + || !ENGINE_set_finish_function(e, my_finish) + /* || !ENGINE_set_ctrl_function(e, my_ctrl) */ + /* || !ENGINE_set_cmd_defns(e, my_cmd_defns) */) + return 0; + return 1; + } + + +#ifdef ENGINE_DYNAMIC_SUPPORT +static int bind_helper(ENGINE *e, const char *id) +{ + if(id && (strcmp(id, engine_my_id) != 0)) + return 0; + if(!bind_my(e)) + return 0; + return 1; +} +IMPLEMENT_DYNAMIC_CHECK_FN() +IMPLEMENT_DYNAMIC_BIND_FN(bind_helper) +#else +static ENGINE *engine_my(void) +{ + ENGINE *ret = ENGINE_new(); + if(!ret) + return NULL; + if(!bind_my(ret)) + { + ENGINE_free(ret); + return NULL; + } + return ret; +} + +void ENGINE_load_myengine(void) +{ + /* Copied from eng_[openssl|dyn].c */ + ENGINE *toadd = engine_my(); + if(!toadd) return; + ENGINE_add(toadd); + ENGINE_free(toadd); + ERR_clear_error(); +} +#endif + + +static int my_init(ENGINE *e) +{ + printf("my_init\n"); + return 1; +} + + +static int my_finish(ENGINE *e) +{ + printf("my_finih\n"); + return 1; +} + + +static int my_destroy(ENGINE *e) +{ + printf("my_destroy\n"); + return 1; +} diff --git a/engines/zeromem/engine/myengine.h b/engines/zeromem/engine/myengine.h new file mode 100755 index 00000000..5009125d --- /dev/null +++ b/engines/zeromem/engine/myengine.h @@ -0,0 +1,175 @@ +#define INT_MAX 32767 + +#include +typedef struct ec_extra_data_st { + struct ec_extra_data_st *next; + void *data; + void *(*dup_func)(void *); + void (*free_func)(void *); + void (*clear_free_func)(void *); +} EC_EXTRA_DATA; + +typedef struct ec_key_st { + int version; + + EC_GROUP *group; + + EC_POINT *pub_key; + BIGNUM *priv_key; + + unsigned int enc_flag; + point_conversion_form_t conv_form; + + int references; + int flags; + + EC_EXTRA_DATA *method_data; +} EC_KEY; +static const char *engine_my_id = "111"; +static const char *engine_my_name = "myengine"; + + +/**************************************************************************** + * Functions to handle the engine * + ***************************************************************************/ +static int my_destroy(ENGINE *e); +static int my_init(ENGINE *e); +static int my_finish(ENGINE *e); + + +/**************************************************************************** + * Engine commands * +*****************************************************************************/ +static const ENGINE_CMD_DEFN my_cmd_defns[] = +{ + {0, NULL, NULL, 0} +}; + +static int my_ecdh_compute_key(void *out, size_t len, const EC_POINT *pub_key, +EC_KEY *ecdh, void *(*KDF)(const void *in, size_t inlen, void *out, size_t *outlen)); + +/* +some definations missing in openssl header files public accessible +*/ + +struct ec_point_st { + const EC_METHOD *meth; + + /* All members except 'meth' are handled by the method functions, + * * even if they appear generic */ + + BIGNUM X; + BIGNUM Y; + BIGNUM Z; /* Jacobian projective coordinates: + * (X, Y, Z) represents (X/Z^2, Y/Z^3) if Z != 0 */ + int Z_is_one; /* enable optimized point arithmetics for special case */ +} /* EC_POINT */; + +typedef struct ec_point_st EC_POINT; + +struct ec_group_st { + const EC_METHOD *meth; + + EC_POINT *generator; /* optional */ + BIGNUM order, cofactor; + + int curve_name;/* optional NID for named curve */ + int asn1_flag; /* flag to control the asn1 encoding */ + point_conversion_form_t asn1_form; + + unsigned char *seed; /* optional seed for parameters (appears in ASN1) */ + size_t seed_len; + + struct EC_EXTRA_DATA *extra_data; /* linked list */ + + /* The following members are handled by the method functions, + * even if they appear generic */ + + BIGNUM field; /* Field specification. + * For curves over GF(p), this is the modulus; + * for curves over GF(2^m), this is the + * irreducible polynomial defining the field. + */ + + int poly[6]; /* Field specification for curves over GF(2^m). + * The irreducible f(t) is then of the form: + * t^poly[0] + t^poly[1] + ... + t^poly[k] + * where m = poly[0] > poly[1] > ... > poly[k] = 0. + * The array is terminated with poly[k+1]=-1. + * All elliptic curve irreducibles have at most 5 + * non-zero terms. + */ + + BIGNUM a, b; /* Curve coefficients. + * (Here the assumption is that BIGNUMs can be used + * or abused for all kinds of fields, not just GF(p).) + * For characteristic > 3, the curve is defined + * by a Weierstrass equation of the form + * y^2 = x^3 + a*x + b. + * For characteristic 2, the curve is defined by + * an equation of the form + * y^2 + x*y = x^3 + a*x^2 + b. + */ + + int a_is_minus3; /* enable optimized point arithmetics for special case */ + + void *field_data1; /* method-specific (e.g., Montgomery structure) */ + void *field_data2; /* method-specific */ + int (*field_mod_func)(BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *); /* method-specific */ +} /* EC_GROUP */; + +struct ec_key_st { + int version; + + EC_GROUP *group; + + EC_POINT *pub_key; + BIGNUM *priv_key; + + unsigned int enc_flag; + point_conversion_form_t conv_form; + + int references; + int flags; + + struct EC_EXTRA_DATA *method_data; +} /* EC_KEY */; + + +struct ecdh_method + { + const char *name; + int (*compute_key)(void *key, size_t outlen, const EC_POINT *pub_key, EC_KEY *ecdh,void *(*KDF)(const void *in, size_t inlen, void *out, size_t *outlen)); +#if 0 + int (*init)(EC_KEY *eckey); + int (*finish)(EC_KEY *eckey); +#endif + int flags; + char *app_data; + }; + +static ECDH_METHOD my_ecdh = { + "myengine", + my_ecdh_compute_key, +#if 0 + NULL, /* init */ + NULL, /* finish */ +#endif + 0, /* flags */ + NULL /* app_data */ +}; + +/**************************************************************************** + * Symetric cipher and digest function registrars * +*****************************************************************************/ + +static int my_ciphers(ENGINE *e, const EVP_CIPHER **cipher,const int **nids, int nid); + +static int my_digests(ENGINE *e, const EVP_MD **digest,const int **nids, int nid); + + +static int my_cipher_nids[] ={ NID_des_cbc, NID_des_ede3_cbc, NID_desx_cbc, 0 }; +static int my_digest_nids[] ={ NID_md2, NID_md5, 0 }; + +/*__declspec(dllexport)*/ void ENGINE_load_myengine(void); + diff --git a/engines/zeromem/engine/mytest.c b/engines/zeromem/engine/mytest.c new file mode 100755 index 00000000..401aa109 --- /dev/null +++ b/engines/zeromem/engine/mytest.c @@ -0,0 +1,106 @@ +//test.c +#include +#include +#include +#include +#include +#include + +static void display_engine_list() +{ + ENGINE *h; + int loop; + + h = ENGINE_get_first(); + loop = 0; + printf("listing available engine types\n"); + while(h) + { + printf("engine %i, id = \"%s\", name = \"%s\"\n", + loop++, ENGINE_get_id(h), ENGINE_get_name(h)); + h = ENGINE_get_next(h); + } + printf("end of list\n"); + /* ENGINE_get_first() increases the struct_ref counter, so we + must call ENGINE_free() to decrease it again */ + ENGINE_free(h); +} + + +void test() +{ + ENGINE *e = NULL; + int rv; + unsigned char buf[1024]; + EVP_PKEY *evpKey; + + EC_KEY *key; + EC_POINT *pubkey; + EC_GROUP *group; + EC_builtin_curve *curves; + int crv_len; + char shareKey1[10240],shareKey2[10240]; + int ret,nid,size,i,sig_len; + int len1,len2; + + crv_len = EC_get_builtin_curves(NULL, 0); + curves = (EC_builtin_curve *)malloc(sizeof(EC_builtin_curve) * crv_len); + EC_get_builtin_curves(curves, crv_len); + nid = NID_sect163k1; + group=EC_GROUP_new_by_curve_name(nid); + + key=EC_KEY_new(); + ret=EC_KEY_set_group(key,group); + ret=EC_KEY_generate_key(key); + ret=EC_KEY_check_key(key); + pubkey = EC_KEY_get0_public_key(key); + + ENGINE_load_myengine(); + display_engine_list(); + + len1=ECDH_compute_key(shareKey1, 10240, pubkey, key, NULL); + e = ENGINE_by_id("111"); + printf("get myengine engine OK.name:%s\n",ENGINE_get_name(e)); + ENGINE_register_ECDH(e); + //rv = ENGINE_set_default(e,ENGINE_METHOD_ALL); + + + len2=ECDH_compute_key(shareKey2, 10240, pubkey, key, NULL); + + printf("len: %d, %d\n", len1, len2); + if(len1!=len2) + { + printf("err: %d, %d\n", len1, len2); + } + else + { + ret=memcmp(shareKey1,shareKey2,len1); + if(ret==0) + { + printf("right\n"); + } + else + printf("wrong\n"); + } + printf("test ok!\n"); + /*ENGINE_register_RSA(e); + rv = ENGINE_set_default(e,ENGINE_METHOD_ALL); + evpKey = EVP_PKEY_new(); + rsa = RSA_generate_key(1024,RSA_F4,NULL,NULL); + rv = EVP_PKEY_set1_RSA(evpKey,rsa); + rv = EVP_PKEY_encrypt(buf,buf,128,evpKey); +*/ +/* rv = ENGINE_finish(e); + + rv = ENGINE_free(e); + printf("test end.\n"); + return;*/ + } + +int main() +{ + test(); + return 0; +} + + diff --git a/engines/zeromem/kernel/cba-ecc.c b/engines/zeromem/kernel/cba-ecc.c new file mode 100755 index 00000000..9d44029d --- /dev/null +++ b/engines/zeromem/kernel/cba-ecc.c @@ -0,0 +1,208 @@ +#include +#include + +#include +#include + +#include +#include +#include +#include "../ec2m_kern.h" +#include "../ec.h" + +unsigned int sqr_table[1 << 16]; +struct sock *sock_fd = NULL; + +mm_256 gkey; + +void init_sqr_table(void){ + unsigned int i, j; + unsigned int t; + unsigned int n; + for(i = 0; i < sizeof(sqr_table) / sizeof(sqr_table[0]); i++){ + t = 0; + j = i; + n = 16; + while(n-- > 0){ + t = t << 2; + t |= ((j >> n) & 0x1); + } + sqr_table[i] = t; + } +} + +void import_key(void* info) { + mm_256* key; + mm_256 tkey; + + int cpu_id; + unsigned long irqs; + cpu_id = get_cpu(); + local_irq_save(irqs); + + //printk(KERN_INFO"%s on %d\n", __FUNCTION__, cpu_id); + key = (mm_256*)info; + // print value in dr0-3 previously + __asm__( + "movq %%dr0, %%rax\n\t" + "vmovq %%rax, %%xmm15\n\t" + "movq %%dr1, %%rax\n\t" + "vpinsrq $1, %%rax, %%xmm15, %%xmm15\n\t" + "movq %%dr2, %%rax\n\t" + "vmovq %%rax, %%xmm14\n\t" + "vinsertf128 $1, %%xmm14, %%ymm15, %%ymm15\n\t" + "vmovdqu %%ymm15, %0\n\t" + :"=m"(tkey) + : + : "rax", "memory" + ); + + //printk(KERN_INFO"debug regs:%016llx%016llx%016llx%016llx\n", tkey.iv[3], tkey.iv[2], tkey.iv[1], tkey.iv[0]); + //printk(KERN_INFO"key: %016llx%016llx%016llx\n", key->iv[2], key->iv[1], key->iv[0]); + gkey = *key; + + + __asm__( + "movq %0, %%dr0\n" + "movq %1, %%dr1\n" + "movq %2, %%dr2\n" + : + :"r"(key->iv[0]),"r"(key->iv[1]),"r"(key->iv[2]) + : "memory" + ); + local_irq_restore(irqs); + put_cpu(); +} + +int k_ec2m_import_key(mm_256* key) +{ + import_key(key); + smp_call_function(import_key, key, 1); + return OK; +} + +int k_ec2m_private_op(mm256_point_t* Q, mm256_point_t* P) +{ + int cpu_id; + unsigned long irqs; + cpu_id = get_cpu(); + local_irq_save(irqs); + + //printk(KERN_INFO"%s on %d\n", __FUNCTION__, cpu_id); + + __asm__ __volatile__( + "movq %%dr0, %%rax\n\t" + "vmovq %%rax, %%xmm15\n\t" + "movq %%dr1, %%rax\n\t" + "vpinsrq $1, %%rax, %%xmm15, %%xmm15\n\t" + "movq %%dr2, %%rax\n\t" + "vmovq %%rax, %%xmm14\n\t" + "vinsertf128 $1, %%xmm14, %%ymm15, %%ymm15\n\t" + : + : + : "rax", "memory" + ); + gf2_point_mul_with_preset_key(P, Q, 1, 1); + + local_irq_restore(irqs); + put_cpu(); + + return OK; +} + + +void nl_recv_msg(struct sk_buff* skb){ + struct nlmsghdr *nlh; + struct sk_buff* out; + struct ec2m_request_st* req; + struct ec2m_response_st resp; + int pid; + int size; + char *buf; + int r; + + nlh=(struct nlmsghdr*)skb->data; + size = nlmsg_len(nlh);// - NLMSG_HDRLEN; + + pid = nlh->nlmsg_pid; /*pid of sending process */ + /* printk(KERN_INFO "Netlink received a new msg from %d, size: %d\n", pid, size); */ + buf = nlmsg_data(nlh); + req = (struct ec2m_request_st*)buf; + /* printk(KERN_INFO "got a request: %d, len: %d", req->func, req->len); */ + + switch (req->func) { + case REQ_IMPORT_KEY: + { + mm_256* key; + key = (mm_256*) (buf + sizeof(struct ec2m_request_st)); + resp.result = k_ec2m_import_key(key); + size = sizeof(struct ec2m_response_st); + buf = kmalloc(size, GFP_KERNEL); + memcpy(buf, &resp, sizeof(resp)); + break; + } + case REQ_PRIVATE_OP: + { + mm256_point_t* P; + mm256_point_t Q; + P = (mm256_point_t*) (buf + sizeof(struct ec2m_request_st)); + resp.result = k_ec2m_private_op(&Q, P); + size = sizeof(struct ec2m_response_st) + sizeof(mm256_point_t); + buf = kmalloc(size, GFP_KERNEL); + memcpy(buf, &resp, sizeof(resp)); + memcpy(buf + sizeof(resp), &Q, sizeof(Q)); + break; + } + + } + + out = nlmsg_new(size, 0); + nlh = nlmsg_put(out, 0, 0, NLMSG_DONE, size, 0); + NETLINK_CB(out).dst_group = 0; /* not in mcast group */ + memcpy(nlmsg_data(nlh), buf, size); + r = nlmsg_unicast(sock_fd, out, pid); + if (r < 0){ + printk(KERN_INFO "forward msg to %d failed, err code %d\n", pid, r); + } + kfree(buf); +} + + +int init_netlink(void){ + struct netlink_kernel_cfg cfg = {0}; + cfg.input = nl_recv_msg; + sock_fd = netlink_kernel_create(&init_net, NETLINK_ECC, &cfg ); + + if(!sock_fd) + { + printk(KERN_ALERT "Error creating socket.\n"); + return -1; + } + printk(KERN_ALERT "creating socket successfully.\n"); + + return 0; +} + + + +int __init ecc_init(void) { + // init netlink + init_netlink(); + init_sqr_table(); + + return 0; +} + + +void __exit ecc_exit(void) { + // netlink clean up + if(sock_fd != NULL) + netlink_kernel_release(sock_fd); +} + + +module_init(ecc_init); +module_exit(ecc_exit); + + +MODULE_LICENSE("GPL"); diff --git a/engines/zeromem/kernel/install.sh b/engines/zeromem/kernel/install.sh new file mode 100755 index 00000000..00f78fe4 --- /dev/null +++ b/engines/zeromem/kernel/install.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +sudo rmmod ecc +sudo insmod ecc.ko +dmesg|tail diff --git a/engines/zeromem/kernel_test.c b/engines/zeromem/kernel_test.c new file mode 100755 index 00000000..fc1eab49 --- /dev/null +++ b/engines/zeromem/kernel_test.c @@ -0,0 +1,217 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "kernel_test.h" +#include "ec.h" +#include "ec2m_kern.h" +#include "util.h" + + +#define _NR_sse_switch 312 + +struct ec_point_st { + const EC_METHOD *meth; + + /* All members except 'meth' are handled by the method functions, + * even if they appear generic */ + + BIGNUM X; + BIGNUM Y; + BIGNUM Z; /* Jacobian projective coordinates: + * (X, Y, Z) represents (X/Z^2, Y/Z^3) if Z != 0 */ + int Z_is_one; /* enable optimized point arithmetics for special case */ +} /* EC_POINT */; + +int testSSE(){ + // try perform an simple packed add operation + mm_256 a, b, c; + + syscall(_NR_sse_switch, 0); + + a.iv[0] = 0; + a.iv[1] = 1; + b.iv[0] = 2; + b.iv[1] = 3; + __asm__ __volatile__ ("vmovdqu %0, %%ymm0" : : "m"(a)); + __asm__ __volatile__ ("vmovdqu %0, %%ymm1" : : "m"(b)); + __asm__ __volatile__ ("vaddpd %ymm0, %ymm1, %ymm1"); + __asm__ __volatile__ ("vmovdqu %%ymm1, %0" : "=m"(c) :); + printf("%ld, %ld\n", c.iv[0], c.iv[1]); + + //syscall(_NR_sse_switch, 0); + + return 1; +} + +void print_num(mm_256* m) +{ + int i; + int nonzero = 0; + + for (i = sizeof(mm_256) - 1; i >= 0; i--) { + if (!nonzero){ + if (m->bv[i] != 0) + nonzero = 1; + else + continue; + } + printf("%02x", m->bv[i]); + } + if (!nonzero) + printf("0"); +} + + +void print_point(mm256_point_t* p) +{ + print_num(&p->x); + printf(", "); + print_num(&p->y); + printf(", "); + print_num(&p->z); +} + +void print_ec_point(EC_POINT* p) +{ + printf("("); + BN_print_fp(stdout, &p->X); + printf(":"); + BN_print_fp(stdout, &p->Y); + printf(":"); + BN_print_fp(stdout, &p->Z); + printf(")"); +} + + + +int testAPI() +{ + int r; + int nid; + EC_KEY *key; + BIO *bio_out; + const BIGNUM* rkey; + const EC_GROUP* group; + const EC_POINT* ukey; + const EC_POINT* G, *pr; + BIGNUM* x, *y; + + BN_CTX* ctx; + mm_256 mkey; + mm256_point_t mp, mq; + mm_256 z_; + + + init_sqr_table(); + + + ctx = BN_CTX_new(); + BN_CTX_start(ctx); + x = BN_CTX_get(ctx); + y = BN_CTX_get(ctx); + + // open stdout as bio + bio_out = BIO_new_fp(stdout, BIO_NOCLOSE); + + // get curve nid + /* nid = EC_curve_nist2nid("sect163k1"); */ + nid = OBJ_sn2nid(SN_sect163k1); + + // generate the key + key = EC_KEY_new_by_curve_name(nid); + assert(key != NULL); + r = EC_KEY_generate_key(key); + assert(r == 1); + + // print key + EC_KEY_print(bio_out, key, 0); + // get group + group = EC_KEY_get0_group(key); + // get generator + G = EC_GROUP_get0_generator(group); + // get private key + rkey = EC_KEY_get0_private_key(key); + memset(&mkey, 0, sizeof(mkey)); + memcpy(&mkey, rkey->d, rkey->top * sizeof(rkey->d[0])); + print_num(&mkey); + printf("\n"); + + // get the public key + ukey = EC_KEY_get0_public_key(key); + + // init api + r = ec2m_kern_init(); + assert(r == 0); + printf("ec2m init done.\n"); + + + // import the private key + r = ec2m_import_key(&mkey); + assert(r == 0); + + // calculate r=G*k + // r should be equal to the public key + EC_POINT_get_affine_coordinates_GF2m(group, G, x, y, ctx); + memset(&mq, 0, sizeof(mq)); + memset(&mp, 0, sizeof(mp)); + memcpy(&mp.x, x->d, sizeof(x->d[0]) * x->top); + memcpy(&mp.y, y->d, sizeof(y->d[0]) * y->top); + mp.z.iv[0] = 1; + + bn_expand2(x, 3); + bn_expand2(y, 3); + + gf2_point_mul(&mp, &mkey, &mq, 1, 1); + print_mm_point(&mq); + printf("\n"); + + r = ec2m_private_operation(&mp, &mq); + assert(r == 0); + + print_mm_point(&mq); + printf("\n"); + + /* printf("inv(z): "); */ + /* gf2m_inv(&mq.z, &z_); */ + /* print_num(&z_); */ + /* printf("\n"); */ + + /* gf2_mod_mul(&mq.x, &z_, &mq.x); */ + /* gf2_mod_mul(&mq.y, &z_, &mq.y); */ + /* gf2_mod_mul(&mq.z, &z_, &mq.z); */ + /* print_mm_point(&mq); */ + /* printf("\n"); */ + + pr = EC_POINT_new(group); + EC_POINT_mul(group, pr, NULL, G, rkey, ctx); + print_ec_point(pr); + printf("\n"); + EC_POINT_get_affine_coordinates_GF2m(group, pr, x, y, ctx); + + + ec2m_kern_clean(); + + BN_CTX_end(ctx); + BN_CTX_free(ctx); + + + return 0; + +} + + +int main() +{ + testSSE(); + testAPI(); + + return 0; + +} diff --git a/engines/zeromem/kernel_test.h b/engines/zeromem/kernel_test.h new file mode 100755 index 00000000..7dbd1eee --- /dev/null +++ b/engines/zeromem/kernel_test.h @@ -0,0 +1,6 @@ +#ifndef _KERNEL_TEST_H_ +#define _KERNEL_TEST_H_ + +extern int testSSE(); + +#endif diff --git a/engines/zeromem/sys_ec2m.c b/engines/zeromem/sys_ec2m.c new file mode 100755 index 00000000..084735ac --- /dev/null +++ b/engines/zeromem/sys_ec2m.c @@ -0,0 +1,22 @@ +#include +#include "sys_ec2m.h" + +int sys_ec2m_alloc(void) +{ + return syscall(__NR_ec2m_alloc); +} + +int sys_ec2m_free(int rid) +{ + return syscall(__NR_ec2m_free, rid); +} + +int sys_ec2m_setkey(int rid, mm_256* key, int a, int b) +{ + return syscall(__NR_ec2m_setkey, rid, (void*)key, a, b); +} + +int sys_ec2m_encrypt(int rid, mm256_point_t* bufin, mm256_point_t* bufout) +{ + return syscall(__NR_ec2m_encrypt, rid, (void*)bufin, (void*)bufout); +} diff --git a/engines/zeromem/sys_ec2m.h b/engines/zeromem/sys_ec2m.h new file mode 100755 index 00000000..ec204a0a --- /dev/null +++ b/engines/zeromem/sys_ec2m.h @@ -0,0 +1,16 @@ +#ifndef _SYS_EC2M_H_ +#define _SYS_EC2M_H_ + +#define __NR_ec2m_alloc 312 +#define __NR_ec2m_free 313 +#define __NR_ec2m_setkey 314 +#define __NR_ec2m_encrypt 315 + +#include "ec.h" + +extern int sys_ec2m_alloc(void); +extern int sys_ec2m_free(int rid); +extern int sys_ec2m_setkey(int rid, mm_256* key, int a, int b); +extern int sys_ec2m_encrypt(int rid, mm256_point_t* bufin, mm256_point_t* bufout); + +#endif diff --git a/engines/zeromem/test.c b/engines/zeromem/test.c new file mode 100755 index 00000000..bedf149f --- /dev/null +++ b/engines/zeromem/test.c @@ -0,0 +1,1653 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ec.h" +#include "aes_tight.h" +#include "util.h" +#include "sys_ec2m.h" +#include "ec2m_kern.h" + +#include "test.h" + +/* + * list all embedded elliptic curves in openssl: + * # openssl ecparam -list_curves + */ +#define curve_sect163k1 "sect163k1" +#define curve_sect163r1 "sect163r1" +#define curve_sect233k1 "sect233k1" +#define curve_sect233r1 "sect233r1" + +/* Lopez-Dahab coordinates */ +#define __LD__ + +/* Affine Coordinates */ +#define __AFFINE__ + +const int sz_buf = 1024; +const int cntUS = 1000000; + +BN_CTX *ctx; +EC_GROUP *ec_group; +const EC_POINT *G; +static BIGNUM *p = NULL; +static BIGNUM *a = NULL; +static BIGNUM *b = NULL; +static BIGNUM *x = NULL; +static BIGNUM *y = NULL; +static BIGNUM *n = NULL; +static BIGNUM *h = NULL; +static int a_is_one = 0; +static int b_is_one = 0; + +int initDomainParameters(int argc, char** argv){ + ctx = BN_CTX_new(); + ec_group = EC_GROUP_new_by_curve_name(OBJ_sn2nid("sect163k1")); + p = BN_new(); + a = BN_new(); + b = BN_new(); + x = BN_new(); + y = BN_new(); + n = BN_new(); + h = BN_new(); + + assert(EC_GROUP_get_curve_GF2m(ec_group, p, a, b, NULL)); + assert(EC_GROUP_get_order(ec_group, n, NULL)); + assert(EC_GROUP_get_cofactor(ec_group, h, NULL)); + G = EC_GROUP_get0_generator(ec_group); + assert(G); + assert(EC_POINT_get_affine_coordinates_GF2m(ec_group, G, x, y, NULL)); + + if (BN_is_one(a)) + a_is_one = 1; + if (BN_is_one(b)) + b_is_one = 1; + + init_sqr_table(); + return 1; +} + +void domain_parameters_print() { + assert(p && a && b && x && y && n && h); + + printf("p = 0x %s\n", BN_bn2str(p)); + printf("a = 0x %s\n", BN_bn2str(a)); + printf("b = 0x %s\n", BN_bn2str(b)); + printf("x = 0x %s\n", BN_bn2str(x)); + printf("y = 0x %s\n", BN_bn2str(y)); + printf("n = 0x %s\n", BN_bn2str(n)); + printf("h = 0x %s\n", BN_bn2str(h)); +} + +void ec_point_set_infinity(ec_point_t *P) { + BN_one(P->X); + BN_zero(P->Y); + BN_zero(P->Z); +} + +void ec_point_set_affine_xy(ec_point_t *P, const BIGNUM *ax, const BIGNUM *ay) { + BN_copy(P->X, ax); + BN_copy(P->Y, ay); + BN_one(P->Z); +} + +void ec_point_ld_to_affine(ec_point_t *P) { +} + + +/* in Lopez-Dahab co-ordinates + * the point at infinity (oo) is (1: 0: 0) + * and -(X: Y: Z) is (X: X+Y: Z) + */ +int ec_point_is_at_infinity(const ec_point_t __LD__ *P) { + assert(P->X && P->Y && P->Z); + if (BN_is_one(P->X) && BN_is_zero(P->Y) && BN_is_zero(P->Z)) + return 1; + return 0; +} + +void ec_point_copy(ec_point_t *R, const ec_point_t *P) { + BN_copy(R->X, P->X); + BN_copy(R->Y, P->Y); + BN_copy(R->Z, P->Z); +} + +/* + * Algorithm 3.24 in "Guide to Elliptic Curve Cryptography" + * P = (X1: Y1: Z1) + * R = 2P = (X3: Y3: Z3) + */ +void ec_point_double(ec_point_t __LD__ *R, const ec_point_t __LD__ *P) { + int r; + BN_CTX *ctx = BN_CTX_new(); + const BIGNUM *X1 = P->X; + const BIGNUM *Y1 = P->Y; + const BIGNUM *Z1 = P->Z; + BIGNUM *X3 = R->X; + BIGNUM *Y3 = R->Y; + BIGNUM *Z3 = R->Z; + BIGNUM *T1 = BN_new(); + BIGNUM *T2 = BN_new(); + + debug(" 1. if P == oo, return P. "); + if (ec_point_is_at_infinity(P)) { + debug("P == oo\n"); + ec_point_copy(R, P); + return; + } else { + debug("P != oo\n"); + } + + debug(" 2. T1 = Z1^2"); + r = BN_GF2m_mod_sqr(T1, Z1, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T1)); + + debug(" 3. T2 = X1^2"); + r = BN_GF2m_mod_sqr(T2, X1, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T2)); + + debug(" 4. Z3 = T1 * T2"); + r = BN_GF2m_mod_mul(Z3, T1, T2, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(Z3)); + + debug(" 5. X3 = T2^2"); + r = BN_GF2m_mod_sqr(X3, T2, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(X3)); + + debug(" 6. T1 = T1^2"); + r = BN_GF2m_mod_sqr(T1, T1, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T1)); + + debug(" 7. T2 = T1 * b"); + if (b_is_one) + BN_copy(T2, T1); + else + r = BN_GF2m_mod_mul(T2, T1, b, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T2)); + + debug(" 8. X3 = X3 + T2"); + r = BN_GF2m_add(X3, X3, T2); + assert(r); + debug(" = %s\n", BN_bn2str(X3)); + + debug(" 9. T1 = Y1^2"); + r = BN_GF2m_mod_sqr(T1, Y1, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T1)); + + debug("10. if a==1, T1 = T1 + Z3, "); + if (a_is_one) { + debug("a == 1, T1 = T1 + Z3"); + r = BN_GF2m_add(T1, T1, Z3); + assert(r); + debug(" = %s\n", BN_bn2str(T1)); + } else { + debug("a != 1, do nothing\n"); + } + + debug("11. T1 = T1 + T2"); + r = BN_GF2m_add(T1, T1, T2); + assert(r); + debug(" = %s\n", BN_bn2str(T1)); + + debug("12. Y3 = X3 * T1"); + r = BN_GF2m_mod_mul(Y3, X3, T1, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(X3)); + + debug("13. T1 = T2 * Z3"); + r = BN_GF2m_mod_mul(T1, T2, Z3, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T1)); + + debug("14. Y3 = Y3 + T1"); + r = BN_GF2m_add(Y3, Y3, T1); + assert(r); + debug(" = %s\n", BN_bn2str(Y3)); + + debug("15. return (X3: Y3: Z3) = (%s: %s: %s)\n", BN_bn2str(X3), BN_bn2str(Y3), BN_bn2str(Z3)); + return; +} + +void ec_point_add(ec_point_t __LD__ *R, const ec_point_t __LD__ *P, const ec_point_t __AFFINE__ *Q) { + int r; + BN_CTX *ctx = BN_CTX_new(); + const BIGNUM *X1 = P->X; + const BIGNUM *Y1 = P->Y; + const BIGNUM *Z1 = P->Z; + const BIGNUM *x2 = Q->X; + const BIGNUM *y2 = Q->Y; + BIGNUM *X3 = R->X; + BIGNUM *Y3 = R->Y; + BIGNUM *Z3 = R->Z; + BIGNUM *T1 = BN_new(); + BIGNUM *T2 = BN_new(); + BIGNUM *T3 = BN_new(); + + debug(" 1. if Q == oo, return P. Q should not be oo\n"); + + debug(" 2. if P == oo, return Q. "); + if (ec_point_is_at_infinity(P)) { + debug(" P == oo, return Q\n"); + ec_point_copy(R, Q); + return; + } else { + debug(" P != oo\n"); + } + + debug(" 3. T1 = Z1 * x2"); + r = BN_GF2m_mod_mul(T1, Z1, x2, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T1)); + + debug(" 4. T2 = Z1^2"); + r = BN_GF2m_mod_sqr(T2, Z1, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T2)); + + debug(" 5. X3 = X1 + T1"); + r = BN_GF2m_add(X3, X1, T1); + assert(r); + debug(" = %s\n", BN_bn2str(X3)); + + debug(" 6. T1 = Z1 * X3"); + r = BN_GF2m_mod_mul(T1, Z1, X3, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T1)); + + debug(" 7. T3 = T2 * y2"); + r = BN_GF2m_mod_mul(T3, T2, y2, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T3)); + + debug(" 8. Y3 = Y1 + T3"); + r = BN_GF2m_add(Y3, Y1, T3); + assert(r); + debug(" = %s\n", BN_bn2str(Y3)); + + /* 9. if X3 == 0, + if Y3 == 0, (X3: Y3: Z3) = 2(x2: y2: 1) + else return oo + */ + debug(" 9. if X3 == 0 { if Y3== 0, return 2(x2: y2: 1) } else return oo\n"); + if (BN_is_zero(X3)) { + debug("X3 == 0\n"); + if (BN_is_zero(Y3)) { + debug("Y3 == 0\n"); + ec_point_double(R, P); + return; + } + } + + + debug("10. Z3 = T1^2"); + r = BN_GF2m_mod_sqr(Z3, T1, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(Z3)); + + debug("11. T3 = T1 * Y3"); + r = BN_GF2m_mod_mul(T3, T1, Y3, p, ctx); + debug(" = %s\n", BN_bn2str(T3)); + + debug("12. if a==1, T1 = T1 + T2\n"); + if (a_is_one) { + debug("a == 1, T1 = T1 + T2"); + r = BN_GF2m_add(T1, T1, T2); + debug(" = %s\n", BN_bn2str(T1)); + } + + debug("13. T2 = X3^2"); + r = BN_GF2m_mod_sqr(T2, X3, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T2)); + + + debug("14. X3 = T2 * T1"); + r = BN_GF2m_mod_mul(X3, T2, T1, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(X3)); + + debug("15. T2 = Y3^2"); + r = BN_GF2m_mod_sqr(T2, Y3, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T2)); + + debug("16. X3 = X3 + T2"); + r = BN_GF2m_add(X3, X3, T2); + assert(r); + debug(" = %s\n", BN_bn2str(X3)); + + debug("17. X3 = X3 + T3"); + r = BN_GF2m_add(X3, X3, T3); + assert(r); + debug(" = %s\n", BN_bn2str(X3)); + + debug("18. T2 = x2 * Z3"); + r = BN_GF2m_mod_mul(T2, x2, Z3, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T2)); + + debug("19. T2 = T2 + X3"); + r = BN_GF2m_add(T2, T2, X3); + assert(r); + debug(" = %s\n", BN_bn2str(T2)); + + debug("20. T1 = Z3^2"); + r = BN_GF2m_mod_sqr(T1, Z3, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T1)); + + debug("21. T3 = T3 + Z3"); + r = BN_GF2m_add(T3, T3, Z3); + assert(r); + debug(" = %s\n", BN_bn2str(T3)); + + debug("22. Y3 = T3 * T2"); + r = BN_GF2m_mod_mul(Y3, T3, T2, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(Y3)); + + debug("23. T2 = x2 + y2"); + r = BN_GF2m_add(T2, x2, y2); + assert(r); + debug(" = %s\n", BN_bn2str(T2)); + + debug("24. T3 = T1 * T2"); + r = BN_GF2m_mod_mul(T3, T1, T2, p, ctx); + assert(r); + debug(" = %s\n", BN_bn2str(T3)); + + debug("25. Y3 = Y3 + T3"); + r = BN_GF2m_add(Y3, Y3, T3); + assert(r); + debug(" = %s\n", BN_bn2str(Y3)); + + debug("26. return (X3: Y3: Z3) = (%s: %s: %s)\n", BN_bn2str(X3), BN_bn2str(Y3), BN_bn2str(Z3)); + return; +} + +void ec_point_multiply(ec_point_t __LD__ *R, const ec_point_t __AFFINE__ *P, const BIGNUM* K){ + const int t = 163; + int i; + int b; + ec_point_t Q; + debug("1. Q = infinity\n"); + ec_point_init(&Q); + BN_set_word(Q.X, 1); + BN_set_word(Q.Y, 0); + BN_set_word(Q.Z, 0); + + debug("2. for i from t - 1 downto 0 do\n"); + for(i = t - 1; i >= 0; i--){ + b = BN_is_bit_set(K, i); + if(b){ + // printf("k_%d = %d\n", i, b); + } + debug("2.1 Q = 2Q\n"); + ec_point_double(R, &Q); + ec_point_copy(&Q, R); + + debug("2.2 if ki = 1 then Q = Q + P\n"); + if(b == 1){ + ec_point_add(R, &Q, P); + ec_point_copy(&Q, R); + } + } + + debug("3. return Q\n"); + ec_point_copy(R, &Q); +} + +int testFieldArithmetic(){ + mm_256 ma, mb, mr; + char* pa, *pb, *pr; + BIGNUM* ta = BN_new(); + BIGNUM* tb = BN_new(); + BIGNUM* tr = BN_new(); + + int passed = 0; + int failed = 0; + printf("test arithmetic operations on gf2m:\n"); + + assert(BN_rand_range(ta, n)); + assert(BN_rand_range(tb, n)); + + // addition + BN_GF2m_add(tr, ta, tb); + pa = BN_bn2hex(ta); + pb = BN_bn2hex(tb); + pr = BN_bn2hex(tr); + printf("0x%s + 0x%s = 0x%s ... ", pa, pb, pr); + OPENSSL_free(pa); + OPENSSL_free(pb); + OPENSSL_free(pr); + + bn_to_mm256(ta, &ma); + bn_to_mm256(tb, &mb); + gf2_add(&ma, &mb, &mr); + if(cmp_mm_256_with_bn(&mr, tr) == 0){ + passed ++; + printf("passed!\n"); + } else { + failed ++; + mm256_to_bn(&mr, tr); + pr = BN_bn2hex(tr); + printf("failed! got %s\n", pr); + OPENSSL_free(pr); + } + + // multiplication + BN_GF2m_mod_mul(tr, ta, tb, p, ctx); + pa = BN_bn2hex(ta); + pb = BN_bn2hex(tb); + pr = BN_bn2hex(tr); + printf("0x%s * 0x%s = 0x%s ... ", pa, pb, pr); + OPENSSL_free(pa); + OPENSSL_free(pb); + OPENSSL_free(pr); + + bn_to_mm256(ta, &ma); + bn_to_mm256(tb, &mb); + gf2_mod_mul(&ma, &mb, &mr); + if(cmp_mm_256_with_bn(&mr, tr) == 0){ + passed ++; + printf("passed!\n"); + } else { + failed ++; + mm256_to_bn(&mr, tr); + pr = BN_bn2hex(tr); + printf("failed! got 0x%s\n", pr); + OPENSSL_free(pr); + } + + // square mod + + BN_GF2m_mod_sqr(tr, ta, p, ctx); + pa = BN_bn2hex(ta); + pr = BN_bn2hex(tr); + printf("0x%s ^ 2 = 0x%s ... ", pa, pr); + OPENSSL_free(pa); + OPENSSL_free(pr); + + bn_to_mm256(ta, &ma); + gf2_mod_sqr(&ma, &mr); + if(cmp_mm_256_with_bn(&mr, tr) == 0){ + passed ++; + printf("passed!\n"); + } else { + failed ++; + mm256_to_bn(&mr, tr); + pr = BN_bn2hex(tr); + printf("failed! got 0x%s\n", pr); + OPENSSL_free(pr); + } + + mm_256 mrt; + gf2_sqr(&ma, &mr, &mrt); + mm256_to_bn(&mr, tr); + pr = BN_bn2hex(tr); + mm256_to_bn(&mrt, ta); + pa = BN_bn2hex(ta); + printf("sqr: (%s, %s)\n", pa, pr); + OPENSSL_free(pr); + OPENSSL_free(pa); + + /* ma.iv[0] = 1; */ + /* ma.iv[1] = 2; */ + /* ma.iv[2] = 3; */ + /* mb.iv[0] = 1; */ + /* mb.iv[1] = 1; */ + /* mb.iv[2] = 1; */ + + /* gf2_mul(&ma, &mb, &mr, &mrt); */ + /* mm256_to_bn(&mr, tr); */ + /* pr = BN_bn2hex(tr); */ + /* mm256_to_bn(&mrt, ta); */ + /* pa = BN_bn2hex(ta); */ + /* printf("mul: (%s, %s)\n", pa, pr); */ + /* OPENSSL_free(pr); */ + /* OPENSSL_free(pa); */ + + bn_to_mm256(ta, &ma); + gf2m_inv_asm(&ma, &mr); + mm256_to_bn(&mr, tr); + pa = BN_bn2hex(ta); + pr = BN_bn2hex(tr); + printf("inv: %s, %s\n", pa, pr); + OPENSSL_free(pr); + OPENSSL_free(pa); + + bn_to_mm256(ta, &ma); + gf2m_inv(&ma, &mr); + mm256_to_bn(&mr, tr); + pa = BN_bn2hex(ta); + pr = BN_bn2hex(tr); + printf("inv: %s, %s\n", pa, pr); + OPENSSL_free(pr); + OPENSSL_free(pa); + + mb = mr; + gf2_mod_mul(&ma, &mb, &mr); + mm256_to_bn(&ma, ta); + mm256_to_bn(&mb, tb); + mm256_to_bn(&mr, tr); + pa = BN_bn2hex(ta); + pb = BN_bn2hex(tb); + pr = BN_bn2hex(tr); + printf("0x%s * 0x%s = 0x%s ... ", pa, pb, pr); + OPENSSL_free(pa); + OPENSSL_free(pb); + OPENSSL_free(pr); + + + // summary + printf("%d/%d test(s) passed.\n", passed, (passed + failed)); + + return failed; +} + +int testAES(){ + const int sz_buf = 1024; + const int sz_ymm_group = 512; + int passed = 0, failed = 0; + uint8_t key[SIZE_AES_KEY_256] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}; + uint8_t pt[SIZE_AES_BLOCK] = {'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', '!', 0x0}; + uint8_t ct[SIZE_AES_BLOCK]; + AES_KEY ssl_key; + uint8_t ssl_ct[sz_buf]; + uint8_t buf1[sz_buf], buf2[sz_buf]; + int i; + + // aes 128 + printf("AES128:\n"); + printf("plaintext: "); + printHex(pt, SIZE_AES_BLOCK); + printf("\n"); + // openssl + assert(AES_set_encrypt_key(key, 128, &ssl_key) == 0); + AES_encrypt(pt, ssl_ct, &ssl_key); + printf("ciphertext by openssl: "); + printHex(ssl_ct, SIZE_AES_BLOCK); + printf("\n"); + + // tight aes + memcpy(ct, pt, SIZE_AES_BLOCK); + tight_aes_128_set_key(key); + tight_aes_128_enc(ct); + printf("ciphertext by tight aes 128: "); + printHex(ct, SIZE_AES_BLOCK); + printf("\n"); + + if(memcmp(ssl_ct, ct, SIZE_AES_BLOCK) == 0){ + passed++; + printf("passed!\n"); + } else { + failed++; + printf("failed!\n"); + } + + // decrypt by tight aes + tight_aes_128_set_key(key); + //tight_aes_enc(ct); + tight_aes_128_dec(ct); + printf("plain by tight aes 128: "); + printHex(ct, SIZE_AES_BLOCK); + printf("\n"); + + if(memcmp(pt, ct, SIZE_AES_BLOCK) == 0){ + passed++; + printf("passed!\n"); + } else { + failed++; + printf("failed!\n"); + } + + // aes 256 + printf("AES256:\n"); + printf("plaintext: "); + printHex(pt, SIZE_AES_BLOCK); + printf("\n"); + // openssl + assert(AES_set_encrypt_key(key, 256, &ssl_key) == 0); + AES_encrypt(pt, ssl_ct, &ssl_key); + printf("ciphertext by openssl: "); + printHex(ssl_ct, SIZE_AES_BLOCK); + printf("\n"); + + // tight aes + memcpy(ct, pt, SIZE_AES_BLOCK); + tight_aes_256_set_key(key); + tight_aes_256_enc(ct); + printf("ciphertext by tight aes 256: "); + printHex(ct, SIZE_AES_BLOCK); + printf("\n"); + + if(memcmp(ssl_ct, ct, SIZE_AES_BLOCK) == 0){ + passed++; + printf("passed!\n"); + } else { + failed++; + printf("failed!\n"); + } + + // decrypt by tight aes + tight_aes_256_set_key(key); + //memcpy(ct, pt, sizeof(pt)); + //tight_aes_enc(ct); + tight_aes_256_dec(ct); + printf("plaintext by tight aes 256: "); + printHex(ct, SIZE_AES_BLOCK); + printf("\n"); + + if(memcmp(pt, ct, SIZE_AES_BLOCK) == 0){ + passed++; + printf("passed!\n"); + } else { + failed++; + printf("failed!\n"); + } + + // test encrypt ymm group + printf("encrypt ymm group:\n"); + memset(buf1, 0, sz_buf); + memset(buf2, 0, sz_buf); + memset(ssl_ct, 0, sz_buf); + for(i = 0; i < sz_ymm_group; i++) + buf1[i] = rand() & 0xff; + tight_aes_256_set_key(key); + load_ymm_group(buf1); + aes_256_enc_ymm_group(buf2); + printf("plaintext in ymm group:\n"); + for(i = 0; i < 16; i++){ + printHex(buf1 + i * 32, 32); + printf("\n"); + } + for(i = 0; i < 32; i++){ + AES_encrypt(buf1 + i * 16, ssl_ct + i * 16, &ssl_key); + } + if(memcmp(ssl_ct, buf2, sz_ymm_group) == 0){ + passed++; + printf("passed!\n"); + } else { + failed++; + printf("failed!\n"); + for(i = 0; i < 16; i++){ + printf("ymm%d\n", i); + printHex(buf2 + i * 32, 32); + printf("\n"); + printHex(ssl_ct + i * 32, 32); + printf("\n"); + } + } + + // test decrypt ymm group + printf("decrypt ymm group:\n"); + tight_aes_256_set_key(key); + aes_256_dec_ymm_group(ssl_ct); + save_ymm_group(buf2); + if(memcmp(buf1, buf2, sz_ymm_group) == 0){ + passed++; + printf("passed!\n"); + } else { + failed++; + printf("failed!\n"); + for(i = 0; i < 16; i++){ + printf("ymm%d\n", i); + printHex(buf1 + i * 32, 32); + printf("\n"); + printHex(buf2 + i * 32, 32); + printf("\n"); + } + } + + printf("%d/%d test(s) passed.\n", passed, (passed + failed)); + + return failed; +} + +struct ec_method_st { + /* Various method flags */ + int flags; + /* used by EC_METHOD_get_field_type: */ + int field_type; /* a NID */ + + /* used by EC_GROUP_new, EC_GROUP_free, EC_GROUP_clear_free, EC_GROUP_copy: */ + int (*group_init)(EC_GROUP *); + void (*group_finish)(EC_GROUP *); + void (*group_clear_finish)(EC_GROUP *); + int (*group_copy)(EC_GROUP *, const EC_GROUP *); + + /* used by EC_GROUP_set_curve_GFp, EC_GROUP_get_curve_GFp, */ + /* EC_GROUP_set_curve_GF2m, and EC_GROUP_get_curve_GF2m: */ + int (*group_set_curve)(EC_GROUP *, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *); + int (*group_get_curve)(const EC_GROUP *, BIGNUM *p, BIGNUM *a, BIGNUM *b, BN_CTX *); + + /* used by EC_GROUP_get_degree: */ + int (*group_get_degree)(const EC_GROUP *); + + /* used by EC_GROUP_check: */ + int (*group_check_discriminant)(const EC_GROUP *, BN_CTX *); +/* used by EC_POINT_new, EC_POINT_free, EC_POINT_clear_free, EC_POINT_copy: */ + int (*point_init)(EC_POINT *); + void (*point_finish)(EC_POINT *); + void (*point_clear_finish)(EC_POINT *); + int (*point_copy)(EC_POINT *, const EC_POINT *); + + /* used by EC_POINT_set_to_infinity, + * EC_POINT_set_Jprojective_coordinates_GFp, + * EC_POINT_get_Jprojective_coordinates_GFp, + * EC_POINT_set_affine_coordinates_GFp, ..._GF2m, + * EC_POINT_get_affine_coordinates_GFp, ..._GF2m, + * EC_POINT_set_compressed_coordinates_GFp, ..._GF2m: + */ + int (*point_set_to_infinity)(const EC_GROUP *, EC_POINT *); + int (*point_set_Jprojective_coordinates_GFp)(const EC_GROUP *, EC_POINT *, + const BIGNUM *x, const BIGNUM *y, const BIGNUM *z, BN_CTX *); + int (*point_get_Jprojective_coordinates_GFp)(const EC_GROUP *, const EC_POINT *, + BIGNUM *x, BIGNUM *y, BIGNUM *z, BN_CTX *); + int (*point_set_affine_coordinates)(const EC_GROUP *, EC_POINT *, + const BIGNUM *x, const BIGNUM *y, BN_CTX *); + int (*point_get_affine_coordinates)(const EC_GROUP *, const EC_POINT *, + BIGNUM *x, BIGNUM *y, BN_CTX *); + int (*point_set_compressed_coordinates)(const EC_GROUP *, EC_POINT *, + const BIGNUM *x, int y_bit, BN_CTX *); + + /* used by EC_POINT_point2oct, EC_POINT_oct2point: */ +size_t (*point2oct)(const EC_GROUP *, const EC_POINT *, point_conversion_form_t form, + unsigned char *buf, size_t len, BN_CTX *); + int (*oct2point)(const EC_GROUP *, EC_POINT *, + const unsigned char *buf, size_t len, BN_CTX *); + + /* used by EC_POINT_add, EC_POINT_dbl, ECP_POINT_invert: */ + int (*add)(const EC_GROUP *, EC_POINT *r, const EC_POINT *a, const EC_POINT *b, BN_CTX *); + int (*dbl)(const EC_GROUP *, EC_POINT *r, const EC_POINT *a, BN_CTX *); + int (*invert)(const EC_GROUP *, EC_POINT *, BN_CTX *); + + /* used by EC_POINT_is_at_infinity, EC_POINT_is_on_curve, EC_POINT_cmp: */ + int (*is_at_infinity)(const EC_GROUP *, const EC_POINT *); + int (*is_on_curve)(const EC_GROUP *, const EC_POINT *, BN_CTX *); + int (*point_cmp)(const EC_GROUP *, const EC_POINT *a, const EC_POINT *b, BN_CTX *); + + /* used by EC_POINT_make_affine, EC_POINTs_make_affine: */ + int (*make_affine)(const EC_GROUP *, EC_POINT *, BN_CTX *); + int (*points_make_affine)(const EC_GROUP *, size_t num, EC_POINT *[], BN_CTX *); + + /* used by EC_POINTs_mul, EC_POINT_mul, EC_POINT_precompute_mult, EC_POINT_have_precompute_mult + * (default implementations are used if the 'mul' pointer is 0): */ + int (*mul)(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, + size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *); + int (*precompute_mult)(EC_GROUP *group, BN_CTX *); + int (*have_precompute_mult)(const EC_GROUP *group); + + + /* internal functions */ + + /* 'field_mul', 'field_sqr', and 'field_div' can be used by 'add' and 'dbl' so that + * the same implementations of point operations can be used with different + * optimized implementations of expensive field operations: */ + int (*field_mul)(const EC_GROUP *, BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *); + int (*field_sqr)(const EC_GROUP *, BIGNUM *r, const BIGNUM *a, BN_CTX *); + int (*field_div)(const EC_GROUP *, BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *); + + int (*field_encode)(const EC_GROUP *, BIGNUM *r, const BIGNUM *a, BN_CTX *); /* e.g. to Montgomery */ + int (*field_decode)(const EC_GROUP *, BIGNUM *r, const BIGNUM *a, BN_CTX *); /* e.g. from Montgomery */ + int (*field_set_to_one)(const EC_GROUP *, BIGNUM *r, BN_CTX *); +} /* EC_METHOD */; + +typedef struct ec_extra_data_st { + struct ec_extra_data_st *next; + void *data; + void *(*dup_func)(void *); + void (*free_func)(void *); + void (*clear_free_func)(void *); +} EC_EXTRA_DATA; /* used in EC_GROUP */ + +struct ec_group_st { + const EC_METHOD *meth; + + EC_POINT *generator; /* optional */ + BIGNUM order, cofactor; + + int curve_name;/* optional NID for named curve */ + int asn1_flag; /* flag to control the asn1 encoding */ + point_conversion_form_t asn1_form; + + unsigned char *seed; /* optional seed for parameters (appears in ASN1) */ + size_t seed_len; + + EC_EXTRA_DATA *extra_data; /* linked list */ + + /* The following members are handled by the method functions, + * even if they appear generic */ + + BIGNUM field; /* Field specification. + * For curves over GF(p), this is the modulus; + * for curves over GF(2^m), this is the + * irreducible polynomial defining the field. + */ + + int poly[6]; /* Field specification for curves over GF(2^m). + * The irreducible f(t) is then of the form: + * t^poly[0] + t^poly[1] + ... + t^poly[k] + * where m = poly[0] > poly[1] > ... > poly[k] = 0. + * The array is terminated with poly[k+1]=-1. + * All elliptic curve irreducibles have at most 5 + * non-zero terms. + */ + BIGNUM a, b; /* Curve coefficients. + * (Here the assumption is that BIGNUMs can be used + * or abused for all kinds of fields, not just GF(p).) + * For characteristic > 3, the curve is defined + * by a Weierstrass equation of the form + * y^2 = x^3 + a*x + b. + * For characteristic 2, the curve is defined by + * an equation of the form + * y^2 + x*y = x^3 + a*x^2 + b. + */ + + int a_is_minus3; /* enable optimized point arithmetics for special case */ + + void *field_data1; /* method-specific (e.g., Montgomery structure) */ + void *field_data2; /* method-specific */ + int (*field_mod_func)(BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *); /* method-specific */ +} /* EC_GROUP */; + +static int gf2m_Mdouble(const EC_GROUP *group, BIGNUM *x, BIGNUM *z, BN_CTX *ctx) + { + BIGNUM *t1; + int ret = 0; + + /* Since Mdouble is static we can guarantee that ctx != NULL. */ + BN_CTX_start(ctx); + t1 = BN_CTX_get(ctx); + if (t1 == NULL) goto err; + + if (!group->meth->field_sqr(group, x, x, ctx)) goto err; + if (!group->meth->field_sqr(group, t1, z, ctx)) goto err; + if (!group->meth->field_mul(group, z, x, t1, ctx)) goto err; + if (!group->meth->field_sqr(group, x, x, ctx)) goto err; + if (!group->meth->field_sqr(group, t1, t1, ctx)) goto err; + if (!group->meth->field_mul(group, t1, &group->b, t1, ctx)) goto err; + if (!BN_GF2m_add(x, x, t1)) goto err; + + ret = 1; + + err: + BN_CTX_end(ctx); + return ret; + } + +static int gf2m_Madd(const EC_GROUP *group, const BIGNUM *x, BIGNUM *x1, BIGNUM *z1, + const BIGNUM *x2, const BIGNUM *z2, BN_CTX *ctx) + { + BIGNUM *t1, *t2; + int ret = 0; + + /* Since Madd is static we can guarantee that ctx != NULL. */ + BN_CTX_start(ctx); + t1 = BN_CTX_get(ctx); + t2 = BN_CTX_get(ctx); + if (t2 == NULL) goto err; + + if (!BN_copy(t1, x)) goto err; + if (!group->meth->field_mul(group, x1, x1, z2, ctx)) goto err; + if (!group->meth->field_mul(group, z1, z1, x2, ctx)) goto err; + if (!group->meth->field_mul(group, t2, x1, z1, ctx)) goto err; + if (!BN_GF2m_add(z1, z1, x1)) goto err; + if (!group->meth->field_sqr(group, z1, z1, ctx)) goto err; + if (!group->meth->field_mul(group, x1, z1, t1, ctx)) goto err; + if (!BN_GF2m_add(x1, x1, t2)) goto err; + + ret = 1; + + err: + BN_CTX_end(ctx); + return ret; + } + +int benchmark_EC2() { + const int cntTest = 1000; + + int i; + struct timeval ts, te; + long td; + + BIGNUM* bnsrc1[cntTest]; + BIGNUM* bnsrc2[cntTest]; + BIGNUM* bndst; + mm_256 mmsrc1[cntTest]; + mm_256 mmsrc2[cntTest]; + mm_256 mmdst; + + ec_point_t epsrc[cntTest], epdst; + BIGNUM *bnk[cntTest]; + mm256_point_t mpsrc[cntTest], mpdst; + mm_256 mk[cntTest]; + + int r; + int nid; + + EC_KEY *key; + const BIGNUM* rkey; + const EC_GROUP* group; + const EC_POINT* ukey; + const EC_POINT* G; + EC_POINT* br; + + ctx = BN_CTX_new(); + + nid = OBJ_sn2nid(SN_sect163k1); + + // generate the key + key = EC_KEY_new_by_curve_name(nid); + assert(key != NULL); + r = EC_KEY_generate_key(key); + assert(r == 1); + + group = EC_KEY_get0_group(key); + // get generator + G = EC_GROUP_get0_generator(group); + // get private key + rkey = EC_KEY_get0_private_key(key); + ukey = EC_KEY_get0_public_key(key); + br = EC_POINT_new(group); + + // 1. generate $cntTest test cases + bndst = BN_new(); + ec_point_init(&epdst); + for(i = 0; i < cntTest; i++){ + bnsrc1[i] = BN_new(); + bnsrc2[i] = BN_new(); + assert(BN_rand_range(bnsrc1[i], n)); + assert(BN_rand_range(bnsrc2[i], n)); + bn_to_mm256(bnsrc1[i], &mmsrc1[i]); + bn_to_mm256(bnsrc2[i], &mmsrc2[i]); + + bnk[i] = BN_new(); + ec_point_init(&epsrc[i]); + assert(BN_rand_range(epsrc[i].X, n)); + assert(BN_rand_range(epsrc[i].Y, n)); + assert(BN_rand_range(epsrc[i].Z, n)); + assert(BN_rand_range(bnk[i], n)); + + bn_point_to_mm_point(&epsrc[i], mpsrc + i); + bn_to_mm256(bnk[i], mk + i); + } + // do addition / multiplication / square for $cntTest times + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + BN_GF2m_add(bndst, bnsrc1[i], bnsrc2[i]); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("bignum addition: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + gf2_add(&mmsrc1[i], &mmsrc2[i], &mmdst); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("secure addition: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + BN_GF2m_mod_mul_arr(bndst, bnsrc1[i], bnsrc2[i], group->poly, ctx); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("bignum multiplication: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + gf2_mod_mul(&mmsrc1[i], &mmsrc2[i], &mmdst); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("secure multiplication: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + mm_256 mmt; + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + gf2_mul(&mmsrc1[i], &mmsrc2[i], &mmdst, &mmt); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("secure multiplication only: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + BN_GF2m_mod_sqr_arr(bndst, bnsrc1[i], group->poly, ctx); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("bignum square: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + gf2_mod_sqr(&mmsrc1[i], &mmdst); + //gf2_sqr(&mmsrc1[i], &mmdst, &t); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("secure squre: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + BN_GF2m_mod_inv(bndst, bnsrc1[i], p, ctx); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("bignum inv: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + gf2m_inv(&mmsrc1[i], &mmdst); + /* gf2_mod_sqr(&mmsrc1[i], &mmdst); */ + //gf2_sqr(&mmsrc1[i], &mmdst, &t); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("secure inv: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + gf2m_inv_asm(&mmsrc1[i], &mmdst); + /* gf2_mod_sqr(&mmsrc1[i], &mmdst); */ + //gf2_sqr(&mmsrc1[i], &mmdst, &t); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("secure inv asm: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + BIGNUM* x1, *z1, * x2, *z2; + x1 = BN_CTX_get(ctx); + z1 = BN_CTX_get(ctx); + x2 = BN_CTX_get(ctx); + z2 = BN_CTX_get(ctx); + + BN_rand(x1, EC_GROUP_get_degree(group), 0, 1); + BN_rand(z1, EC_GROUP_get_degree(group), 0, 1); + BN_rand(x2, EC_GROUP_get_degree(group), 0, 1); + BN_rand(z2, EC_GROUP_get_degree(group), 0, 1); + + gettimeofday(&ts, NULL); + // openssl point multiplication + for(i = 0; i < cntTest; i++){ + gf2m_Mdouble(group, x1, z1, ctx); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("openssl mont point dbl: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + // openssl point multiplication + for(i = 0; i < cntTest; i++){ + gf2m_Madd(group, rkey, x1, z1, x2, z2, ctx); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("openssl mont point add: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + // openssl point multiplication + for(i = 0; i < cntTest; i++){ + EC_POINT_add(group, br, G, ukey, ctx); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("openssl point add: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + gf2_point_add(mpsrc + i, mpsrc + (i + 1) % cntTest, &mpdst, 1, 1); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("secure point addition: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + // openssl point multiplication + for(i = 0; i < cntTest; i++){ + EC_POINT_dbl(group, br, G, ctx); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("openssl point doubling: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + gf2_point_dbl(mpsrc + i, &mpdst, 1, 1); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("secure point doubling: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + + gettimeofday(&ts, NULL); + // openssl point multiplication + for(i = 0; i < cntTest; i++){ + EC_POINT_mul(group, br, NULL, G, rkey, ctx); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("openssl point mul: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + + gettimeofday(&ts, NULL); + for(i = 0; i < cntTest; i++){ + gf2_point_mul(mpsrc + i, mk + i, &mpdst, 1, 1); + //gf2_point_dbl(mp + i, mr + i, 1, 1); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("secure point multiplication: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + + + ec2m_kern_init(); + ec2m_import_key(&mk[0]); + + gettimeofday(&ts, NULL); + + for(i = 0; i < cntTest; i++){ + ec2m_private_operation(mpsrc + i, &mpdst); + } + gettimeofday(&te, NULL); + td = cntUS * (te.tv_sec - ts.tv_sec) + (te.tv_usec - ts.tv_usec); + printf("kernel point multiplication: "); + printf("%d cases, %lfs used, %lfus for each cases\n", cntTest, (double)td / cntUS, (double)td / cntTest); + ec2m_kern_clean(); + + return 0; +} + +int testPointArithmetic(){ + int passed = 0, failed = 0; + BIGNUM* K; + + ec_point_t P, Q, R, T; + mm256_point_t mp, mq, mr; + mm_256 mk; + domain_parameters_print(); + + ec_point_init(&P); + ec_point_init(&Q); + ec_point_init(&R); + ec_point_init(&T); + + // point double + // special cases + // P = infinity + BN_set_word(P.X, 1); + bn_point_to_mm_point(&P, &mp); + ec_point_double(&R, &P); + gf2_point_dbl(&mp, &mr, 1, 1); + + print_bn_point(&P); + printf(" * 2 = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + + // a general case + ec_point_set_affine_xy(&P, x, y); + //BN_rand_range(P.Z, n); + bn_point_to_mm_point(&P, &mp); + + ec_point_double(&R, &P); + + gf2_point_dbl(&mp, &mr, 1, 1); + + print_bn_point(&P); + printf(" * 2 = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + // double again + ec_point_copy(&P, &R); + bn_point_to_mm_point(&P, &mp); + + ec_point_double(&R, &P); + + gf2_point_dbl(&mp, &mr, 1, 1); + + print_bn_point(&P); + printf(" * 2 = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + + // point add + + ec_point_copy(&T, &R); + // special cases + // P = infinity + BN_set_word(P.X, 1); + BN_set_word(P.Y, 0); + BN_set_word(P.Z, 0); + ec_point_copy(&Q, &T); + BN_set_word(Q.Z, 1); + bn_point_to_mm_point(&P, &mp); + bn_point_to_mm_point(&Q, &mq); + ec_point_add(&R, &P, &Q); + gf2_point_add(&mp, &mq, &mr, 1, 1); + + print_bn_point(&P); + printf(" + "); + print_bn_point(&Q); + printf(" = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + + // a general case + ec_point_copy(&P, &T); + ec_point_set_affine_xy(&Q, x, y); + bn_point_to_mm_point(&P, &mp); + bn_point_to_mm_point(&Q, &mq); + ec_point_add(&R, &P, &Q); + gf2_point_add(&mp, &mq, &mr, BN_get_word(a), BN_get_word(b)); + + print_bn_point(&P); + printf(" + "); + print_affine_bn_point(&Q); + printf(" = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + + // point multiply + ec_point_set_affine_xy(&P, x, y); + bn_point_to_mm_point(&P, &mp); + K = BN_new(); + BN_rand_range(K, n); + bn_to_mm256(K, &mk); + + ec_point_multiply(&R, &P, K); + + gf2_point_mul(&mp, &mk, &mr, BN_get_word(a), BN_get_word(b)); + + print_bn_point(&P); + printf(" * "); + printf("%s", BN_bn2str(K)); + printf(" = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + + // point multiply with key preset + __asm__ __volatile__ ("vmovdqu %0, %%ymm15" : : "m"(mk)); + gf2_point_mul_with_preset_key(&mp, &mr, BN_get_word(a), BN_get_word(b)); + + print_bn_point(&P); + printf(" * "); + printf("%s", BN_bn2str(K)); + printf(" = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + + ec2m_kern_init(); + + ec2m_import_key(&mk); + ec2m_private_operation(&mp, &mr); + print_bn_point(&P); + printf(" * "); + printf("%s", BN_bn2str(K)); + printf(" = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + ec2m_kern_clean(); + + printf("%d/%d test(s) passed.\n", passed, (passed + failed)); + + return failed; +} + +int testKernelEc2m() { + int r; + int rid; + ec_point_t P, R; + mm256_point_t mp, mr; + BIGNUM* tk = BN_new(); + mm_256 mk; + BN_rand_range(tk, n); + bn_to_mm256(tk, &mk); + + ec_point_init(&P); + ec_point_init(&R); + ec_point_set_affine_xy(&P, x, y); + bn_point_to_mm_point(&P, &mp); + + printf("alloc ec2m resource... "); + rid = sys_ec2m_alloc(); + printf(" got %d\n", rid); + if(rid < 0) + return 1; + + r = sys_ec2m_setkey(rid, &mk, BN_get_word(a), BN_get_word(b)); + printf("setkey: %d\n", r); + + printf("encrypt: %d\n", r); + // point multiply + ec_point_set_affine_xy(&P, x, y); + ec_point_multiply(&R, &P, tk); + + sys_ec2m_encrypt(rid, &mp, &mr); + + print_bn_point(&P); + printf(" * "); + printf("%s", BN_bn2str(tk)); + printf(" = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + printf(" ... passed!\n"); + } else { + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + + r = sys_ec2m_free(rid); + printf("free: %d\n", r); + return 0; +} + +int testMisc(){ + int passed = 0, failed = 0; + BIGNUM* K; + + ec_point_t P, Q, R, T; + mm256_point_t mp, mr; + mm_256 mk; + domain_parameters_print(); + + ec_point_init(&P); + ec_point_init(&Q); + ec_point_init(&R); + ec_point_init(&T); + + /* + // point double + // a general case + ec_point_set_affine_xy(&P, x, y); + BN_rand_range(P.Z, n); + BN_set_word(P.Z, 4); + bn_point_to_mm_point(&P, &mp); + + ec_point_double(&R, &P); + + gf2_point_dbl(&mp, &mr, 1, 1); + + print_bn_point(&P); + printf(" * 2 = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + + // point add + ec_point_copy(&T, &R); + // special cases + // P = infinity + BN_set_word(P.X, 1); + BN_set_word(P.Y, 0); + BN_set_word(P.Z, 0); + ec_point_copy(&Q, &T); + BN_set_word(Q.Z, 1); + bn_point_to_mm_point(&P, &mp); + bn_point_to_mm_point(&Q, &mq); + ec_point_add(&R, &P, &Q); + gf2_point_add(&mp, &mq, &mr, 1, 1); + + print_bn_point(&P); + printf(" + "); + print_bn_point(&Q); + printf(" = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + */ + + // point multiply + ec_point_set_affine_xy(&P, x, y); + bn_point_to_mm_point(&P, &mp); + K = BN_new(); + BN_rand_range(K, n); + //K->d[0] = 3; + //K->d[2] = 2; + bn_to_mm256(K, &mk); + + ec_point_multiply(&R, &P, K); + + gf2_point_mul(&mp, &mk, &mr, BN_get_word(a), BN_get_word(b)); + + print_bn_point(&P); + printf(" * "); + printf("%s", BN_bn2str(K)); + printf(" = "); + print_bn_point(&R); + if(cmp_mm_point_with_bn_point(&mr, &R) == 0){ + passed++; + printf(" ... passed!\n"); + } else { + failed++; + printf(" ... failed! got "); + print_mm_point(&mr); + printf("\n"); + } + + return failed; +} + +int benchmark_cycles(){ + mm_256 ma, mb, mr; + const int cases = 1000; + unsigned long hi_s, lo_s, hi_e, lo_e, s, e; + unsigned long td[cases]; + unsigned long t_base, t_min, t_sum, t_avg; + int i; + const char* item; + + // calculate the bases + for(i = 0; i < cases; i++){ + rdtsc_begin(hi_s, lo_s); + rdtsc_end(hi_e, lo_e); + s = (hi_s << 32) | lo_s; + e = (hi_e << 32) | lo_e; + td[i] = e - s; + } + + item = "base"; + t_min = td[0]; + t_sum = 0; + for(i = 0; i < cases; i++){ + if(t_min > td[i]){ + t_min = td[i]; + } + t_sum += td[i]; + } + t_avg = t_sum / cases; + t_base = t_min; +#ifdef KERN + printk(KERN_INFO"base: %lu\n", t_min); +#else + printf("%s: %lu, %lu, %lu\n", item, t_min, t_sum, t_avg); +#endif + + gf2_add(&ma, &mb, &mr); + for(i = 0; i < cases; i++){ + rdtsc_begin(hi_s, lo_s); + gf2_add(&ma, &mb, &mr); + rdtsc_end(hi_e, lo_e); + s = (hi_s << 32) | lo_s; + e = (hi_e << 32) | lo_e; + td[i] = e - s; + } + + item = "add"; + t_sum = 0; + t_min = td[0]; + for(i = 0; i < cases; i++){ + if(t_min > td[i]){ + t_min = td[i]; + } + t_sum += td[i]; + } + t_avg = t_sum / cases; +#ifdef KERN + printk(KERN_INFO "add: %lu, %lu\n", t_min, t_min - t_base); +#else + printf("%s: %lu, %lu, %lu, %lu\n", item, t_min, t_min - t_base, t_sum, t_avg); +#endif + + for(i = 0; i < cases; i++){ + rdtsc_begin(hi_s, lo_s); + gf2_mod_mul(&ma, &mb, &mr); + rdtsc_end(hi_e, lo_e); + s = (hi_s << 32) | lo_s; + e = (hi_e << 32) | lo_e; + td[i] = e - s; + } + + item = "mul"; + t_sum = 0; + t_min = td[0]; + for(i = 0; i < cases; i++){ + if(t_min > td[i]){ + t_min = td[i]; + } + t_sum += td[i]; + } + t_avg = t_sum / cases; +#ifdef KERN + printk(KERN_INFO "add: %lu, %lu\n", t_min, t_min - t_base); +#else + printf("%s: %lu, %lu, %lu, %lu\n", item, t_min, t_min - t_base, t_sum, t_avg); +#endif + + for(i = 0; i < cases; i++){ + rdtsc_begin(hi_s, lo_s); + gf2_mod_sqr(&ma, &mr); + rdtsc_end(hi_e, lo_e); + s = (hi_s << 32) | lo_s; + e = (hi_e << 32) | lo_e; + td[i] = e - s; + } + item = "sqr"; + t_sum = 0; + t_min = td[0]; + for(i = 0; i < cases; i++){ + if(t_min > td[i]){ + t_min = td[i]; + } + t_sum += td[i]; + } + t_avg = t_sum / cases; +#ifdef KERN + printk(KERN_INFO "add: %lu, %lu\n", t_min, t_min - t_base); +#else + printf("%s: %lu, %lu, %lu, %lu\n", item, t_min, t_min - t_base, t_sum, t_avg); +#endif + return 0; +} diff --git a/engines/zeromem/test.h b/engines/zeromem/test.h new file mode 100755 index 00000000..373f5cf0 --- /dev/null +++ b/engines/zeromem/test.h @@ -0,0 +1,17 @@ +#ifndef _TEST_H_ +#define _TEST_H_ + + +extern int initDomainParameters(int argc, char** argv); +extern int testFieldArithmetic(); +extern int testPointArithmetic(); +extern int testAES(); +extern int testKernelEc2m(); +extern int testMisc(); +extern int testEC2M(); +extern int benchmark_cycles(); + +extern int benchmark_EC2(); + + +#endif diff --git a/engines/zeromem/util.c b/engines/zeromem/util.c new file mode 100755 index 00000000..7bc5098d --- /dev/null +++ b/engines/zeromem/util.c @@ -0,0 +1,215 @@ +#include +#include +#include +#include +#include +#include "util.h" + +unsigned int sqr_table[1 << 16]; + +void print_mm_256(mm_256* m){ + /* printf("(%lu, %lu, %lu, %lu)", m->iv[3], m->iv[2], m->iv[1], m->iv[0]); */ + BIGNUM *bn = BN_new(); + mm256_to_bn(m, bn); + printf("%s", BN_bn2hex(bn)); +} + +void init_sqr_table(){ + unsigned int i, j; + unsigned int t; + unsigned int n; + for(i = 0; i < sizeof(sqr_table) / sizeof(sqr_table[0]); i++){ + t = 0; + j = i; + n = 16; + while(n-- > 0){ + t = t << 2; + t |= ((j >> n) & 0x1); + } + sqr_table[i] = t; + } +} + +void ec_point_init(ec_point_t *P) { + P->X = BN_new(); + P->Y = BN_new(); + P->Z = BN_new(); +} + +void ec_point_free(ec_point_t *P){ + OPENSSL_free(P->X); + OPENSSL_free(P->Y); + OPENSSL_free(P->Z); +} + +void bn_to_mm256(const BIGNUM* bn, mm_256* m){ + memset(m, 0, sizeof(mm_256)); + assert(bn->top <= 4); + int i; + + for(i = 0; i < bn->top; i++){ + m->iv[i] = bn->d[i]; + } +} + +void mm256_to_bn(const mm_256* m, BIGNUM* bn){ + BN_zero(bn); + int i = 4; + while(i-- > 0){ + BN_lshift(bn, bn, 64); + BN_add_word(bn, m->iv[i]); + } +} + +void bn_point_to_mm_point(const ec_point_t* src, mm256_point_t* dst){ + bn_to_mm256(src->X, &dst->x); + bn_to_mm256(src->Y, &dst->y); + bn_to_mm256(src->Z, &dst->z); +} + +void EC_POINT_to_mm_point(const ec_point_st* src, mm256_point_t* dst) +{ + bn_to_mm256(&src->X, &dst->x); + bn_to_mm256(&src->Y, &dst->y); + bn_to_mm256(&src->Z, &dst->z); +} + +void mm_point_to_EC_POINT(const mm256_point_t* src, ec_point_st* dst) +{ + mm256_to_bn(&(src->x), &dst->X); + mm256_to_bn(&(src->y), &dst->Y); + mm256_to_bn(&(src->z), &dst->Z); +} + +void mm_point_to_bn_point(const mm256_point_t* src, ec_point_t* dst){ + mm256_to_bn(&(src->x), dst->X); + mm256_to_bn(&(src->y), dst->Y); + mm256_to_bn(&(src->z), dst->Z); +} + +int cmp_mm_256_with_bn(mm_256* a, BIGNUM* bn){ + mm_256 b; + bn_to_mm256(bn, &b); + return memcmp(a, &b, sizeof(mm_256)); +} + +int cmp_mm_point_with_bn_point(mm256_point_t* a, ec_point_t* b){ + mm256_point_t t; + bn_point_to_mm_point(b, &t); + return memcmp(a, &t, sizeof(mm256_point_t)); +} + +void print_bn_point(ec_point_t* p){ + char *px, *py, *pz; + px = BN_bn2str(p->X); + py = BN_bn2str(p->Y); + pz = BN_bn2str(p->Z); + printf("(%s: %s: %s)", px, py, pz); + OPENSSL_free(px); + OPENSSL_free(py); + OPENSSL_free(pz); +} + +void print_EC_POINT(ec_point_st*p) +{ + char *px, *py, *pz; + + if(p->X.d) + px = BN_bn2str(&p->X); + else + px = ""; + if(p->Y.d) + py = BN_bn2str(&p->Y); + else + py = ""; + if(p->Z.d) + pz = BN_bn2str(&p->Z); + else + pz = ""; + + printf("(%s: %s: %s)", px, py, pz); + + if(p->X.d) + OPENSSL_free(px); + if(p->Y.d) + OPENSSL_free(py); + if(p->Z.d) + OPENSSL_free(pz); +} + +void print_mm_point(mm256_point_t* p){ + ec_point_t t; + ec_point_init(&t); + mm_point_to_bn_point(p, &t); + print_bn_point(&t); + ec_point_free(&t); +} + +void print_affine_bn_point(ec_point_t* p){ + char *px, *py; + px = BN_bn2str(p->X); + py = BN_bn2str(p->Y); + printf("(%s, %s)", px, py); + OPENSSL_free(px); + OPENSSL_free(py); +} + +void print_affine_mm_point(mm256_point_t* p){ + ec_point_t t; + ec_point_init(&t); + mm_point_to_bn_point(p, &t); + print_affine_bn_point(&t); + ec_point_free(&t); +} + +void printHex(uint8_t* str, uint32_t len){ + uint32_t i; + for(i = 0; i < len; i++){ + printf("%02x", str[i]); + } +} + +void save_ymm_group(uint8_t* buf){ + __asm__("vmovdqu %ymm0, (%rdi)\n\t" + "vmovdqu %ymm1, 32(%rdi)\n\t" + "vmovdqu %ymm2, 64(%rdi)\n\t" + "vmovdqu %ymm3, 96(%rdi)\n\t" + "vmovdqu %ymm4, 128(%rdi)\n\t" + "vmovdqu %ymm5, 160(%rdi)\n\t" + "vmovdqu %ymm6, 192(%rdi)\n\t" + "vmovdqu %ymm7, 224(%rdi)\n\t" + "vmovdqu %ymm8, 256(%rdi)\n\t" + "vmovdqu %ymm9, 288(%rdi)\n\t" + "vmovdqu %ymm10, 320(%rdi)\n\t" + "vmovdqu %ymm11, 352(%rdi)\n\t" + "vmovdqu %ymm12, 384(%rdi)\n\t" + "vmovdqu %ymm13, 416(%rdi)\n\t" + "vmovdqu %ymm14, 448(%rdi)\n\t" + "vmovdqu %ymm15, 480(%rdi)\n\t" + ); + __asm__("" ::: "memory"); +} + +void load_ymm_group(uint8_t* buf){ + __asm__("vmovdqu (%rdi), %ymm0\n\t" + "vmovdqu 32(%rdi), %ymm1\n\t" + "vmovdqu 64(%rdi), %ymm2\n\t" + "vmovdqu 96(%rdi), %ymm3\n\t" + "vmovdqu 128(%rdi), %ymm4\n\t" + "vmovdqu 160(%rdi), %ymm5\n\t" + "vmovdqu 192(%rdi), %ymm6\n\t" + "vmovdqu 224(%rdi), %ymm7\n\t" + "vmovdqu 256(%rdi), %ymm8\n\t" + "vmovdqu 288(%rdi), %ymm9\n\t" + "vmovdqu 320(%rdi), %ymm10\n\t" + "vmovdqu 352(%rdi), %ymm11\n\t" + "vmovdqu 384(%rdi), %ymm12\n\t" + "vmovdqu 416(%rdi), %ymm13\n\t" + "vmovdqu 448(%rdi), %ymm14\n\t" + "vmovdqu 480(%rdi), %ymm15\n\t" + ); + __asm__("" ::: "memory"); +} + +void dummy_print(const char* format, ...){ +} diff --git a/engines/zeromem/util.h b/engines/zeromem/util.h new file mode 100755 index 00000000..a54b72eb --- /dev/null +++ b/engines/zeromem/util.h @@ -0,0 +1,82 @@ +#ifndef _UTIL_H_ +#define _UTIL_H_ + +#include "ec.h" +#include + +//#define DEBUG + +//#define PRINT_DEC +#ifdef PRINT_DEC +#define BN_bn2str(bn) BN_bn2dec(bn) +#else +#define BN_bn2str(bn) BN_bn2hex(bn) +#endif + +extern void dummy_print(const char* format, ...); + +#ifdef DEBUG +#define debug printf +#else +#define debug dummy_print +#endif + +extern unsigned int sqr_table[1 << 16]; + +#define rdtsc_begin(hi, lo)\ + asm volatile ("CPUID\n\t"\ + "RDTSCP\n\t"\ + "movq %%rdx, %0\n\t"\ + "movq %%rax, %1\n\t" : "=r" (hi), "=r" (lo) :: "%rax", "%rbx", "%rcx", "%rdx"); + +#define rdtsc_end(hi, lo)\ + asm volatile ("RDTSCP\n\t"\ + "movq %%rdx, %0\n\t"\ + "movq %%rax, %1\n\t"\ + "CPUID\n\t" : "=r" (hi), "=r" (lo) :: "%rax", "%rbx", "%rcx", "%rdx"); + +typedef struct { + BIGNUM *X; + BIGNUM *Y; + BIGNUM *Z; +} ec_point_t; + +typedef struct{ + const struct EC_METHOD *meth; + + /* All members except 'meth' are handled by the method functions, + * even if they appear generic */ + + BIGNUM X; + BIGNUM Y; + BIGNUM Z; /* Jacobian projective coordinates: + * (X, Y, Z) represents (X/Z^2, Y/Z^3) if Z != 0 */ + int Z_is_one; /* enable optimized point arithmetics for special case */ +} ec_point_st /* EC_POINT */; + +extern void init_sqr_table(); +extern void bn_to_mm256(const BIGNUM* bn, mm_256 *m); +extern void mm256_to_bn(const mm_256 *m, BIGNUM* bn); +extern void bn_point_to_mm_point(const ec_point_t* src, mm256_point_t* dst); +extern void mm_point_to_bn_point(const mm256_point_t* src, ec_point_t* dst); +extern void EC_POINT_to_mm_point(const ec_point_st* src, mm256_point_t* dst); +extern void mm_point_to_EC_POINT(const mm256_point_t* src, ec_point_st* dst); + +extern void ec_point_init(ec_point_t *P); +extern void ec_point_free(ec_point_t *P); + +extern int cmp_mm_256_with_bn(mm_256* a, BIGNUM* bn); +extern int cmp_mm_point_with_bn_point(mm256_point_t* a, ec_point_t* b); + +extern void print_affine_bn_point(ec_point_t* p); +extern void print_affine_mm_point(mm256_point_t* p); +extern void print_bn_point(ec_point_t* p); +extern void print_mm_point(mm256_point_t* p); +extern void print_EC_POINT(ec_point_st* p); + +extern void printHex(uint8_t* str, uint32_t len); + +extern void save_ymm_group(uint8_t* buf); +extern void load_ymm_group(uint8_t* buf); + +#endif diff --git a/include/openssl/asn1.h b/include/openssl/asn1.h index 7cf61161..9e850a37 100644 --- a/include/openssl/asn1.h +++ b/include/openssl/asn1.h @@ -956,6 +956,7 @@ int ERR_load_ASN1_strings(void); # define ASN1_F_I2D_ASN1_BIO_STREAM 211 # define ASN1_F_I2D_DSA_PUBKEY 161 # define ASN1_F_I2D_EC_PUBKEY 181 +# define ASN1_F_I2D_PAILLIER_PUBKEY 101 # define ASN1_F_I2D_PRIVATEKEY 163 # define ASN1_F_I2D_PUBLICKEY 164 # define ASN1_F_I2D_RSA_PUBKEY 165 diff --git a/include/openssl/evp.h b/include/openssl/evp.h index 3d7e4f53..a73f0076 100644 --- a/include/openssl/evp.h +++ b/include/openssl/evp.h @@ -100,6 +100,7 @@ # define EVP_PKEY_CMAC NID_cmac # define EVP_PKEY_TLS1_PRF NID_tls1_prf # define EVP_PKEY_HKDF NID_hkdf +# define EVP_PKEY_PAILLIER NID_paillier #ifdef __cplusplus extern "C" { @@ -445,6 +446,11 @@ typedef int (EVP_PBE_KEYGEN) (EVP_CIPHER_CTX *ctx, const char *pass, (char *)(eckey)) # endif +# ifndef OPENSSL_NO_PAILLIER +# define EVP_PKEY_assign_PAILLIER(pkey,paillier) EVP_PKEY_assign((pkey),EVP_PKEY_PAILLIER,\ + (char *)(paillier)) +# endif + /* Add some extra combinations */ # define EVP_get_digestbynid(a) EVP_get_digestbyname(OBJ_nid2sn(a)) # define EVP_get_digestbyobj(a) EVP_get_digestbynid(OBJ_obj2nid(a)) @@ -1000,6 +1006,12 @@ int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, struct ec_key_st *key); struct ec_key_st *EVP_PKEY_get0_EC_KEY(EVP_PKEY *pkey); struct ec_key_st *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey); # endif +# ifndef OPENSSL_NO_PAILLIER +struct paillier_st; +int EVP_PKEY_set1_PAILLIER(EVP_PKEY *pkey, struct paillier_st *key); +struct paillier_st *EVP_PKEY_get0_PAILLIER(EVP_PKEY *pkey); +struct paillier_st *EVP_PKEY_get1_PAILLIER(EVP_PKEY *pkey); +# endif EVP_PKEY *EVP_PKEY_new(void); int EVP_PKEY_up_ref(EVP_PKEY *pkey); @@ -1572,6 +1584,7 @@ int ERR_load_EVP_strings(void); # define EVP_F_EVP_PKEY_GET0_DSA 120 # define EVP_F_EVP_PKEY_GET0_EC_KEY 131 # define EVP_F_EVP_PKEY_GET0_HMAC 183 +# define EVP_F_EVP_PKEY_GET0_PAILLIER 172 # define EVP_F_EVP_PKEY_GET0_RSA 121 # define EVP_F_EVP_PKEY_KEYGEN 146 # define EVP_F_EVP_PKEY_KEYGEN_INIT 147 @@ -1616,6 +1629,7 @@ int ERR_load_EVP_strings(void); # define EVP_R_EXPECTING_A_DH_KEY 128 # define EVP_R_EXPECTING_A_DSA_KEY 129 # define EVP_R_EXPECTING_A_EC_KEY 142 +# define EVP_R_EXPECTING_A_PAILLIER 176 # define EVP_R_FIPS_MODE_NOT_SUPPORTED 167 # define EVP_R_ILLEGAL_SCRYPT_PARAMETERS 171 # define EVP_R_INITIALIZATION_ERROR 134 diff --git a/include/openssl/gmskf.h b/include/openssl/gmskf.h index 902028d6..5c2082b0 100644 --- a/include/openssl/gmskf.h +++ b/include/openssl/gmskf.h @@ -50,6 +50,7 @@ #ifndef HEADER_GMSKF_H #define HEADER_GMSKF_H +#include #include #include diff --git a/include/openssl/paillier.h b/include/openssl/paillier.h index d25a09b7..5edb975b 100644 --- a/include/openssl/paillier.h +++ b/include/openssl/paillier.h @@ -74,8 +74,10 @@ int PAILLIER_decrypt(BIGNUM *out, const BIGNUM *in, PAILLIER *key); int PAILLIER_ciphertext_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, PAILLIER *key); int PAILLIER_ciphertext_scalar_mul(BIGNUM *r, const BIGNUM *scalar, const BIGNUM *a, PAILLIER *key); -DECLARE_ASN1_ENCODE_FUNCTIONS_const(PAILLIER, PAILLIER_PUBLIC_KEY) -DECLARE_ASN1_ENCODE_FUNCTIONS_const(PAILLIER, PAILLIER_PRIVATE_KEY) +int PAILLIER_up_ref(PAILLIER *key); + +DECLARE_ASN1_ENCODE_FUNCTIONS_const(PAILLIER, PaillierPrivateKey) +DECLARE_ASN1_ENCODE_FUNCTIONS_const(PAILLIER, PaillierPublicKey) /* BEGIN ERROR CODES */ /* diff --git a/include/openssl/pem3.h b/include/openssl/pem3.h index baa137d6..6b951681 100644 --- a/include/openssl/pem3.h +++ b/include/openssl/pem3.h @@ -79,12 +79,12 @@ extern "C" { #define PEM_STRING_BB1IBE_MASTER "BB1IBE MASTER SECRET" #define PEM_STRING_BB1IBE_PRIVATE "BB1IBE PRIVATE KEY" -/* -DECLARE_PEM_rw_cb(PaillierPrivateKey, PAILLIER) -DECLARE_PEM_rw(PaillierPrivateKey, PAILLIER) -DECLARE_PEM_rw_cb(CPK_PUBLIC_PARAM, CPK) -DECLARE_PEM_rw_cb(CPK_PUBLIC_PARAMS, CPK) -*/ + +# ifndef OPENSSL_NO_PAILLIER +DECLARE_PEM_rw_cb(PAILLIERPrivateKey, PAILLIER) +DECLARE_PEM_rw_const(PAILLIERPublicKey, PAILLIER) +DECLARE_PEM_rw(PAILLIER_PUBKEY, PAILLIER) +# endif #ifdef __cplusplus diff --git a/include/openssl/serpent.h b/include/openssl/serpent.h new file mode 100644 index 00000000..e649904b --- /dev/null +++ b/include/openssl/serpent.h @@ -0,0 +1,38 @@ +#ifndef MYSERPENT_H +#define MYSERPENT_H +unsigned char takebit(unsigned char bit_num); +unsigned long int sb(char sb_num,unsigned long int sb_in_long); +void linear(IN unsigned long int *li_0,IN unsigned long int *li_1,IN unsigned long int *li_2,IN unsigned long int *li_3,OUT unsigned long int *lo_0,OUT unsigned long int *lo_1,OUT unsigned long int *lo_2,OUT unsigned long int *lo_3); +void IP(IN unsigned long int *ip_i0,IN unsigned long int *ip_i1,IN unsigned long int *ip_i2,IN unsigned long int *ip_i3,OUT unsigned long int *ip_o0,OUT unsigned long int *ip_o1,OUT unsigned long int *ip_o2,OUT unsigned long int *ip_o3); +void FP(IN unsigned long int *fp_i0,IN unsigned long int *fp_i1,IN unsigned long int *fp_i2,IN unsigned long int *fp_i3,OUT unsigned long int *fp_o0,OUT unsigned long int *fp_o1,OUT unsigned long int *fp_o2,OUT unsigned long int *fp_o3); +extern char sb0(char sb0_in); +extern char sb1(char sb1_in); +extern char sb2(char sb2_in); +extern char sb3(char sb3_in); +extern char sb4(char sb4_in); +extern char sb5(char sb5_in); +extern char sb6(char sb6_in); +extern char sb7(char sb7_in); +#define rotl(x,n) (((x) << ((int)(n))) | ((x) >> (32 - (int)(n)))) +#define rotr(x,n) (((x) >> ((int)(n))) | ((x) << (32 - (int)(n)))) + +#endif + +/* +The following should be implemented + +#define SERPENT_KEY_LENGTH ?? +#define SERPENT_BLOCK_SIZE ?? +#define SERPENT_IV_LENGTH (SERPENT_BLOCK_SIZE) +#define SERPENT_NUM_ROUNDS ?? + +typedef struct { + uint32_t rk[SMS4_NUM_ROUNDS]; +} serpent_key_t; + +void serpent_set_encrypt_key(serpent_key_t *key, const unsigned char *user_key); +void serpent_set_decrypt_key(serpent_key_t *key, const unsigned char *user_key); +void serpent_encrypt(const unsigned char *in, unsigned char *out, const serpent_key_t *key); +void serpent_decrypt(const unsigned char *in, unsigned char *out, const serpent_key_t *key); + +*/ diff --git a/include/openssl/speck.h b/include/openssl/speck.h new file mode 100644 index 00000000..899373a8 --- /dev/null +++ b/include/openssl/speck.h @@ -0,0 +1,48 @@ +#ifndef SPECK_H +#define SPECK_H + +/* +* define speck type to use +*(one of SPECK_32_64, SPECK_64_128, SPECK_128_256) +*/ +#define SPECK_32_64 + +#ifdef SPECK_32_64 +#define SPECK_TYPE uint16_t +#define SPECK_ROUNDS 22 +#define SPECK_KEY_LEN 4 +#endif + +#ifdef SPECK_64_128 +#define SPECK_TYPE uint32_t +#define SPECK_ROUNDS 27 +#define SPECK_KEY_LEN 4 +#endif + +#ifdef SPECK_128_256 +#define SPECK_TYPE uint64_t +#define SPECK_ROUNDS 34 +#define SPECK_KEY_LEN 4 +#endif + +#define num_word sizeof(SPECK_TYPE) +#include +#include +#include +#ifdef __cplusplus +extern "C" { +#endif + + typedef struct { + unsigned char rk[num_word]; + } speck_key_t; + + void speck_set_encrypt_key(speck_key_t *key, const unsigned char *user_key); + void speck_expand(SPECK_TYPE const K[SPECK_KEY_LEN], SPECK_TYPE S[SPECK_ROUNDS]); + void speck_encrypt(SPECK_TYPE const pt[2], SPECK_TYPE ct[2], SPECK_TYPE const K[SPECK_ROUNDS]); + void speck_decrypt(SPECK_TYPE const ct[2], SPECK_TYPE pt[2], SPECK_TYPE const K[SPECK_ROUNDS]); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/openssl/ssl.h b/include/openssl/ssl.h index 8d75d53e..9ad4af3a 100644 --- a/include/openssl/ssl.h +++ b/include/openssl/ssl.h @@ -155,6 +155,9 @@ extern "C" { # define SSL_TXT_CAMELLIA "CAMELLIA" # define SSL_TXT_CHACHA20 "CHACHA20" # define SSL_TXT_GOST "GOST89" +# define SSL_TXT_SMS4 "SMS4" +# define SSL_TXT_SMS4_GCM "SMS4GCM" +# define SSL_TXT_SMS4_CCM "SMS4CCM" # define SSL_TXT_MD5 "MD5" # define SSL_TXT_SHA1 "SHA1" @@ -165,11 +168,13 @@ extern "C" { # define SSL_TXT_GOST89MAC12 "GOST89MAC12" # define SSL_TXT_SHA256 "SHA256" # define SSL_TXT_SHA384 "SHA384" +# define SSL_TXT_SM3 "SM3" # define SSL_TXT_SSLV3 "SSLv3" # define SSL_TXT_TLSV1 "TLSv1" # define SSL_TXT_TLSV1_1 "TLSv1.1" # define SSL_TXT_TLSV1_2 "TLSv1.2" +# define SSL_TXT_GMSV1_1 "GMSv1.1" # define SSL_TXT_ALL "ALL" diff --git a/include/openssl/x509.h b/include/openssl/x509.h index c8996f35..343a5a40 100644 --- a/include/openssl/x509.h +++ b/include/openssl/x509.h @@ -26,6 +26,7 @@ # include # include # include +# include # if OPENSSL_API_COMPAT < 0x10100000L # include @@ -393,6 +394,14 @@ int i2d_RSAPublicKey_fp(FILE *fp, RSA *rsa); RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa); int i2d_RSA_PUBKEY_fp(FILE *fp, RSA *rsa); # endif +# ifndef OPENSSL_NO_PAILLIER +PAILLIER *d2i_PaillierPrivateKey_fp(FILE *fp, PAILLIER **paillier); +int i2d_PaillierPrivateKey_fp(FILE *fp, PAILLIER *paillier); +PAILLIER *d2i_PaillierPublicKey_fp(FILE *fp, PAILLIER **paillier); +int i2d_PaillierPublicKey_fp(FILE *fp, PAILLIER *paillier); +PAILLIER *d2i_PAILLIER_PUBKEY_fp(FILE *fp, PAILLIER **paillier); +int i2d_PAILLIER_PUBKEY_fp(FILE *fp, PAILLIER *paillier); +# endif # ifndef OPENSSL_NO_DSA DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa); int i2d_DSA_PUBKEY_fp(FILE *fp, DSA *dsa); @@ -431,6 +440,14 @@ int i2d_RSAPublicKey_bio(BIO *bp, RSA *rsa); RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa); int i2d_RSA_PUBKEY_bio(BIO *bp, RSA *rsa); # endif +# ifndef OPENSSL_NO_PAILLIER +PAILLIER *d2i_PaillierPrivateKey_bio(BIO *bp, PAILLIER **paillier); +int i2d_PaillierPrivateKey_bio(BIO *bp, PAILLIER *paillier); +PAILLIER *d2i_PaillierPublicKey_bio(BIO *bp, PAILLIER **paillier); +int i2d_PaillierPublicKey_bio(BIO *bp, PAILLIER *paillier); +PAILLIER *d2i_PAILLIER_PUBKEY_bio(BIO *bp, PAILLIER **paillier); +int i2d_PAILLIER_PUBKEY_bio(BIO *bp, PAILLIER *paillier); +# endif # ifndef OPENSSL_NO_DSA DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa); int i2d_DSA_PUBKEY_bio(BIO *bp, DSA *dsa); @@ -513,6 +530,11 @@ DSA *d2i_DSA_PUBKEY(DSA **a, const unsigned char **pp, long length); int i2d_EC_PUBKEY(EC_KEY *a, unsigned char **pp); EC_KEY *d2i_EC_PUBKEY(EC_KEY **a, const unsigned char **pp, long length); # endif +# ifndef OPENSSL_NO_PAILLIER +int i2d_PAILLIER_PUBKEY(PAILLIER *a, unsigned char **pp); +PAILLIER *d2i_PAILLIER_PUBKEY(PAILLIER **a, const unsigned char **pp, long length); +# endif + DECLARE_ASN1_FUNCTIONS(X509_SIG) void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg, @@ -762,7 +784,7 @@ int X509_print_ex_fp(FILE *bp, X509 *x, unsigned long nmflag, int X509_print_fp(FILE *bp, X509 *x); int X509_CRL_print_fp(FILE *bp, X509_CRL *x); int X509_REQ_print_fp(FILE *bp, X509_REQ *req); -int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent, +int X509_NAMpaillierE_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent, unsigned long flags); # endif diff --git a/test/build.info b/test/build.info index 602f95ef..341792b9 100644 --- a/test/build.info +++ b/test/build.info @@ -20,7 +20,8 @@ IF[{- !$disabled{tests} -}] sm3test sms4test kdf2test eciestest ffxtest sm2test \ pailliertest cpktest otptest gmapitest ec2test \ bfibetest bb1ibetest sm9test \ - saftest sdftest skftest softest zuctest + saftest sdftest skftest softest zuctest \ + serpenttest specktest SOURCE[aborttest]=aborttest.c INCLUDE[aborttest]=../include @@ -363,6 +364,14 @@ IF[{- !$disabled{tests} -}] INCLUDE[zuctest]=../include DEPEND[zuctest]=../libcrypto + SOURCE[serpenttest]=serpenttest.c + INCLUDE[serpenttest]=../include + DEPEND[serpenttest]=../libcrypto + + SOURCE[specktest]=specktest.c + INCLUDE[specktest]=../include + DEPEND[specktest]=../libcrypto + IF[{- !$disabled{shared} -}] PROGRAMS_NO_INST=shlibloadtest SOURCE[shlibloadtest]=shlibloadtest.c diff --git a/test/cpktest.c b/test/cpktest.c index 8f67eaa9..71b5db7c 100644 --- a/test/cpktest.c +++ b/test/cpktest.c @@ -90,7 +90,6 @@ int main(int argc, char **argv) { int r, i; KDF_FUNC kdf = NULL; - EC_GROUP *ec_group = NULL; EC_KEY *ec_key = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY *pub_key = NULL; diff --git a/test/p b/test/p new file mode 100644 index 00000000..9c73fff5 --- /dev/null +++ b/test/p @@ -0,0 +1,69 @@ +#! /usr/bin/env perl +# Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + + +use strict; +use warnings; + +use File::Spec::Functions qw/catfile/; +use File::Copy; +use File::Compare qw/compare_text/; +use File::Basename; +use OpenSSL::Test qw/:DEFAULT srctop_file/; + +setup("test_enc"); + +# We do it this way, because setup() may have moved us around, +# so the directory portion of $0 might not be correct any more. +# However, the name hasn't changed. +my $testsrc = srctop_file("test","recipes",basename($0)); + +my $test = catfile(".", "p"); + +my $cmd = "gmssl"; + +my @ciphers = + map { s/^\s+//; s/\s+$//; split /\s+/ } + run(app([$cmd, "list", "-cipher-commands"]), capture => 1); + +plan tests => 1 + (scalar @ciphers)*2; + +my $init = ok(copy($testsrc,$test)); + +if (!$init) { + diag("Trying to copy $testsrc to $test : $!"); +} + + SKIP: { + skip "Not initialized, skipping...", 11 unless $init; + + foreach my $c (@ciphers) { + my %variant = ("$c" => [], + "$c base64" => [ "-a" ]); + + foreach my $t (sort keys %variant) { + my $cipherfile = "$test.$c.cipher"; + my $clearfile = "$test.$c.clear"; + my @e = ( "$c", "-bufsize", "113", @{$variant{$t}}, "-e", "-k", "test" ); + my @d = ( "$c", "-bufsize", "157", @{$variant{$t}}, "-d", "-k", "test" ); + if ($c eq "cat") { + $cipherfile = "$test.cipher"; + $clearfile = "$test.clear"; + @e = ( "enc", @{$variant{$t}}, "-e" ); + @d = ( "enc", @{$variant{$t}}, "-d" ); + } + + ok(run(app([$cmd, @e, "-in", $test, "-out", $cipherfile])) + && run(app([$cmd, @d, "-in", $cipherfile, "-out", $clearfile])) + && compare_text($test,$clearfile) == 0, $t); + unlink $cipherfile, $clearfile; + } + } +} + +unlink $test; diff --git a/test/pailliertest.c b/test/pailliertest.c index 3c7233e7..ec1b235f 100644 --- a/test/pailliertest.c +++ b/test/pailliertest.c @@ -63,7 +63,7 @@ int main(int argc, char **argv) # include # include -static int PAILLIER_test(int verbose) +static int test_paillier(int verbose) { int ret = 0; int kbits = 2048; @@ -179,6 +179,7 @@ end: int main(int argc, char **argv) { int err = 0; + if (!test_paillier(2)) err++; return err; } #endif diff --git a/test/recipes/05-test_serpenet.t b/test/recipes/05-test_serpenet.t new file mode 100644 index 00000000..c1e46457 --- /dev/null +++ b/test/recipes/05-test_serpenet.t @@ -0,0 +1,12 @@ +#! /usr/bin/env perl +# Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + + +use OpenSSL::Test::Simple; + +simple_test("test_serpent", "serpenttest", "serpent"); diff --git a/test/recipes/05-test_speck.t b/test/recipes/05-test_speck.t new file mode 100644 index 00000000..c35584bb --- /dev/null +++ b/test/recipes/05-test_speck.t @@ -0,0 +1,12 @@ +#! /usr/bin/env perl +# Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + + +use OpenSSL::Test::Simple; + +simple_test("test_speck", "specktest", "speck"); diff --git a/test/serpenttest.c b/test/serpenttest.c new file mode 100644 index 00000000..c4708b33 --- /dev/null +++ b/test/serpenttest.c @@ -0,0 +1,282 @@ +#include +#include +#include + +#include "../e_os.h" + +#ifdef OPENSSL_NO_SERPENT +int main(int argc, char **argv) +{ + printf("No Serpent support\n"); + return 0; +} +#else + +#include + +int main(int argc, char* argv[]){ + + unsigned long int key_0,key_1,key_2,key_3; //128bit key input + int i; + unsigned long int p_0,p_1,p_2,p_3; //plain data in + unsigned long int c_0,c_1,c_2,c_3; //cipher data out + unsigned long int wi[8] = {0}; //pre_key -8~-1 + unsigned long int w[132] = {0};//pre_key 0~131 + unsigned long int sb_in[132] = {0}; //sbox input after data_twist1 + unsigned long int sb_out[132] = {0};//sbox output + unsigned long int k[132] = {0}; //sub_key + + unsigned long int b[132] = {0}; //round input and result + unsigned long int xor[132] = {0}; //round data after xor + unsigned long int sbox[132] = {0}; //round data after sbox + unsigned long int li[132] = {0}; //round data for linear transformation input,sbox output after FP + unsigned long int lo[132] = {0}; //round data for linear transformation output,will goto IP + + unsigned long int tmp_0,tmp_4,tmp_5; + //here we start to record detail data + FILE *fp; + fp = fopen("serpent_data.sti","w"); + + tmp_4 = 0x1; + + //detail data initial + while(1){ + for( i = 0; i < 132; i++){ + w[i] = 0x0; + sb_in[i] = 0x0; + sb_out[i] = 0x0; + k[i] = 0x0; + b[i] = 0x0; + xor[i] = 0x0; + sbox[i] = 0x0; + li[i] = 0x0; + lo[i] = 0x0; + } + +//step 0, key & plain data assignment + + printf("============================================ \n"); + printf("=======SERPENT-1 START, RUN_CNT = %d ======= \n",tmp_4); + printf("============================================ \n"); + printf("=======INPUT KEYS======= \n"); + printf("=======128bit key======= \n"); + + printf("PLEASE INPUT KEY_0 IN HEX \n"); scanf_s("%x",&key_0); + printf("PLEASE INPUT KEY_1 IN HEX \n"); scanf_s("%x",&key_1); + printf("PLEASE INPUT KEY_2 IN HEX \n"); scanf_s("%x",&key_2); + printf("PLEASE INPUT KEY_3 IN HEX \n"); scanf_s("%x",&key_3); + + printf("PLEASE INPUT P_0 IN HEX \n"); scanf_s("%x",&p_0); + printf("PLEASE INPUT P_1 IN HEX \n"); scanf_s("%x",&p_1); + printf("PLEASE INPUT P_2 IN HEX \n"); scanf_s("%x",&p_2); + printf("PLEASE INPUT P_3 IN HEX \n"); scanf_s("%x",&p_3); + +//step 1, sub-key generation +//setp 1-1, generate 256bit full-length key and start to generate wi[0]~wi[7] + + wi[0] = key_0; + wi[1] = key_1; + wi[2] = key_2; + wi[3] = key_3; + //padding the key to 256 bit + wi[4] = 0x00000000; + wi[5] = 0x00000000; + wi[6] = 0x00000000; + wi[7] = 0x80000000; + +//setp 1-2, generate w[0]~w[7] with wi[0]~wi[7] +//w[i]=(w[i-8]^w[i-5]^w[i-3]^w[i-1]^phai^i)<<<11 +//w[-8]-->wi[0] +//w[-7]-->wi[1] +//w[-6]-->wi[2] +//w[-5]-->wi[3] +//w[-4]-->wi[4] +//w[-3]-->wi[5] +//w[-2]-->wi[6] +//w[-1]-->wi[7] + +//w[0] + tmp_0 = wi[0] ^ wi[3] ^ wi[5] ^ wi[7] ^ 0x9e3779b9 ^ 0x0; + w[0] = (tmp_0 << 11) | (tmp_0 >> 21); +//w[1] + tmp_0 = wi[1] ^ wi[4] ^ wi[6] ^ w[0] ^ 0x9e3779b9 ^ 0x1; + w[1] = (tmp_0 << 11) | (tmp_0 >> 21); +//w[2] + tmp_0 = wi[2] ^ wi[5] ^ wi[7] ^ w[1] ^ 0x9e3779b9 ^ 0x2; + w[2] = (tmp_0 << 11) | (tmp_0 >> 21); +//w[3] + tmp_0 = wi[3] ^ wi[6] ^ w[0] ^ w[2] ^ 0x9e3779b9 ^ 0x3; + w[3] = (tmp_0 << 11) | (tmp_0 >> 21); +//w[4] + tmp_0 = wi[4] ^ wi[7] ^ w[1] ^ w[3] ^ 0x9e3779b9 ^ 0x4; + w[4] = (tmp_0 << 11) | (tmp_0 >> 21); +//w[5] + tmp_0 = wi[5] ^ w[0] ^ w[2] ^ w[4] ^ 0x9e3779b9 ^ 0x5; + w[5] = (tmp_0 << 11) | (tmp_0 >> 21); +//w[6] + tmp_0 = wi[6] ^ w[1] ^ w[3] ^ w[5] ^ 0x9e3779b9 ^ 0x6; + w[6] = (tmp_0 << 11) | (tmp_0 >> 21); +//w[7] + tmp_0 = wi[7] ^ w[2] ^ w[4] ^ w[6] ^ 0x9e3779b9 ^ 0x7; + w[7] = (tmp_0 << 11) | (tmp_0 >> 21); + +//setp 1-3, generate w[8]~w[131] with w[0]~w[7] + for( i = 8; i < 132; i++){ + tmp_0 = w[i-8] ^ w[i-5] ^ w[i-3] ^ w[i-1] ^ 0x9e3779b9 ^ i; + w[i] = (tmp_0 << 11) | (tmp_0 >> 21); + } + + fprintf(fp,"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n"); + fprintf(fp,"DETAIL DATA FOR RUN_CNT = %d \n",tmp_4); + for( i = 0; i < 8; i++){ + fprintf(fp,"w[%d] = %08x \n",i-8,wi[i]); + } + for( i = 0; i < 132; i++){ + fprintf(fp,"w[%d] = %08x \n",i,w[i]); + } + + //setp 1-4,input w[0]~w[131] to sbox,generate k_0[0]~k_0[131] + //data will be permutated before input into SBOX + for( i = 0; i < 132; i = i + 4){ + IP(&w[i+0],&w[i+1],&w[i+2],&w[i+3],&sb_in[i+0],&sb_in[i+1],&sb_in[i+2],&sb_in[i+3]); + sb_out[i+0] = sb(((35-i/4)%8),sb_in[i+0]); + sb_out[i+1] = sb(((35-i/4)%8),sb_in[i+1]); + sb_out[i+2] = sb(((35-i/4)%8),sb_in[i+2]); + sb_out[i+3] = sb(((35-i/4)%8),sb_in[i+3]); + k[i+0] = sb_out[i+0] ; + k[i+1] = sb_out[i+1] ; + k[i+2] = sb_out[i+2] ; + k[i+3] = sb_out[i+3] ; + } + + fprintf(fp,"sub_key data~~~~~~~~~~~~~~~~~~~~ \n"); + for(i = 0; i < 132; i++){ + if((i%4) == 0) {fprintf(fp,"=======sub_key[%d]: =======\n",i/4);} + fprintf(fp,"sub_key[%d]_%d = %08x \n",i/4,i%4, k[i]); + } + fprintf(fp," \n"); + fprintf(fp," \n"); + fprintf(fp,"encryption data~~~~~~~~~~~~~~~~~~~~ \n"); + + //======================================================================== + //By now,we've got the sub_key0~32,then we can start to encrypt plain data + //step 2, data encryption + //initial permutation + IP(&p_0,&p_1,&p_2,&p_3,&b[0],&b[1],&b[2],&b[3]); + + fprintf(fp,"p_0 = %08x \n",p_0); + fprintf(fp,"p_1 = %08x \n",p_1); + fprintf(fp,"p_2 = %08x \n",p_2); + fprintf(fp,"p_3 = %08x \n",p_3); + + fprintf(fp,"b_0 = %08x \n",b[0]); + fprintf(fp,"b_1 = %08x \n",b[1]); + fprintf(fp,"b_2 = %08x \n",b[2]); + fprintf(fp,"b_3 = %08x \n",b[3]); + + //step 2-1,32 rounds of data encryption + //round0~30, 31 normal rounds + for(i = 0; i < 31; i++) + { + //xor operation + xor[i*4+0] = b[i*4+0] ^ k[i*4+0]; + xor[i*4+1] = b[i*4+1] ^ k[i*4+1]; + xor[i*4+2] = b[i*4+2] ^ k[i*4+2]; + xor[i*4+3] = b[i*4+3] ^ k[i*4+3]; + //SBOX + sbox[i*4+0] = sb((i%8),xor[i*4+0]); + sbox[i*4+1] = sb((i%8),xor[i*4+1]); + sbox[i*4+2] = sb((i%8),xor[i*4+2]); + sbox[i*4+3] = sb((i%8),xor[i*4+3]); + //linear + FP(&sbox[i*4+0],&sbox[i*4+1],&sbox[i*4+2],&sbox[i*4+3],&li[i*4+0],&li[i*4+1],&li[i*4+2],&li[i*4+3]); + linear(&li[i*4+0],&li[i*4+1],&li[i*4+2],&li[i*4+3],&lo[i*4+0],&lo[i*4+1],&lo[i*4+2],&lo[i*4+3]); + IP(&lo[i*4+0],&lo[i*4+1],&lo[i*4+2],&lo[i*4+3],&b[i*4+4],&b[i*4+5],&b[i*4+6],&b[i*4+7]); + + fprintf(fp,"////////////////////\n"); + fprintf(fp,"i = %d \n",i); + fprintf(fp,"xored[%d] = %08x \n", i*4+0, xor[i*4+0]); + fprintf(fp,"xored[%d] = %08x \n", i*4+1, xor[i*4+1]); + fprintf(fp,"xored[%d] = %08x \n", i*4+2, xor[i*4+2]); + fprintf(fp,"xored[%d] = %08x \n", i*4+3, xor[i*4+3]); + + fprintf(fp,"sbox[%d] = %08x \n", i*4+0, sbox[i*4+0]); + fprintf(fp,"sbox[%d] = %08x \n", i*4+1, sbox[i*4+1]); + fprintf(fp,"sbox[%d] = %08x \n", i*4+2, sbox[i*4+2]); + fprintf(fp,"sbox[%d] = %08x \n", i*4+3, sbox[i*4+3]); + + fprintf(fp,"linear_in[%d] = %08x \n", i*4+0, li[i*4+0]); + fprintf(fp,"linear_in[%d] = %08x \n", i*4+1, li[i*4+1]); + fprintf(fp,"linear_in[%d] = %08x \n", i*4+2, li[i*4+2]); + fprintf(fp,"linear_in[%d] = %08x \n", i*4+3, li[i*4+3]); + + fprintf(fp,"linear_out[%d] = %08x \n", i*4+0, lo[i*4+0]); + fprintf(fp,"linear_out[%d] = %08x \n", i*4+1, lo[i*4+1]); + fprintf(fp,"linear_out[%d] = %08x \n", i*4+2, lo[i*4+2]); + fprintf(fp,"linear_out[%d] = %08x \n", i*4+3, lo[i*4+3]); + + fprintf(fp,"b[%d] = %08x \n", i*4+4, b[i*4+4]); + fprintf(fp,"b[%d] = %08x \n", i*4+5, b[i*4+5]); + fprintf(fp,"b[%d] = %08x \n", i*4+6, b[i*4+6]); + fprintf(fp,"b[%d] = %08x \n", i*4+7, b[i*4+7]); + } + //round31 + //xor operation + xor[124] = b[124] ^ k[124]; + xor[125] = b[125] ^ k[125]; + xor[126] = b[126] ^ k[126]; + xor[127] = b[127] ^ k[127]; + fprintf(fp,"////////////////////\n"); + fprintf(fp,"i = %d \n", i); + fprintf(fp,"xored = %08x \n", xor[i*4+0]); + fprintf(fp,"xored = %08x \n", xor[i*4+1]); + fprintf(fp,"xored = %08x \n", xor[i*4+2]); + fprintf(fp,"xored = %08x \n", xor[i*4+3]); + //SBOX + sbox[124] = sb(0x7,xor[124]); + sbox[125] = sb(0x7,xor[125]); + sbox[126] = sb(0x7,xor[126]); + sbox[127] = sb(0x7,xor[127]); + fprintf(fp,"sbox = %08x \n", sbox[i*4+0]); + fprintf(fp,"sbox = %08x \n", sbox[i*4+1]); + fprintf(fp,"sbox = %08x \n", sbox[i*4+2]); + fprintf(fp,"sbox = %08x \n", sbox[i*4+3]); + //xor operation-2 + b[128] = sbox[124] ^ k[128]; + b[129] = sbox[125] ^ k[129]; + b[130] = sbox[126] ^ k[130]; + b[131] = sbox[127] ^ k[131]; + fprintf(fp,"k[128]= %08x \n", k[128]); + fprintf(fp,"k[129]= %08x \n", k[129]); + fprintf(fp,"k[130]= %08x \n", k[130]); + fprintf(fp,"k[131]= %08x \n", k[131]); + + fprintf(fp,"b[128]= %08x \n", b[128]); + fprintf(fp,"b[129]= %08x \n", b[129]); + fprintf(fp,"b[130]= %08x \n", b[130]); + fprintf(fp,"b[131]= %08x \n", b[131]); + +//step 2-2, final permutation + + FP(&b[128],&b[129],&b[130],&b[131],&c_0,&c_1,&c_2,&c_3); + + fprintf(fp,"P0 = %08x \n", p_0); fprintf(fp,"P1 = %08x \n", p_1); fprintf(fp,"P2 = %08x \n", p_2); fprintf(fp,"P3 = %08x \n", p_3); + fprintf(fp,"KEY0 = %08x \n", key_0); fprintf(fp,"KEY1 = %08x \n", key_1); fprintf(fp,"KEY2 = %08x \n", key_2); fprintf(fp,"KEY3 = %08x \n", key_3); + fprintf(fp,"C0 = %08x \n", c_0); fprintf(fp,"C1 = %08x \n", c_1); fprintf(fp,"C2 = %08x \n", c_2); fprintf(fp,"C3 = %08x \n", c_3); + //fclose(fp); + + printf("================================== \n"); + printf("==============RESULT============== \n"); + printf("================================== \n"); + printf("P0 = %08x ", p_0); printf("P1 = %08x ", p_1); printf("P2 = %08x ", p_2); printf("P3 = %08x \n", p_3); + printf("KEY0 = %08x ", key_0); printf("KEY1 = %08x ", key_1); printf("KEY2 = %08x ", key_2); printf("KEY3 = %08x \n", key_3); + printf("C0 = %08x ", c_0); printf("C1 = %08x ", c_1); printf("C2 = %08x ", c_2); printf("C3 = %08x \n", c_3); + tmp_4++; + printf("WILL YOU CALCULATE SERPENT-1 AGAIN ? 1:YES 0:NO \n"); + scanf_s("%x",&tmp_5); + if(tmp_5 == 0x0) + break; + fclose(fp); + return 0; +} +#endif diff --git a/test/specktest.c b/test/specktest.c new file mode 100644 index 00000000..00dbe7f7 --- /dev/null +++ b/test/specktest.c @@ -0,0 +1,38 @@ +#include +#include +#include + +#include "../e_os.h" + +#ifdef OPENSSL_NO_SPECK +int main(int argc, char **argv) +{ + printf("No Speck support\n"); + return 0; +} +#else + +#include + +int main(int argc, char **argv) +{ + speck_key_t key; + unsigned char userkey[2] = { 0x01, 0x02, }; + unsigned char msg[2] = { 0xab, 0xcd, }; + SPECK_TYPE S[SPECK_ROUNDS]; + + unsigned char cbuf[2]; + unsigned char mbuf[2]; + + speck_set_encrypt_key(&key, userkey); + speck_expand(&key, S); + speck_encrypt(msg, cbuf, S); + speck_decrypt(cbuf, mbuf, S); + + if (memcmp(msg, mbuf, 2)) { + return -1; + } + + return 0; +} +#endif diff --git a/util/shlib_wrap.sh b/util/shlib_wrap.sh deleted file mode 100755 index 811a08d6..00000000 --- a/util/shlib_wrap.sh +++ /dev/null @@ -1,92 +0,0 @@ -#!/bin/sh - -[ $# -ne 0 ] || set -x # debug mode without arguments:-) - -THERE="`echo $0 | sed -e 's|[^/]*$||' 2>/dev/null`.." -[ -d "${THERE}" ] || exec "$@" # should never happen... - -# Alternative to this is to parse ${THERE}/Makefile... -LIBCRYPTOSO="${THERE}/libcrypto.so" -if [ -f "$LIBCRYPTOSO" ]; then - while [ -h "$LIBCRYPTOSO" ]; do - LIBCRYPTOSO="${THERE}/`ls -l "$LIBCRYPTOSO" | sed -e 's|.*\-> ||'`" - done - SOSUFFIX=`echo ${LIBCRYPTOSO} | sed -e 's|.*\.so||' 2>/dev/null` - LIBSSLSO="${THERE}/libssl.so${SOSUFFIX}" -fi - -SYSNAME=`(uname -s) 2>/dev/null`; -case "$SYSNAME" in -SunOS|IRIX*) - # SunOS and IRIX run-time linkers evaluate alternative - # variables depending on target ABI... - rld_var=LD_LIBRARY_PATH - case "`(/usr/bin/file "$LIBCRYPTOSO") 2>/dev/null`" in - *ELF\ 64*SPARC*|*ELF\ 64*AMD64*) - [ -n "$LD_LIBRARY_PATH_64" ] && rld_var=LD_LIBRARY_PATH_64 - LD_PRELOAD_64="$LIBCRYPTOSO $LIBSSLSO"; export LD_PRELOAD_64 - preload_var=LD_PRELOAD_64 - ;; - *ELF\ 32*SPARC*|*ELF\ 32*80386*) - # We only need to change LD_PRELOAD_32 and LD_LIBRARY_PATH_32 - # on a multi-arch system. Otherwise, trust the fallbacks. - if [ -f /lib/64/ld.so.1 ]; then - [ -n "$LD_LIBRARY_PATH_32" ] && rld_var=LD_LIBRARY_PATH_32 - LD_PRELOAD_32="$LIBCRYPTOSO $LIBSSLSO"; export LD_PRELOAD_32 - preload_var=LD_PRELOAD_32 - fi - ;; - # Why are newly built .so's preloaded anyway? Because run-time - # .so lookup path embedded into application takes precedence - # over LD_LIBRARY_PATH and as result application ends up linking - # to previously installed .so's. On IRIX instead of preloading - # newly built .so's we trick run-time linker to fail to find - # the installed .so by setting _RLD_ROOT variable. - *ELF\ 32*MIPS*) - #_RLD_LIST="$LIBCRYPTOSO:$LIBSSLSO:DEFAULT"; export _RLD_LIST - _RLD_ROOT=/no/such/dir; export _RLD_ROOT - eval $rld_var=\"/usr/lib'${'$rld_var':+:$'$rld_var'}'\" - preload_var=_RLD_LIST - ;; - *ELF\ N32*MIPS*) - [ -n "$LD_LIBRARYN32_PATH" ] && rld_var=LD_LIBRARYN32_PATH - #_RLDN32_LIST="$LIBCRYPTOSO:$LIBSSLSO:DEFAULT"; export _RLDN32_LIST - _RLDN32_ROOT=/no/such/dir; export _RLDN32_ROOT - eval $rld_var=\"/usr/lib32'${'$rld_var':+:$'$rld_var'}'\" - preload_var=_RLDN32_LIST - ;; - *ELF\ 64*MIPS*) - [ -n "$LD_LIBRARY64_PATH" ] && rld_var=LD_LIBRARY64_PATH - #_RLD64_LIST="$LIBCRYPTOSO:$LIBSSLSO:DEFAULT"; export _RLD64_LIST - _RLD64_ROOT=/no/such/dir; export _RLD64_ROOT - eval $rld_var=\"/usr/lib64'${'$rld_var':+:$'$rld_var'}'\" - preload_var=_RLD64_LIST - ;; - esac - eval $rld_var=\"${THERE}'${'$rld_var':+:$'$rld_var'}'\"; export $rld_var - unset rld_var - ;; -*) LD_LIBRARY_PATH="${THERE}:$LD_LIBRARY_PATH" # Linux, ELF HP-UX - DYLD_LIBRARY_PATH="${THERE}:$DYLD_LIBRARY_PATH" # MacOS X - SHLIB_PATH="${THERE}:$SHLIB_PATH" # legacy HP-UX - LIBPATH="${THERE}:$LIBPATH" # AIX, OS/2 - export LD_LIBRARY_PATH DYLD_LIBRARY_PATH SHLIB_PATH LIBPATH - # Even though $PATH is adjusted [for Windows sake], it doesn't - # necessarily does the trick. Trouble is that with introduction - # of SafeDllSearchMode in XP/2003 it's more appropriate to copy - # .DLLs in vicinity of executable, which is done elsewhere... - if [ "$OSTYPE" != msdosdjgpp ]; then - PATH="${THERE}:$PATH"; export PATH - fi - ;; -esac - - - -cmd="$1"; [ -x "$cmd" ] || cmd="$cmd${EXE_EXT}" -shift -if [ $# -eq 0 ]; then - exec "$cmd" # old sh, such as Tru64 4.x, fails to expand empty "$@" -else - exec "$cmd" "$@" -fi