Showing preview only (1,209K chars total). Download the full file or copy to clipboard to get everything.
Repository: windard/sm4
Branch: master
Commit: 25d22143b1f9
Files: 96
Total size: 1.1 MB
Directory structure:
gitextract_g_s27c19/
├── C/
│ ├── SM2_SM3_SM4_C语言实现/
│ │ ├── SM2/
│ │ │ ├── kdf.h
│ │ │ ├── sm2.c
│ │ │ ├── sm2.dsp
│ │ │ ├── sm2.dsw
│ │ │ ├── sm2.h
│ │ │ └── sm2test.c
│ │ ├── SM3/
│ │ │ ├── sm3.c
│ │ │ ├── sm3.h
│ │ │ ├── sm3test.c
│ │ │ ├── sm3test.dsp
│ │ │ └── sm3test.dsw
│ │ └── SM4/
│ │ ├── sm4.c
│ │ ├── sm4.dsp
│ │ ├── sm4.dsw
│ │ ├── sm4.h
│ │ ├── sm4test.c
│ │ └── sms4.c
│ └── sm4.c
├── Java/
│ └── JavaSM4.java
├── JavaScript/
│ ├── demo/
│ │ ├── js/
│ │ │ ├── asn1-1.0.js
│ │ │ ├── asn1hex-1.1.js
│ │ │ ├── asn1x509-1.0.js
│ │ │ ├── base64.js
│ │ │ ├── cipher-core.js
│ │ │ ├── core.js
│ │ │ ├── crypto-1.1.js
│ │ │ ├── ec-patch.js
│ │ │ ├── ec.js
│ │ │ ├── ecdsa-modified-1.0.js
│ │ │ ├── ecparam-1.0.js
│ │ │ ├── enc-base64.js
│ │ │ ├── fingerprint.js
│ │ │ ├── fingerprint2.js
│ │ │ ├── jsbn.js
│ │ │ ├── jsbn2.js
│ │ │ ├── md5.js
│ │ │ ├── pkcs5pkey-1.0.js
│ │ │ ├── prng4.js
│ │ │ ├── rng.js
│ │ │ ├── rsa.js
│ │ │ ├── rsa2.js
│ │ │ ├── rsapem-1.1.js
│ │ │ ├── rsasign-1.2.js
│ │ │ ├── sha1.js
│ │ │ ├── sha256.js
│ │ │ ├── sm2-guomi.js
│ │ │ ├── sm2.js
│ │ │ ├── sm3-guomi.js
│ │ │ ├── sm3-sm2-1.0.js
│ │ │ ├── sm3.js
│ │ │ ├── sm4.js
│ │ │ ├── tripledes.js
│ │ │ ├── utils.js
│ │ │ ├── x509-1.1.js
│ │ │ └── yahoo-min.js
│ │ └── performance.html
│ ├── des/
│ │ └── JavaScript DES Example.html
│ ├── js/
│ │ └── sm4.js
│ ├── sm2/
│ │ ├── js/
│ │ │ ├── asn1-1.0.js
│ │ │ ├── asn1hex-1.1.js
│ │ │ ├── asn1x509-1.0.js
│ │ │ ├── base64.js
│ │ │ ├── cipher-core.js
│ │ │ ├── core.js
│ │ │ ├── crypto-1.1.js
│ │ │ ├── ec-patch.js
│ │ │ ├── ec.js
│ │ │ ├── ecdsa-modified-1.0.js
│ │ │ ├── ecparam-1.0.js
│ │ │ ├── enc-base64.js
│ │ │ ├── fingerprint.js
│ │ │ ├── jsbn.js
│ │ │ ├── jsbn2.js
│ │ │ ├── md5.js
│ │ │ ├── pkcs5pkey-1.0.js
│ │ │ ├── prng4.js
│ │ │ ├── rng.js
│ │ │ ├── rsa.js
│ │ │ ├── rsa2.js
│ │ │ ├── rsapem-1.1.js
│ │ │ ├── rsasign-1.2.js
│ │ │ ├── sha1.js
│ │ │ ├── sha256.js
│ │ │ ├── sm2-guomi.js
│ │ │ ├── sm2.js
│ │ │ ├── sm3-guomi.js
│ │ │ ├── sm3-sm2-1.0.js
│ │ │ ├── sm3.js
│ │ │ ├── tripledes.js
│ │ │ ├── x509-1.1.js
│ │ │ └── yahoo-min.js
│ │ ├── sm2.html
│ │ └── sm2_decrypt.html
│ └── sm4.html
├── Python/
│ └── sm4.py
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM2/kdf.h
================================================
#include <memory.h>
#include <openssl/evp.h>
// ----- KDF FUNCTIONS START -----
//typedef void *(*KDF)(const void *in, size_t inlen, void *out, size_t *outlen);
int x9_63_kdf(const EVP_MD *md, const unsigned char *share, size_t sharelen, size_t keylen, unsigned char *outkey)
{
int ret = 0;
EVP_MD_CTX ctx;
unsigned char counter[4] = {0, 0, 0, 1};
unsigned char dgst[EVP_MAX_MD_SIZE];
unsigned int dgstlen;
int rlen = (int)keylen;
unsigned char * pp;
pp = outkey;
if (keylen > (size_t)EVP_MD_size(md)*255)
{
fprintf(stderr, "%s(%d):", __FILE__, __LINE__);
goto end;
}
while (rlen > 0)
{
EVP_MD_CTX_init(&ctx);
if (!EVP_DigestInit(&ctx, md))
{
fprintf(stderr, "%s(%d):", __FILE__, __LINE__);
goto end;
}
if (!EVP_DigestUpdate(&ctx, share, sharelen))
{
fprintf(stderr, "%s(%d):", __FILE__, __LINE__);
goto end;
}
if (!EVP_DigestUpdate(&ctx, counter, 4))
{
fprintf(stderr, "%s(%d):", __FILE__, __LINE__);
goto end;
}
if (!EVP_DigestFinal(&ctx, dgst, &dgstlen))
{
fprintf(stderr, "%s(%d):", __FILE__, __LINE__);
goto end;
}
EVP_MD_CTX_cleanup(&ctx);
memcpy(pp, dgst, keylen>=dgstlen ? dgstlen:keylen);
rlen -= dgstlen;
pp += dgstlen;
counter[3]++;
}
ret = 1;
end:
return ret;
}
// ----- KDF FUNCTIONS END -----
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM2/sm2.c
================================================
// \file:sm2.c
//SM2 Algorithm
//2011-11-10
//author:goldboar
//email:goldboar@163.com
//depending:opnessl library
//SM2 Standards: http://www.oscca.gov.cn/News/201012/News_1197.htm
#include <limits.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/ecdsa.h>
#include <openssl/ecdh.h>
#include "kdf.h"
#define NID_X9_62_prime_field 406
static void BNPrintf(BIGNUM* bn)
{
char *p=NULL;
p=BN_bn2hex(bn);
printf("%s",p);
OPENSSL_free(p);
}
static int sm2_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kp, BIGNUM **rp)
{
BN_CTX *ctx = NULL;
BIGNUM *k = NULL, *r = NULL, *order = NULL, *X = NULL;
EC_POINT *tmp_point=NULL;
const EC_GROUP *group;
int ret = 0;
if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL)
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (ctx_in == NULL)
{
if ((ctx = BN_CTX_new()) == NULL)
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP,ERR_R_MALLOC_FAILURE);
return 0;
}
}
else
ctx = ctx_in;
k = BN_new(); /* this value is later returned in *kp */
r = BN_new(); /* this value is later returned in *rp */
order = BN_new();
X = BN_new();
if (!k || !r || !order || !X)
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_MALLOC_FAILURE);
goto err;
}
if ((tmp_point = EC_POINT_new(group)) == NULL)
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
goto err;
}
if (!EC_GROUP_get_order(group, order, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
goto err;
}
do
{
/* get random k */
do
if (!BN_rand_range(k, order))
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ECDSA_R_RANDOM_NUMBER_GENERATION_FAILED);
goto err;
}
while (BN_is_zero(k));
/* compute r the x-coordinate of generator * k */
if (!EC_POINT_mul(group, tmp_point, k, NULL, NULL, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
goto err;
}
if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field)
{
if (!EC_POINT_get_affine_coordinates_GFp(group,
tmp_point, X, NULL, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP,ERR_R_EC_LIB);
goto err;
}
}
else /* NID_X9_62_characteristic_two_field */
{
if (!EC_POINT_get_affine_coordinates_GF2m(group,
tmp_point, X, NULL, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP,ERR_R_EC_LIB);
goto err;
}
}
if (!BN_nnmod(r, X, order, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
goto err;
}
}
while (BN_is_zero(r));
/* compute the inverse of k */
// if (!BN_mod_inverse(k, k, order, ctx))
// {
// ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
// goto err;
// }
/* clear old values if necessary */
if (*rp != NULL)
BN_clear_free(*rp);
if (*kp != NULL)
BN_clear_free(*kp);
/* save the pre-computed values */
*rp = r;
*kp = k;
ret = 1;
err:
if (!ret)
{
if (k != NULL) BN_clear_free(k);
if (r != NULL) BN_clear_free(r);
}
if (ctx_in == NULL)
BN_CTX_free(ctx);
if (order != NULL)
BN_free(order);
if (tmp_point != NULL)
EC_POINT_free(tmp_point);
if (X)
BN_clear_free(X);
return(ret);
}
static ECDSA_SIG *sm2_do_sign(const unsigned char *dgst, int dgst_len, const BIGNUM *in_k, const BIGNUM *in_r, EC_KEY *eckey)
{
int ok = 0, i;
BIGNUM *k=NULL, *s, *m=NULL,*tmp=NULL,*order=NULL;
const BIGNUM *ck;
BN_CTX *ctx = NULL;
const EC_GROUP *group;
ECDSA_SIG *ret;
//ECDSA_DATA *ecdsa;
const BIGNUM *priv_key;
BIGNUM *r,*x=NULL,*a=NULL; //new added
//ecdsa = ecdsa_check(eckey);
group = EC_KEY_get0_group(eckey);
priv_key = EC_KEY_get0_private_key(eckey);
if (group == NULL || priv_key == NULL /*|| ecdsa == NULL*/)
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
ret = ECDSA_SIG_new();
if (!ret)
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE);
return NULL;
}
s = ret->s;
r = ret->r;
if ((ctx = BN_CTX_new()) == NULL || (order = BN_new()) == NULL ||
(tmp = BN_new()) == NULL || (m = BN_new()) == NULL ||
(x = BN_new()) == NULL || (a = BN_new()) == NULL)
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EC_GROUP_get_order(group, order, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_EC_LIB);
goto err;
}
// for(i=0;i<dgst_len;i++)
// printf("%02X",dgst[i]);
// printf("\n");
i = BN_num_bits(order);
/* Need to truncate digest if it is too long: first truncate whole
* bytes.
*/
if (8 * dgst_len > i)
dgst_len = (i + 7)/8;
if (!BN_bin2bn(dgst, dgst_len, m))
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
goto err;
}
/* If still too long truncate remaining bits with a shift */
if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7)))
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
goto err;
}
// fprintf(stdout,"m: ");
// BNPrintf(m);
// fprintf(stdout,"\n");
do
{
if (in_k == NULL || in_r == NULL)
{
if (!sm2_sign_setup(eckey, ctx, &k, &x))
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN,ERR_R_ECDSA_LIB);
goto err;
}
ck = k;
}
else
{
ck = in_k;
if (BN_copy(x, in_r) == NULL)
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE);
goto err;
}
}
//r=(e+x1) mod n
if (!BN_mod_add_quick(r, m, x, order))
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
goto err;
}
// BNPrintf(r);
// fprintf(stdout,"\n");
if(BN_is_zero(r) )
continue;
BN_add(tmp,r,ck);
if(BN_ucmp(tmp,order) == 0)
continue;
if (!BN_mod_mul(tmp, priv_key, r, order, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
goto err;
}
if (!BN_mod_sub_quick(s, ck, tmp, order))
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
goto err;
}
BN_one(a);
//BN_set_word((a),1);
if (!BN_mod_add_quick(tmp, priv_key, a, order))
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
goto err;
}
/* compute the inverse of 1+dA */
if (!BN_mod_inverse(tmp, tmp, order, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
goto err;
}
// BNPrintf(tmp);
// fprintf(stdout,"\n");
if (!BN_mod_mul(s, s, tmp, order, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
goto err;
}
if (BN_is_zero(s))
{
/* if k and r have been supplied by the caller
* don't to generate new k and r values */
if (in_k != NULL && in_r != NULL)
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ECDSA_R_NEED_NEW_SETUP_VALUES);
goto err;
}
}
else
/* s != 0 => we have a valid signature */
break;
}
while (1);
ok = 1;
err:
if (!ok)
{
ECDSA_SIG_free(ret);
ret = NULL;
}
if (ctx)
BN_CTX_free(ctx);
if (m)
BN_clear_free(m);
if (tmp)
BN_clear_free(tmp);
if (order)
BN_free(order);
if (k)
BN_clear_free(k);
if (x)
BN_clear_free(x);
if (a)
BN_clear_free(a);
return ret;
}
static int sm2_do_verify(const unsigned char *dgst, int dgst_len,
const ECDSA_SIG *sig, EC_KEY *eckey)
{
int ret = -1, i;
BN_CTX *ctx;
BIGNUM *order, *R, *m, *X,*t;
EC_POINT *point = NULL;
const EC_GROUP *group;
const EC_POINT *pub_key;
/* check input values */
if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL ||
(pub_key = EC_KEY_get0_public_key(eckey)) == NULL || sig == NULL)
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_MISSING_PARAMETERS);
return -1;
}
ctx = BN_CTX_new();
if (!ctx)
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_MALLOC_FAILURE);
return -1;
}
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
R = BN_CTX_get(ctx);
t = BN_CTX_get(ctx);
m = BN_CTX_get(ctx);
X = BN_CTX_get(ctx);
if (!X)
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
goto err;
}
if (!EC_GROUP_get_order(group, order, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB);
goto err;
}
if (BN_is_zero(sig->r) || BN_is_negative(sig->r) ||
BN_ucmp(sig->r, order) >= 0 || BN_is_zero(sig->s) ||
BN_is_negative(sig->s) || BN_ucmp(sig->s, order) >= 0)
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_BAD_SIGNATURE);
ret = 0; /* signature is invalid */
goto err;
}
//t =(r+s) mod n
if (!BN_mod_add_quick(t, sig->s, sig->r,order))
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
goto err;
}
if (BN_is_zero(t))
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_BAD_SIGNATURE);
ret = 0; /* signature is invalid */
goto err;
}
//point = s*G+t*PA
if ((point = EC_POINT_new(group)) == NULL)
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EC_POINT_mul(group, point, sig->s, pub_key, t, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB);
goto err;
}
if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field)
{
if (!EC_POINT_get_affine_coordinates_GFp(group,
point, X, NULL, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB);
goto err;
}
}
else /* NID_X9_62_characteristic_two_field */
{
if (!EC_POINT_get_affine_coordinates_GF2m(group,
point, X, NULL, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB);
goto err;
}
}
i = BN_num_bits(order);
/* Need to truncate digest if it is too long: first truncate whole
* bytes.
*/
if (8 * dgst_len > i)
dgst_len = (i + 7)/8;
if (!BN_bin2bn(dgst, dgst_len, m))
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
goto err;
}
/* If still too long truncate remaining bits with a shift */
if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7)))
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
goto err;
}
/* R = m + X mod order */
if (!BN_mod_add_quick(R, m, X, order))
{
ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
goto err;
}
/* if the signature is correct R is equal to sig->r */
ret = (BN_ucmp(R, sig->r) == 0);
err:
BN_CTX_end(ctx);
BN_CTX_free(ctx);
if (point)
EC_POINT_free(point);
return ret;
}
EC_POINT *sm2_compute_key(const EC_POINT *b_pub_key_r, const EC_POINT *b_pub_key, const BIGNUM *a_r,EC_KEY *a_eckey)
{
BN_CTX *ctx;
EC_POINT *tmp=NULL;
BIGNUM *x=NULL, *y=NULL, *order=NULL,*z=NULL;
const BIGNUM *priv_key;
const EC_GROUP* group;
EC_POINT *ret= NULL;
/* size_t buflen, len;*/
unsigned char *buf=NULL;
int i, j;
//char *p=NULL;
BIGNUM *x1,*x2,*t,*h;
if ((ctx = BN_CTX_new()) == NULL) goto err;
BN_CTX_start(ctx);
x = BN_CTX_get(ctx);
y = BN_CTX_get(ctx);
order = BN_CTX_get(ctx);
z = BN_CTX_get(ctx);
x1 = BN_CTX_get(ctx);
x2 = BN_CTX_get(ctx);
t = BN_CTX_get(ctx);
h = BN_CTX_get(ctx);
priv_key = EC_KEY_get0_private_key(a_eckey);
if (priv_key == NULL)
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_NO_PRIVATE_VALUE);
goto err;
}
group = EC_KEY_get0_group(a_eckey);
if ((tmp=EC_POINT_new(group)) == NULL)
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EC_POINT_mul(group, tmp, a_r, NULL, NULL, ctx))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field)
{
if (!EC_POINT_get_affine_coordinates_GFp(group, tmp, x, NULL, ctx))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
}
else
{
if (!EC_POINT_get_affine_coordinates_GF2m(group, tmp, x, NULL, ctx))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
}
if (!EC_GROUP_get_order(group, order, ctx))
{
ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_EC_LIB);
goto err;
}
i = BN_num_bits(order);
j = i/2 -1;
BN_mask_bits(x,j);
BN_set_word(y,2);
BN_set_word(z,j);
BN_exp(y,y,z,ctx);
BN_add(x1,x,y);
// fprintf(stdout,"X1=: ");
// BNPrintf(x1);
// fprintf(stdout,"\n");
BN_mod_mul(t,x1,a_r,order,ctx);
BN_mod_add_quick(t,t,priv_key,order);
//
// fprintf(stdout,"ta=: ");
// BNPrintf(t);
// fprintf(stdout,"\n");
if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field)
{
if (!EC_POINT_get_affine_coordinates_GFp(group, b_pub_key_r, x, NULL, ctx))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
}
else
{
if (!EC_POINT_get_affine_coordinates_GF2m(group, b_pub_key_r, x, NULL, ctx))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
}
i = BN_num_bits(order);
j = i/2 -1;
BN_mask_bits(x,j);
BN_set_word(y,2);
BN_set_word(z,j);
BN_exp(y,y,z,ctx);
BN_add(x2,x,y);
// fprintf(stdout,"X2=: ");
// BNPrintf(x2);
// fprintf(stdout,"\n");
//x2*Rb+Pb;
if (!EC_POINT_mul(group, tmp, NULL,b_pub_key_r,x2,ctx) )
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
if ((ret=EC_POINT_new(group)) == NULL)
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EC_POINT_add(group, ret, b_pub_key, tmp, ctx))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
if (!EC_POINT_get_affine_coordinates_GFp(group,ret, x, y, ctx))
{
goto err;
}
// fprintf(stdout, "\nTesting x2*Rb+Pb Key Point\n x = 0x");
// BNPrintf(x);
// fprintf(stdout, "\n y = 0x");
// BNPrintf( y);
// fprintf(stdout, "\n");
//
if(!EC_GROUP_get_cofactor(group, h, ctx))
{
goto err;
}
BN_mul(t,t,h,ctx);
//h*t*(x2*Rb+Pb)
if (!EC_POINT_mul(group, ret, NULL,ret,t,ctx) )
{
goto err;
}
if (!EC_POINT_get_affine_coordinates_GFp(group,ret, x, y, ctx))
{
goto err;
}
// fprintf(stdout, "\nTesting ret Key Point\n x = 0x");
// BNPrintf(x);
// fprintf(stdout, "\n y = 0x");
// BNPrintf( y);
// fprintf(stdout, "\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);
}
/** SM2_sign_setup
* precompute parts of the signing operation.
* \param eckey pointer to the EC_KEY object containing a private EC key
* \param ctx pointer to a BN_CTX object (may be NULL)
* \param k pointer to a BIGNUM pointer for the inverse of k
* \param rp pointer to a BIGNUM pointer for x coordinate of k * generator
* \return 1 on success and 0 otherwise
*/
int SM2_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
{
// ECDSA_DATA *ecdsa = ecdsa_check(eckey);
// if (ecdsa == NULL)
// return 0;
return SM2_sign_setup(eckey, ctx_in, kinvp, rp);
}
/** SM2_sign_ex
* computes ECDSA signature of a given hash value using the supplied
* private key (note: sig must point to ECDSA_size(eckey) bytes of memory).
* \param type this parameter is ignored
* \param dgst pointer to the hash value to sign
* \param dgstlen length of the hash value
* \param sig buffer to hold the DER encoded signature
* \param siglen pointer to the length of the returned signature
* \param k optional pointer to a pre-computed inverse k
* \param rp optional pointer to the pre-computed rp value (see
* ECDSA_sign_setup
* \param eckey pointer to the EC_KEY object containing a private EC key
* \return 1 on success and 0 otherwise
*/
int SM2_sign_ex(int type, const unsigned char *dgst, int dlen, unsigned char
*sig, unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r,
EC_KEY *eckey)
{
ECDSA_SIG *s;
RAND_seed(dgst, dlen);
s = sm2_do_sign(dgst, dlen, kinv, r, eckey);
if (s == NULL)
{
*siglen=0;
return 0;
}
*siglen = i2d_ECDSA_SIG(s, &sig);
ECDSA_SIG_free(s);
return 1;
}
/** SM2_sign
* computes ECDSA signature of a given hash value using the supplied
* private key (note: sig must point to ECDSA_size(eckey) bytes of memory).
* \param type this parameter is ignored
* \param dgst pointer to the hash value to sign
* \param dgstlen length of the hash value
* \param sig buffer to hold the DER encoded signature
* \param siglen pointer to the length of the returned signature
* \param eckey pointer to the EC_KEY object containing a private EC key
* \return 1 on success and 0 otherwise
*/
int SM2_sign(int type, const unsigned char *dgst, int dlen, unsigned char
*sig, unsigned int *siglen, EC_KEY *eckey)
{
return SM2_sign_ex(type, dgst, dlen, sig, siglen, NULL, NULL, eckey);
}
/** SM2_verify
* verifies that the given signature is valid ECDSA signature
* of the supplied hash value using the specified public key.
* \param type this parameter is ignored
* \param dgst pointer to the hash value
* \param dgstlen length of the hash value
* \param sig pointer to the DER encoded signature
* \param siglen length of the DER encoded signature
* \param eckey pointer to the EC_KEY object containing a public EC key
* \return 1 if the signature is valid, 0 if the signature is invalid and -1 on error
*/
int SM2_verify(int type, const unsigned char *dgst, int dgst_len,
const unsigned char *sigbuf, int sig_len, EC_KEY *eckey)
{
ECDSA_SIG *s;
int ret=-1;
s = ECDSA_SIG_new();
if (s == NULL) return(ret);
if (d2i_ECDSA_SIG(&s, &sigbuf, sig_len) == NULL) goto err;
ret=sm2_do_verify(dgst, dgst_len, s, eckey);
err:
ECDSA_SIG_free(s);
return(ret);
}
int SM2_DH_key(const EC_GROUP * group, const EC_POINT *b_pub_key_r, const EC_POINT *b_pub_key, const BIGNUM *a_r,EC_KEY *a_eckey,
unsigned char *outkey,size_t keylen)
{
EC_POINT *dhpoint = NULL;
BN_CTX * ctx;
EC_POINT *P;
BIGNUM *x, *y;
int ret = 0;
unsigned char in[128];
int inlen;
int len;
P = EC_POINT_new(group);
if (!P ) goto err;
ctx = BN_CTX_new();
x = BN_new();
y = BN_new();
if (!x || !y ) goto err;
dhpoint = sm2_compute_key(b_pub_key_r,b_pub_key,a_r,a_eckey);
if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field)
{
if (!EC_POINT_get_affine_coordinates_GFp(group,dhpoint, x, y, ctx))
{
fprintf(stdout, " failed\n");
goto err;
}
}
else
{
if (!EC_POINT_get_affine_coordinates_GF2m(group,dhpoint, x, y, ctx))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
}
// if (!EC_POINT_get_affine_coordinates_GFp(group,dhpoint, x, y, ctx))
// {
// fprintf(stdout, " failed\n");
// goto err;
// }
fprintf(stdout, "\nTesting DH Point\n Xv = 0x");
BNPrintf(x);
fprintf(stdout, "\n Yv = 0x");
BNPrintf( y);
fprintf(stdout, "\n");
len = BN_bn2bin(x,in);
inlen =BN_bn2bin(y,in+len);
inlen = inlen + len;
ret = x9_63_kdf(EVP_sha256(),in,inlen,keylen,outkey);
//ret = 1;
err:
EC_POINT_free(P);
EC_POINT_free(dhpoint);
BN_CTX_free(ctx);
return ret;
}
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM2/sm2.dsp
================================================
# Microsoft Developer Studio Project File - Name="sm2" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Console Application" 0x0103
CFG=sm2 - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "sm2.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "sm2.mak" CFG="sm2 - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "sm2 - Win32 Release" (based on "Win32 (x86) Console Application")
!MESSAGE "sm2 - Win32 Debug" (based on "Win32 (x86) Console Application")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "sm2 - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
# ADD BASE RSC /l 0x804 /d "NDEBUG"
# ADD RSC /l 0x804 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
!ELSEIF "$(CFG)" == "sm2 - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /FR /YX /FD /GZ /c
# ADD BASE RSC /l 0x804 /d "_DEBUG"
# ADD RSC /l 0x804 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
!ENDIF
# Begin Target
# Name "sm2 - Win32 Release"
# Name "sm2 - Win32 Debug"
# Begin Source File
SOURCE=.\kdf.h
# End Source File
# Begin Source File
SOURCE=.\sm2.c
# End Source File
# Begin Source File
SOURCE=.\sm2.h
# End Source File
# Begin Source File
SOURCE=.\sm2test.c
# End Source File
# End Target
# End Project
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM2/sm2.dsw
================================================
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
###############################################################################
Project: "sm2"=.\sm2.dsp - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM2/sm2.h
================================================
// \file:sm2.h
//SM2 Algorithm
//2011-11-09
//author:goldboar
//email:goldboar@163.com
//comment:2011-11-10 sm2-sign-verify sm2-dh
//SM2_sign_setup
int SM2_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp);
//SM2_sign_ex
int SM2_sign_ex(int type, const unsigned char *dgst, int dlen, unsigned char
*sig, unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey);
//SM2_sign
int SM2_sign(int type, const unsigned char *dgst, int dlen, unsigned char
*sig, unsigned int *siglen, EC_KEY *eckey);
//SM2_verify
int SM2_verify(int type, const unsigned char *dgst, int dgst_len,
const unsigned char *sigbuf, int sig_len, EC_KEY *eckey);
//SM2 DH, comupting shared point
int SM2_DH_key(const EC_GROUP * group,const EC_POINT *b_pub_key_r, const EC_POINT *b_pub_key, const BIGNUM *a_r,EC_KEY *a_eckey,
unsigned char *outkey,size_t keylen);
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM2/sm2test.c
================================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <openssl/bn.h>
#include <openssl/ec.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/ecdsa.h>
#include <openssl/ecdh.h>
#include "sm2.h"
#pragma comment(lib,"libeay32.lib")
#define ABORT do { \
fflush(stdout); \
fprintf(stderr, "%s:%d: ABORT\n", __FILE__, __LINE__); \
ERR_print_errors_fp(stderr); \
exit(1); \
} while (0)
static const char rnd_seed[] = "string to make the random number generator think it has entropy";
void BNPrintf(BIGNUM* bn)
{
char *p=NULL;
p=BN_bn2hex(bn);
printf("%s",p);
OPENSSL_free(p);
}
int SM2_Test_Vecotor()
{
BN_CTX *ctx = NULL;
BIGNUM *p, *a, *b;
EC_GROUP *group;
EC_POINT *P, *Q, *R;
BIGNUM *x, *y, *z;
EC_KEY *eckey = NULL;
unsigned char digest[20];
unsigned char *signature = NULL;
int sig_len;
CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
ERR_load_crypto_strings();
RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_generate_prime may fail */
ctx = BN_CTX_new();
if (!ctx) ABORT;
/* Curve SM2 (Chinese National Algorithm) */
//http://www.oscca.gov.cn/News/201012/News_1197.htm
p = BN_new();
a = BN_new();
b = BN_new();
if (!p || !a || !b) ABORT;
group = EC_GROUP_new(EC_GFp_mont_method()); /* applications should use EC_GROUP_new_curve_GFp
* so that the library gets to choose the EC_METHOD */
if (!group) ABORT;
if (!BN_hex2bn(&p, "8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3")) ABORT;
if (1 != BN_is_prime_ex(p, BN_prime_checks, ctx, NULL)) ABORT;
if (!BN_hex2bn(&a, "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498")) ABORT;
if (!BN_hex2bn(&b, "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A")) ABORT;
if (!EC_GROUP_set_curve_GFp(group, p, a, b, ctx)) ABORT;
P = EC_POINT_new(group);
Q = EC_POINT_new(group);
R = EC_POINT_new(group);
if (!P || !Q || !R) ABORT;
x = BN_new();
y = BN_new();
z = BN_new();
if (!x || !y || !z) ABORT;
// sm2 testing P256 Vetor
// p8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3
// a787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498
// b63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A
// xG 421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D
// yG 0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2
// n: 8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7
if (!BN_hex2bn(&x, "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D")) ABORT;
if (!EC_POINT_set_compressed_coordinates_GFp(group, P, x, 0, ctx)) ABORT;
if (!EC_POINT_is_on_curve(group, P, ctx)) ABORT;
if (!BN_hex2bn(&z, "8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7")) ABORT;
if (!EC_GROUP_set_generator(group, P, z, BN_value_one())) ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group, P, x, y, ctx)) ABORT;
fprintf(stdout, "\nChinese sm2 algorithm test -- Generator:\n x = 0x");
BNPrintf(x);
fprintf(stdout, "\n y = 0x");
BNPrintf( y);
fprintf(stdout, "\n");
/* G_y value taken from the standard: */
if (!BN_hex2bn(&z, "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2")) ABORT;
if (0 != BN_cmp(y, z)) ABORT;
fprintf(stdout, "verify degree ...");
if (EC_GROUP_get_degree(group) != 256) ABORT;
fprintf(stdout, " ok\n");
fprintf(stdout, "verify group order ...");
fflush(stdout);
if (!EC_GROUP_get_order(group, z, ctx)) ABORT;
if (!EC_GROUP_precompute_mult(group, ctx)) ABORT;
if (!EC_POINT_mul(group, Q, z, NULL, NULL, ctx)) ABORT;
if (!EC_POINT_is_at_infinity(group, Q)) ABORT;
fflush(stdout);
fprintf(stdout, " ok\n");
//testing ECDSA for SM2
/* create new ecdsa key */
if ((eckey = EC_KEY_new()) == NULL)
goto builtin_err;
if (EC_KEY_set_group(eckey, group) == 0)
{
fprintf(stdout," failed\n");
goto builtin_err;
}
/* create key */
if (!EC_KEY_generate_key(eckey))
{
fprintf(stdout," failed\n");
goto builtin_err;
}
/* check key */
if (!EC_KEY_check_key(eckey))
{
fprintf(stdout," failed\n");
goto builtin_err;
}
/* create signature */
sig_len = ECDSA_size(eckey);
fprintf(stdout,"Siglength is: %d \n",sig_len);
if (!RAND_pseudo_bytes(digest, 20))
{
fprintf(stdout," failed\n");
goto builtin_err;
}
if ((signature = OPENSSL_malloc(sig_len)) == NULL)
goto builtin_err;
if (!SM2_sign(0, digest, 20, signature, &sig_len, eckey))
{
fprintf(stdout, " failed\n");
goto builtin_err;
}
fprintf(stdout, "ECSign OK\n");
/* verify signature */
if (SM2_verify(0, digest, 20, signature, sig_len, eckey) != 1)
{
fprintf(stdout, " failed\n");
goto builtin_err;
}
fprintf(stdout, "ECVerify OK\n");
/* cleanup */
OPENSSL_free(signature);
signature = NULL;
EC_KEY_free(eckey);
eckey = NULL;
builtin_err:
EC_POINT_free(P);
EC_POINT_free(Q);
EC_POINT_free(R);
EC_GROUP_free(group);
BN_CTX_free(ctx);
return 0;
}
int SM2_Test_Vecotor2()
{
BN_CTX *ctx = NULL;
BIGNUM *p, *a, *b;
EC_GROUP *group;
EC_POINT *P, *Q, *R;
BIGNUM *x, *y, *z;
EC_KEY *eckey = NULL;
unsigned char *signature;
unsigned char digest[32] = "\xB5\x24\xF5\x52\xCD\x82\xB8\xB0\x28\x47\x6E\x00\x5C\x37\x7F\xB1\x9A\x87\xE6\xFC\x68\x2D\x48\xBB\x5D\x42\xE3\xD9\xB9\xEF\xFE\x76";
int sig_len;
BIGNUM *kinv, *rp,*order;
ECDSA_SIG *ecsig = ECDSA_SIG_new();
EC_POINT * DHPoint = NULL;
// unsigned char *in="123456";
// size_t inlen = 6;
size_t outlen = 256;
unsigned char outkey[256];
size_t keylen = 256;
size_t i;
CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
ERR_load_crypto_strings();
RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_generate_prime may fail */
ctx = BN_CTX_new();
if (!ctx) ABORT;
/* Curve SM2 (Chinese National Algorithm) */
//http://www.oscca.gov.cn/News/201012/News_1197.htm
p = BN_new();
a = BN_new();
b = BN_new();
if (!p || !a || !b) ABORT;
group = EC_GROUP_new(EC_GFp_mont_method()); /* applications should use EC_GROUP_new_curve_GFp
* so that the library gets to choose the EC_METHOD */
if (!group) ABORT;
if (!BN_hex2bn(&p, "8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3")) ABORT;
if (1 != BN_is_prime_ex(p, BN_prime_checks, ctx, NULL)) ABORT;
if (!BN_hex2bn(&a, "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498")) ABORT;
if (!BN_hex2bn(&b, "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A")) ABORT;
if (!EC_GROUP_set_curve_GFp(group, p, a, b, ctx)) ABORT;
P = EC_POINT_new(group);
Q = EC_POINT_new(group);
R = EC_POINT_new(group);
if (!P || !Q || !R) ABORT;
x = BN_new();
y = BN_new();
z = BN_new();
if (!x || !y || !z) ABORT;
// sm2 testing P256 Vetor
// p8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3
// a787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498
// b63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A
// xG 421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D
// yG 0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2
// n: 8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7
if (!BN_hex2bn(&x, "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D")) ABORT;
if (!EC_POINT_set_compressed_coordinates_GFp(group, P, x, 0, ctx)) ABORT;
if (!EC_POINT_is_on_curve(group, P, ctx)) ABORT;
if (!BN_hex2bn(&z, "8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7")) ABORT;
if (!EC_GROUP_set_generator(group, P, z, BN_value_one())) ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group, P, x, y, ctx)) ABORT;
fprintf(stdout, "\nChinese sm2 algorithm test -- Generator:\n x = 0x");
BNPrintf(x);
fprintf(stdout, "\n y = 0x");
BNPrintf( y);
fprintf(stdout, "\n");
/* G_y value taken from the standard: */
if (!BN_hex2bn(&z, "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2")) ABORT;
if (0 != BN_cmp(y, z)) ABORT;
fprintf(stdout, "verify degree ...");
if (EC_GROUP_get_degree(group) != 256) ABORT;
fprintf(stdout, " ok\n");
fprintf(stdout, "verify group order ...");
fflush(stdout);
if (!EC_GROUP_get_order(group, z, ctx)) ABORT;
if (!EC_GROUP_precompute_mult(group, ctx)) ABORT;
if (!EC_POINT_mul(group, Q, z, NULL, NULL, ctx)) ABORT;
if (!EC_POINT_is_at_infinity(group, Q)) ABORT;
fflush(stdout);
fprintf(stdout, " ok\n");
//testing ECDSA for SM2
/* create new ecdsa key */
if ((eckey = EC_KEY_new()) == NULL)
goto builtin_err;
if (EC_KEY_set_group(eckey, group) == 0)
{
fprintf(stdout," failed\n");
goto builtin_err;
}
/* create key */
if (!BN_hex2bn(&z, "128B2FA8BD433C6C068C8D803DFF79792A519A55171B1B650C23661D15897263")) ABORT;
if (!EC_POINT_mul(group,P, z, NULL, NULL, ctx)) ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group,P, x, y, ctx)) ABORT;
fprintf(stdout, "\nTesting ECKey Point\n x = 0x");
BNPrintf(x);
fprintf(stdout, "\n y = 0x");
BNPrintf( y);
fprintf(stdout, "\n");
EC_KEY_set_private_key(eckey,z);
EC_KEY_set_public_key(eckey, P);
/* check key */
if (!EC_KEY_check_key(eckey))
{
fprintf(stdout," failed\n");
goto builtin_err;
}
/* create signature */
sig_len = ECDSA_size(eckey);
//fprintf(stdout,"Siglength is: %d \n",sig_len);
if ((signature = OPENSSL_malloc(sig_len)) == NULL)
goto builtin_err;
rp = BN_new();
kinv = BN_new();
order = BN_new();
if (!BN_hex2bn(&z, "6CB28D99385C175C94F94E934817663FC176D925DD72B727260DBAAE1FB2F96F")) ABORT;
if (!EC_POINT_mul(group, Q, z, NULL, NULL, ctx))
{
fprintf(stdout, " failed\n");
goto builtin_err;
}
if (!EC_POINT_get_affine_coordinates_GFp(group,Q, x, y, ctx))
{
fprintf(stdout, " failed\n");
goto builtin_err;
}
fprintf(stdout, "\nTesting K Point\n x = 0x");
BNPrintf(x);
fprintf(stdout, "\n y = 0x");
BNPrintf( y);
fprintf(stdout, "\n");
EC_GROUP_get_order(group, order, ctx);
if (!BN_nnmod(rp, x, order, ctx))
{
fprintf(stdout, " failed\n");
goto builtin_err;
}
if (!BN_copy(kinv, z ))
{
fprintf(stdout, " failed\n");
goto builtin_err;
}
// for(i=0;i<32;i++)
// printf("%02X",digest[i]);
// printf("\n");
if (!SM2_sign_ex(1, digest, 32, signature, &sig_len, kinv, rp, eckey))
{
fprintf(stdout, " failed\n");
goto builtin_err;
}
fprintf(stdout, "ECSign OK\n");
/* verify signature */
if (SM2_verify(1, digest, 32, signature, sig_len, eckey) != 1)
{
fprintf(stdout, " failed\n");
goto builtin_err;
}
fprintf(stdout, "ECVerify OK\n r = 0x");
d2i_ECDSA_SIG(&ecsig, &signature, sig_len);
BNPrintf(ecsig->r);
fprintf(stdout,"\n s = 0x");
BNPrintf(ecsig->s);
fprintf(stdout,"\n");
//testing SM2DH vector
/* create key */
if (!BN_hex2bn(&z, "6FCBA2EF9AE0AB902BC3BDE3FF915D44BA4CC78F88E2F8E7F8996D3B8CCEEDEE")) ABORT;
if (!EC_POINT_mul(group,P, z, NULL, NULL, ctx)) ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group,P, x, y, ctx)) ABORT;
fprintf(stdout, "\nTesting A Key Point\n x = 0x");
BNPrintf(x);
fprintf(stdout, "\n y = 0x");
BNPrintf( y);
fprintf(stdout, "\n");
EC_KEY_set_private_key(eckey,z);
EC_KEY_set_public_key(eckey, P);
if (!BN_hex2bn(&z, "5E35D7D3F3C54DBAC72E61819E730B019A84208CA3A35E4C2E353DFCCB2A3B53")) ABORT;
if (!EC_POINT_mul(group,Q, z, NULL, NULL, ctx)) ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group,Q, x, y, ctx)) ABORT;
fprintf(stdout, "\nTesting B Key Point\n x = 0x");
BNPrintf(x);
fprintf(stdout, "\n y = 0x");
BNPrintf( y);
fprintf(stdout, "\n");
//EC_KEY_set_private_key(eckey,z);
//EC_KEY_set_public_key(eckey, P);
if (!BN_hex2bn(&z, "33FE21940342161C55619C4A0C060293D543C80AF19748CE176D83477DE71C80")) ABORT;
if (!EC_POINT_mul(group,P, z, NULL, NULL, ctx)) ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group,P, x, y, ctx)) ABORT;
fprintf(stdout, "\nTesting Rb Key Point\n x = 0x");
BNPrintf(x);
fprintf(stdout, "\n y = 0x");
BNPrintf( y);
fprintf(stdout, "\n");
if (!BN_hex2bn(&z, "83A2C9C8B96E5AF70BD480B472409A9A327257F1EBB73F5B073354B248668563")) ABORT;
if (!EC_POINT_mul(group,R, z, NULL, NULL, ctx)) ABORT;
if (!EC_POINT_get_affine_coordinates_GFp(group,R, x, y, ctx)) ABORT;
fprintf(stdout, "\nTesting Ra Key Point\n x = 0x");
BNPrintf(x);
fprintf(stdout, "\n y = 0x");
BNPrintf( y);
fprintf(stdout, "\n");
SM2_DH_key(group,P, Q, z,eckey,outkey,keylen);
fprintf(stdout,"\nExchange key --KDF(Xv||Yv)-- :");
for(i=0; i<outlen; i++)
printf("%02X",outkey[i]);
printf("\n");
builtin_err:
OPENSSL_free(signature);
signature = NULL;
EC_POINT_free(P);
EC_POINT_free(Q);
EC_POINT_free(R);
EC_POINT_free(DHPoint);
EC_KEY_free(eckey);
eckey = NULL;
EC_GROUP_free(group);
BN_CTX_free(ctx);
return 0;
}
int main()
{
CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
ERR_load_crypto_strings();
RAND_seed(rnd_seed, sizeof rnd_seed);
SM2_Test_Vecotor2();
CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
ERR_remove_state(0);
CRYPTO_mem_leaks_fp(stderr);
return 0;
}
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM3/sm3.c
================================================
/*
* SM3 Hash alogrith
* thanks to Xyssl
* author:goldboar
* email:goldboar@163.com
* 2011-10-26
*/
//Testing data from SM3 Standards
//http://www.oscca.gov.cn/News/201012/News_1199.htm
// Sample 1
// Input:"abc"
// Output:66c7f0f4 62eeedd9 d1f2d46b dc10e4e2 4167c487 5cf2f7a2 297da02b 8f4ba8e0
// Sample 2
// Input:"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"
// Outpuf:debe9ff9 2275b8a1 38604889 c18e5a4d 6fdb70e5 387e5765 293dcba3 9c0c5732
#include "sm3.h"
#include <string.h>
#include <stdio.h>
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_ULONG_BE
#define GET_ULONG_BE(n,b,i) \
{ \
(n) = ( (unsigned long) (b)[(i) ] << 24 ) \
| ( (unsigned long) (b)[(i) + 1] << 16 ) \
| ( (unsigned long) (b)[(i) + 2] << 8 ) \
| ( (unsigned long) (b)[(i) + 3] ); \
}
#endif
#ifndef PUT_ULONG_BE
#define PUT_ULONG_BE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
}
#endif
/*
* SM3 context setup
*/
void sm3_starts( sm3_context *ctx )
{
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x7380166F;
ctx->state[1] = 0x4914B2B9;
ctx->state[2] = 0x172442D7;
ctx->state[3] = 0xDA8A0600;
ctx->state[4] = 0xA96F30BC;
ctx->state[5] = 0x163138AA;
ctx->state[6] = 0xE38DEE4D;
ctx->state[7] = 0xB0FB0E4E;
}
static void sm3_process( sm3_context *ctx, unsigned char data[64] )
{
unsigned long SS1, SS2, TT1, TT2, W[68],W1[64];
unsigned long A, B, C, D, E, F, G, H;
unsigned long T[64];
unsigned long Temp1,Temp2,Temp3,Temp4,Temp5;
int j;
#ifdef _DEBUG
int i;
#endif
// for(j=0; j < 68; j++)
// W[j] = 0;
// for(j=0; j < 64; j++)
// W1[j] = 0;
for(j = 0; j < 16; j++)
T[j] = 0x79CC4519;
for(j =16; j < 64; j++)
T[j] = 0x7A879D8A;
GET_ULONG_BE( W[ 0], data, 0 );
GET_ULONG_BE( W[ 1], data, 4 );
GET_ULONG_BE( W[ 2], data, 8 );
GET_ULONG_BE( W[ 3], data, 12 );
GET_ULONG_BE( W[ 4], data, 16 );
GET_ULONG_BE( W[ 5], data, 20 );
GET_ULONG_BE( W[ 6], data, 24 );
GET_ULONG_BE( W[ 7], data, 28 );
GET_ULONG_BE( W[ 8], data, 32 );
GET_ULONG_BE( W[ 9], data, 36 );
GET_ULONG_BE( W[10], data, 40 );
GET_ULONG_BE( W[11], data, 44 );
GET_ULONG_BE( W[12], data, 48 );
GET_ULONG_BE( W[13], data, 52 );
GET_ULONG_BE( W[14], data, 56 );
GET_ULONG_BE( W[15], data, 60 );
#ifdef _DEBUG
printf("Message with padding:\n");
for(i=0; i< 8; i++)
printf("%08x ",W[i]);
printf("\n");
for(i=8; i< 16; i++)
printf("%08x ",W[i]);
printf("\n");
#endif
#define FF0(x,y,z) ( (x) ^ (y) ^ (z))
#define FF1(x,y,z) (((x) & (y)) | ( (x) & (z)) | ( (y) & (z)))
#define GG0(x,y,z) ( (x) ^ (y) ^ (z))
#define GG1(x,y,z) (((x) & (y)) | ( (~(x)) & (z)) )
#define SHL(x,n) (((x) & 0xFFFFFFFF) << n)
#define ROTL(x,n) (SHL((x),n) | ((x) >> (32 - n)))
#define P0(x) ((x) ^ ROTL((x),9) ^ ROTL((x),17))
#define P1(x) ((x) ^ ROTL((x),15) ^ ROTL((x),23))
for(j = 16; j < 68; j++ )
{
//W[j] = P1( W[j-16] ^ W[j-9] ^ ROTL(W[j-3],15)) ^ ROTL(W[j - 13],7 ) ^ W[j-6];
//Why thd release's result is different with the debug's ?
//Below is okay. Interesting, Perhaps VC6 has a bug of Optimizaiton.
Temp1 = W[j-16] ^ W[j-9];
Temp2 = ROTL(W[j-3],15);
Temp3 = Temp1 ^ Temp2;
Temp4 = P1(Temp3);
Temp5 = ROTL(W[j - 13],7 ) ^ W[j-6];
W[j] = Temp4 ^ Temp5;
}
#ifdef _DEBUG
printf("Expanding message W0-67:\n");
for(i=0; i<68; i++)
{
printf("%08x ",W[i]);
if(((i+1) % 8) == 0) printf("\n");
}
printf("\n");
#endif
for(j = 0; j < 64; j++)
{
W1[j] = W[j] ^ W[j+4];
}
#ifdef _DEBUG
printf("Expanding message W'0-63:\n");
for(i=0; i<64; i++)
{
printf("%08x ",W1[i]);
if(((i+1) % 8) == 0) printf("\n");
}
printf("\n");
#endif
A = ctx->state[0];
B = ctx->state[1];
C = ctx->state[2];
D = ctx->state[3];
E = ctx->state[4];
F = ctx->state[5];
G = ctx->state[6];
H = ctx->state[7];
#ifdef _DEBUG
printf("j A B C D E F G H\n");
printf(" %08x %08x %08x %08x %08x %08x %08x %08x\n",A,B,C,D,E,F,G,H);
#endif
for(j =0; j < 16; j++)
{
SS1 = ROTL((ROTL(A,12) + E + ROTL(T[j],j)), 7);
SS2 = SS1 ^ ROTL(A,12);
TT1 = FF0(A,B,C) + D + SS2 + W1[j];
TT2 = GG0(E,F,G) + H + SS1 + W[j];
D = C;
C = ROTL(B,9);
B = A;
A = TT1;
H = G;
G = ROTL(F,19);
F = E;
E = P0(TT2);
#ifdef _DEBUG
printf("%02d %08x %08x %08x %08x %08x %08x %08x %08x\n",j,A,B,C,D,E,F,G,H);
#endif
}
for(j =16; j < 64; j++)
{
SS1 = ROTL((ROTL(A,12) + E + ROTL(T[j],j)), 7);
SS2 = SS1 ^ ROTL(A,12);
TT1 = FF1(A,B,C) + D + SS2 + W1[j];
TT2 = GG1(E,F,G) + H + SS1 + W[j];
D = C;
C = ROTL(B,9);
B = A;
A = TT1;
H = G;
G = ROTL(F,19);
F = E;
E = P0(TT2);
#ifdef _DEBUG
printf("%02d %08x %08x %08x %08x %08x %08x %08x %08x\n",j,A,B,C,D,E,F,G,H);
#endif
}
ctx->state[0] ^= A;
ctx->state[1] ^= B;
ctx->state[2] ^= C;
ctx->state[3] ^= D;
ctx->state[4] ^= E;
ctx->state[5] ^= F;
ctx->state[6] ^= G;
ctx->state[7] ^= H;
#ifdef _DEBUG
printf(" %08x %08x %08x %08x %08x %08x %08x %08x\n",ctx->state[0],ctx->state[1],ctx->state[2],
ctx->state[3],ctx->state[4],ctx->state[5],ctx->state[6],ctx->state[7]);
#endif
}
/*
* SM3 process buffer
*/
void sm3_update( sm3_context *ctx, unsigned char *input, int ilen )
{
int fill;
unsigned long left;
if( ilen <= 0 )
return;
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += ilen;
ctx->total[0] &= 0xFFFFFFFF;
if( ctx->total[0] < (unsigned long) ilen )
ctx->total[1]++;
if( left && ilen >= fill )
{
memcpy( (void *) (ctx->buffer + left),
(void *) input, fill );
sm3_process( ctx, ctx->buffer );
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
sm3_process( ctx, input );
input += 64;
ilen -= 64;
}
if( ilen > 0 )
{
memcpy( (void *) (ctx->buffer + left),
(void *) input, ilen );
}
}
static const unsigned char sm3_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*
* SM3 final digest
*/
void sm3_finish( sm3_context *ctx, unsigned char output[32] )
{
unsigned long last, padn;
unsigned long high, low;
unsigned char msglen[8];
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
PUT_ULONG_BE( high, msglen, 0 );
PUT_ULONG_BE( low, msglen, 4 );
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
sm3_update( ctx, (unsigned char *) sm3_padding, padn );
sm3_update( ctx, msglen, 8 );
PUT_ULONG_BE( ctx->state[0], output, 0 );
PUT_ULONG_BE( ctx->state[1], output, 4 );
PUT_ULONG_BE( ctx->state[2], output, 8 );
PUT_ULONG_BE( ctx->state[3], output, 12 );
PUT_ULONG_BE( ctx->state[4], output, 16 );
PUT_ULONG_BE( ctx->state[5], output, 20 );
PUT_ULONG_BE( ctx->state[6], output, 24 );
PUT_ULONG_BE( ctx->state[7], output, 28 );
}
/*
* output = SM3( input buffer )
*/
void sm3( unsigned char *input, int ilen,
unsigned char output[32] )
{
sm3_context ctx;
sm3_starts( &ctx );
sm3_update( &ctx, input, ilen );
sm3_finish( &ctx, output );
memset( &ctx, 0, sizeof( sm3_context ) );
}
/*
* output = SM3( file contents )
*/
int sm3_file( char *path, unsigned char output[32] )
{
FILE *f;
size_t n;
sm3_context ctx;
unsigned char buf[1024];
if( ( f = fopen( path, "rb" ) ) == NULL )
return( 1 );
sm3_starts( &ctx );
while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 )
sm3_update( &ctx, buf, (int) n );
sm3_finish( &ctx, output );
memset( &ctx, 0, sizeof( sm3_context ) );
if( ferror( f ) != 0 )
{
fclose( f );
return( 2 );
}
fclose( f );
return( 0 );
}
/*
* SM3 HMAC context setup
*/
void sm3_hmac_starts( sm3_context *ctx, unsigned char *key, int keylen )
{
int i;
unsigned char sum[32];
if( keylen > 64 )
{
sm3( key, keylen, sum );
keylen = 32;
//keylen = ( is224 ) ? 28 : 32;
key = sum;
}
memset( ctx->ipad, 0x36, 64 );
memset( ctx->opad, 0x5C, 64 );
for( i = 0; i < keylen; i++ )
{
ctx->ipad[i] = (unsigned char)( ctx->ipad[i] ^ key[i] );
ctx->opad[i] = (unsigned char)( ctx->opad[i] ^ key[i] );
}
sm3_starts( ctx);
sm3_update( ctx, ctx->ipad, 64 );
memset( sum, 0, sizeof( sum ) );
}
/*
* SM3 HMAC process buffer
*/
void sm3_hmac_update( sm3_context *ctx, unsigned char *input, int ilen )
{
sm3_update( ctx, input, ilen );
}
/*
* SM3 HMAC final digest
*/
void sm3_hmac_finish( sm3_context *ctx, unsigned char output[32] )
{
int hlen;
unsigned char tmpbuf[32];
//is224 = ctx->is224;
hlen = 32;
sm3_finish( ctx, tmpbuf );
sm3_starts( ctx );
sm3_update( ctx, ctx->opad, 64 );
sm3_update( ctx, tmpbuf, hlen );
sm3_finish( ctx, output );
memset( tmpbuf, 0, sizeof( tmpbuf ) );
}
/*
* output = HMAC-SM#( hmac key, input buffer )
*/
void sm3_hmac( unsigned char *key, int keylen,
unsigned char *input, int ilen,
unsigned char output[32] )
{
sm3_context ctx;
sm3_hmac_starts( &ctx, key, keylen);
sm3_hmac_update( &ctx, input, ilen );
sm3_hmac_finish( &ctx, output );
memset( &ctx, 0, sizeof( sm3_context ) );
}
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM3/sm3.h
================================================
/**
* \file sm3.h
* thanks to Xyssl
* SM3 standards:http://www.oscca.gov.cn/News/201012/News_1199.htm
* author:goldboar
* email:goldboar@163.com
* 2011-10-26
*/
#ifndef XYSSL_SM3_H
#define XYSSL_SM3_H
/**
* \brief SM3 context structure
*/
typedef struct
{
unsigned long total[2]; /*!< number of bytes processed */
unsigned long state[8]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
unsigned char ipad[64]; /*!< HMAC: inner padding */
unsigned char opad[64]; /*!< HMAC: outer padding */
}
sm3_context;
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief SM3 context setup
*
* \param ctx context to be initialized
*/
void sm3_starts( sm3_context *ctx );
/**
* \brief SM3 process buffer
*
* \param ctx SM3 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void sm3_update( sm3_context *ctx, unsigned char *input, int ilen );
/**
* \brief SM3 final digest
*
* \param ctx SM3 context
*/
void sm3_finish( sm3_context *ctx, unsigned char output[32] );
/**
* \brief Output = SM3( input buffer )
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output SM3 checksum result
*/
void sm3( unsigned char *input, int ilen,
unsigned char output[32]);
/**
* \brief Output = SM3( file contents )
*
* \param path input file name
* \param output SM3 checksum result
*
* \return 0 if successful, 1 if fopen failed,
* or 2 if fread failed
*/
int sm3_file( char *path, unsigned char output[32] );
/**
* \brief SM3 HMAC context setup
*
* \param ctx HMAC context to be initialized
* \param key HMAC secret key
* \param keylen length of the HMAC key
*/
void sm3_hmac_starts( sm3_context *ctx, unsigned char *key, int keylen);
/**
* \brief SM3 HMAC process buffer
*
* \param ctx HMAC context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void sm3_hmac_update( sm3_context *ctx, unsigned char *input, int ilen );
/**
* \brief SM3 HMAC final digest
*
* \param ctx HMAC context
* \param output SM3 HMAC checksum result
*/
void sm3_hmac_finish( sm3_context *ctx, unsigned char output[32] );
/**
* \brief Output = HMAC-SM3( hmac key, input buffer )
*
* \param key HMAC secret key
* \param keylen length of the HMAC key
* \param input buffer holding the data
* \param ilen length of the input data
* \param output HMAC-SM3 result
*/
void sm3_hmac( unsigned char *key, int keylen,
unsigned char *input, int ilen,
unsigned char output[32] );
#ifdef __cplusplus
}
#endif
#endif /* sm3.h */
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM3/sm3test.c
================================================
#include <string.h>
#include <stdio.h>
#include "sm3.h"
int main( int argc, char *argv[] )
{
unsigned char *input = "abc";
int ilen = 3;
unsigned char output[32];
int i;
sm3_context ctx;
printf("Message:\n");
printf("%s\n",input);
sm3(input, ilen, output);
printf("Hash:\n ");
for(i=0; i<32; i++)
{
printf("%02x",output[i]);
if (((i+1) % 4 ) == 0) printf(" ");
}
printf("\n");
printf("Message:\n");
for(i=0; i < 16; i++)
printf("abcd");
printf("\n");
sm3_starts( &ctx );
for(i=0; i < 16; i++)
sm3_update( &ctx, "abcd", 4 );
sm3_finish( &ctx, output );
memset( &ctx, 0, sizeof( sm3_context ) );
printf("Hash:\n ");
for(i=0; i<32; i++)
{
printf("%02x",output[i]);
if (((i+1) % 4 ) == 0) printf(" ");
}
printf("\n");
//getch(); //VS2008
}
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM3/sm3test.dsp
================================================
# Microsoft Developer Studio Project File - Name="sm3test" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Console Application" 0x0103
CFG=sm3test - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "sm3test.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "sm3test.mak" CFG="sm3test - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "sm3test - Win32 Release" (based on "Win32 (x86) Console Application")
!MESSAGE "sm3test - Win32 Debug" (based on "Win32 (x86) Console Application")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "sm3test - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
# ADD BASE RSC /l 0x804 /d "NDEBUG"
# ADD RSC /l 0x804 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
# SUBTRACT LINK32 /debug
!ELSEIF "$(CFG)" == "sm3test - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
# ADD BASE RSC /l 0x804 /d "_DEBUG"
# ADD RSC /l 0x804 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
!ENDIF
# Begin Target
# Name "sm3test - Win32 Release"
# Name "sm3test - Win32 Debug"
# Begin Source File
SOURCE=.\sm3.c
# End Source File
# Begin Source File
SOURCE=.\sm3.h
# End Source File
# Begin Source File
SOURCE=.\sm3test.c
# End Source File
# End Target
# End Project
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM3/sm3test.dsw
================================================
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
###############################################################################
Project: "sm3test"=".\sm3test.dsp" - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM4/sm4.c
================================================
/*
* SM4 Encryption alogrithm (SMS4 algorithm)
* GM/T 0002-2012 Chinese National Standard ref:http://www.oscca.gov.cn/
* thanks to Xyssl
* thnaks and refers to http://hi.baidu.com/numax/blog/item/80addfefddfb93e4cf1b3e61.html
* author:goldboar
* email:goldboar@163.com
* 2012-4-20
*/
// Test vector 1
// plain: 01 23 45 67 89 ab cd ef fe dc ba 98 76 54 32 10
// key: 01 23 45 67 89 ab cd ef fe dc ba 98 76 54 32 10
// round key and temp computing result:
// rk[ 0] = f12186f9 X[ 0] = 27fad345
// rk[ 1] = 41662b61 X[ 1] = a18b4cb2
// rk[ 2] = 5a6ab19a X[ 2] = 11c1e22a
// rk[ 3] = 7ba92077 X[ 3] = cc13e2ee
// rk[ 4] = 367360f4 X[ 4] = f87c5bd5
// rk[ 5] = 776a0c61 X[ 5] = 33220757
// rk[ 6] = b6bb89b3 X[ 6] = 77f4c297
// rk[ 7] = 24763151 X[ 7] = 7a96f2eb
// rk[ 8] = a520307c X[ 8] = 27dac07f
// rk[ 9] = b7584dbd X[ 9] = 42dd0f19
// rk[10] = c30753ed X[10] = b8a5da02
// rk[11] = 7ee55b57 X[11] = 907127fa
// rk[12] = 6988608c X[12] = 8b952b83
// rk[13] = 30d895b7 X[13] = d42b7c59
// rk[14] = 44ba14af X[14] = 2ffc5831
// rk[15] = 104495a1 X[15] = f69e6888
// rk[16] = d120b428 X[16] = af2432c4
// rk[17] = 73b55fa3 X[17] = ed1ec85e
// rk[18] = cc874966 X[18] = 55a3ba22
// rk[19] = 92244439 X[19] = 124b18aa
// rk[20] = e89e641f X[20] = 6ae7725f
// rk[21] = 98ca015a X[21] = f4cba1f9
// rk[22] = c7159060 X[22] = 1dcdfa10
// rk[23] = 99e1fd2e X[23] = 2ff60603
// rk[24] = b79bd80c X[24] = eff24fdc
// rk[25] = 1d2115b0 X[25] = 6fe46b75
// rk[26] = 0e228aeb X[26] = 893450ad
// rk[27] = f1780c81 X[27] = 7b938f4c
// rk[28] = 428d3654 X[28] = 536e4246
// rk[29] = 62293496 X[29] = 86b3e94f
// rk[30] = 01cf72e5 X[30] = d206965e
// rk[31] = 9124a012 X[31] = 681edf34
// cypher: 68 1e df 34 d2 06 96 5e 86 b3 e9 4f 53 6e 42 46
//
// test vector 2
// the same key and plain 1000000 times coumpting
// plain: 01 23 45 67 89 ab cd ef fe dc ba 98 76 54 32 10
// key: 01 23 45 67 89 ab cd ef fe dc ba 98 76 54 32 10
// cypher: 59 52 98 c7 c6 fd 27 1f 04 02 f8 04 c3 3d 3f 66
#include "sm4.h"
#include <string.h>
#include <stdio.h>
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_ULONG_BE
#define GET_ULONG_BE(n,b,i) \
{ \
(n) = ( (unsigned long) (b)[(i) ] << 24 ) \
| ( (unsigned long) (b)[(i) + 1] << 16 ) \
| ( (unsigned long) (b)[(i) + 2] << 8 ) \
| ( (unsigned long) (b)[(i) + 3] ); \
}
#endif
#ifndef PUT_ULONG_BE
#define PUT_ULONG_BE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
}
#endif
/*
*rotate shift left marco definition
*
*/
#define SHL(x,n) (((x) & 0xFFFFFFFF) << n)
#define ROTL(x,n) (SHL((x),n) | ((x) >> (32 - n)))
#define SWAP(a,b) { unsigned long t = a; a = b; b = t; t = 0; }
/*
* Expanded SM4 S-boxes
/* Sbox table: 8bits input convert to 8 bits output*/
static const unsigned char SboxTable[16][16] =
{
{0xd6,0x90,0xe9,0xfe,0xcc,0xe1,0x3d,0xb7,0x16,0xb6,0x14,0xc2,0x28,0xfb,0x2c,0x05},
{0x2b,0x67,0x9a,0x76,0x2a,0xbe,0x04,0xc3,0xaa,0x44,0x13,0x26,0x49,0x86,0x06,0x99},
{0x9c,0x42,0x50,0xf4,0x91,0xef,0x98,0x7a,0x33,0x54,0x0b,0x43,0xed,0xcf,0xac,0x62},
{0xe4,0xb3,0x1c,0xa9,0xc9,0x08,0xe8,0x95,0x80,0xdf,0x94,0xfa,0x75,0x8f,0x3f,0xa6},
{0x47,0x07,0xa7,0xfc,0xf3,0x73,0x17,0xba,0x83,0x59,0x3c,0x19,0xe6,0x85,0x4f,0xa8},
{0x68,0x6b,0x81,0xb2,0x71,0x64,0xda,0x8b,0xf8,0xeb,0x0f,0x4b,0x70,0x56,0x9d,0x35},
{0x1e,0x24,0x0e,0x5e,0x63,0x58,0xd1,0xa2,0x25,0x22,0x7c,0x3b,0x01,0x21,0x78,0x87},
{0xd4,0x00,0x46,0x57,0x9f,0xd3,0x27,0x52,0x4c,0x36,0x02,0xe7,0xa0,0xc4,0xc8,0x9e},
{0xea,0xbf,0x8a,0xd2,0x40,0xc7,0x38,0xb5,0xa3,0xf7,0xf2,0xce,0xf9,0x61,0x15,0xa1},
{0xe0,0xae,0x5d,0xa4,0x9b,0x34,0x1a,0x55,0xad,0x93,0x32,0x30,0xf5,0x8c,0xb1,0xe3},
{0x1d,0xf6,0xe2,0x2e,0x82,0x66,0xca,0x60,0xc0,0x29,0x23,0xab,0x0d,0x53,0x4e,0x6f},
{0xd5,0xdb,0x37,0x45,0xde,0xfd,0x8e,0x2f,0x03,0xff,0x6a,0x72,0x6d,0x6c,0x5b,0x51},
{0x8d,0x1b,0xaf,0x92,0xbb,0xdd,0xbc,0x7f,0x11,0xd9,0x5c,0x41,0x1f,0x10,0x5a,0xd8},
{0x0a,0xc1,0x31,0x88,0xa5,0xcd,0x7b,0xbd,0x2d,0x74,0xd0,0x12,0xb8,0xe5,0xb4,0xb0},
{0x89,0x69,0x97,0x4a,0x0c,0x96,0x77,0x7e,0x65,0xb9,0xf1,0x09,0xc5,0x6e,0xc6,0x84},
{0x18,0xf0,0x7d,0xec,0x3a,0xdc,0x4d,0x20,0x79,0xee,0x5f,0x3e,0xd7,0xcb,0x39,0x48}
};
/* System parameter */
static const unsigned long FK[4] = {0xa3b1bac6,0x56aa3350,0x677d9197,0xb27022dc};
/* fixed parameter */
static const unsigned long CK[32] =
{
0x00070e15,0x1c232a31,0x383f464d,0x545b6269,
0x70777e85,0x8c939aa1,0xa8afb6bd,0xc4cbd2d9,
0xe0e7eef5,0xfc030a11,0x181f262d,0x343b4249,
0x50575e65,0x6c737a81,0x888f969d,0xa4abb2b9,
0xc0c7ced5,0xdce3eaf1,0xf8ff060d,0x141b2229,
0x30373e45,0x4c535a61,0x686f767d,0x848b9299,
0xa0a7aeb5,0xbcc3cad1,0xd8dfe6ed,0xf4fb0209,
0x10171e25,0x2c333a41,0x484f565d,0x646b7279
};
/*
* private function:
* look up in SboxTable and get the related value.
* args: [in] inch: 0x00~0xFF (8 bits unsigned value).
*/
static unsigned char sm4Sbox(unsigned char inch)
{
unsigned char *pTable = (unsigned char *)SboxTable;
unsigned char retVal = (unsigned char)(pTable[inch]);
return retVal;
}
/*
* private F(Lt) function:
* "T algorithm" == "L algorithm" + "t algorithm".
* args: [in] a: a is a 32 bits unsigned value;
* return: c: c is calculated with line algorithm "L" and nonline algorithm "t"
*/
static unsigned long sm4Lt(unsigned long ka)
{
unsigned long bb = 0;
unsigned long c = 0;
unsigned char a[4];
unsigned char b[4];
PUT_ULONG_BE(ka,a,0)
b[0] = sm4Sbox(a[0]);
b[1] = sm4Sbox(a[1]);
b[2] = sm4Sbox(a[2]);
b[3] = sm4Sbox(a[3]);
GET_ULONG_BE(bb,b,0)
c =bb^(ROTL(bb, 2))^(ROTL(bb, 10))^(ROTL(bb, 18))^(ROTL(bb, 24));
return c;
}
/*
* private F function:
* Calculating and getting encryption/decryption contents.
* args: [in] x0: original contents;
* args: [in] x1: original contents;
* args: [in] x2: original contents;
* args: [in] x3: original contents;
* args: [in] rk: encryption/decryption key;
* return the contents of encryption/decryption contents.
*/
static unsigned long sm4F(unsigned long x0, unsigned long x1, unsigned long x2, unsigned long x3, unsigned long rk)
{
return (x0^sm4Lt(x1^x2^x3^rk));
}
/* private function:
* Calculating round encryption key.
* args: [in] a: a is a 32 bits unsigned value;
* return: sk[i]: i{0,1,2,3,...31}.
*/
static unsigned long sm4CalciRK(unsigned long ka)
{
unsigned long bb = 0;
unsigned long rk = 0;
unsigned char a[4];
unsigned char b[4];
PUT_ULONG_BE(ka,a,0)
b[0] = sm4Sbox(a[0]);
b[1] = sm4Sbox(a[1]);
b[2] = sm4Sbox(a[2]);
b[3] = sm4Sbox(a[3]);
GET_ULONG_BE(bb,b,0)
rk = bb^(ROTL(bb, 13))^(ROTL(bb, 23));
return rk;
}
static void sm4_setkey( unsigned long SK[32], unsigned char key[16] )
{
unsigned long MK[4];
unsigned long k[36];
unsigned long i = 0;
GET_ULONG_BE( MK[0], key, 0 );
GET_ULONG_BE( MK[1], key, 4 );
GET_ULONG_BE( MK[2], key, 8 );
GET_ULONG_BE( MK[3], key, 12 );
k[0] = MK[0]^FK[0];
k[1] = MK[1]^FK[1];
k[2] = MK[2]^FK[2];
k[3] = MK[3]^FK[3];
for(; i<32; i++)
{
k[i+4] = k[i] ^ (sm4CalciRK(k[i+1]^k[i+2]^k[i+3]^CK[i]));
SK[i] = k[i+4];
}
}
/*
* SM4 standard one round processing
*
*/
static void sm4_one_round( unsigned long sk[32],
unsigned char input[16],
unsigned char output[16] )
{
unsigned long i = 0;
unsigned long ulbuf[36];
memset(ulbuf, 0, sizeof(ulbuf));
GET_ULONG_BE( ulbuf[0], input, 0 )
GET_ULONG_BE( ulbuf[1], input, 4 )
GET_ULONG_BE( ulbuf[2], input, 8 )
GET_ULONG_BE( ulbuf[3], input, 12 )
while(i<32)
{
ulbuf[i+4] = sm4F(ulbuf[i], ulbuf[i+1], ulbuf[i+2], ulbuf[i+3], sk[i]);
// #ifdef _DEBUG
// printf("rk(%02d) = 0x%08x, X(%02d) = 0x%08x \n",i,sk[i], i, ulbuf[i+4] );
// #endif
i++;
}
PUT_ULONG_BE(ulbuf[35],output,0);
PUT_ULONG_BE(ulbuf[34],output,4);
PUT_ULONG_BE(ulbuf[33],output,8);
PUT_ULONG_BE(ulbuf[32],output,12);
}
/*
* SM4 key schedule (128-bit, encryption)
*/
void sm4_setkey_enc( sm4_context *ctx, unsigned char key[16] )
{
ctx->mode = SM4_ENCRYPT;
sm4_setkey( ctx->sk, key );
}
/*
* SM4 key schedule (128-bit, decryption)
*/
void sm4_setkey_dec( sm4_context *ctx, unsigned char key[16] )
{
int i;
ctx->mode = SM4_ENCRYPT;
sm4_setkey( ctx->sk, key );
for( i = 0; i < 16; i ++ )
{
SWAP( ctx->sk[ i ], ctx->sk[ 31-i] );
}
}
/*
* SM4-ECB block encryption/decryption
*/
void sm4_crypt_ecb( sm4_context *ctx,
int mode,
int length,
unsigned char *input,
unsigned char *output)
{
while( length > 0 )
{
sm4_one_round( ctx->sk, input, output );
input += 16;
output += 16;
length -= 16;
}
}
/*
* SM4-CBC buffer encryption/decryption
*/
void sm4_crypt_cbc( sm4_context *ctx,
int mode,
int length,
unsigned char iv[16],
unsigned char *input,
unsigned char *output )
{
int i;
unsigned char temp[16];
if( mode == SM4_ENCRYPT )
{
while( length > 0 )
{
for( i = 0; i < 16; i++ )
output[i] = (unsigned char)( input[i] ^ iv[i] );
sm4_one_round( ctx->sk, output, output );
memcpy( iv, output, 16 );
input += 16;
output += 16;
length -= 16;
}
}
else /* SM4_DECRYPT */
{
while( length > 0 )
{
memcpy( temp, input, 16 );
sm4_one_round( ctx->sk, input, output );
for( i = 0; i < 16; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, 16 );
input += 16;
output += 16;
length -= 16;
}
}
}
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM4/sm4.dsp
================================================
# Microsoft Developer Studio Project File - Name="sm4" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Console Application" 0x0103
CFG=sm4 - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "sm4.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "sm4.mak" CFG="sm4 - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "sm4 - Win32 Release" (based on "Win32 (x86) Console Application")
!MESSAGE "sm4 - Win32 Debug" (based on "Win32 (x86) Console Application")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "sm4 - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
# ADD BASE RSC /l 0x804 /d "NDEBUG"
# ADD RSC /l 0x804 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
!ELSEIF "$(CFG)" == "sm4 - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
# ADD BASE RSC /l 0x804 /d "_DEBUG"
# ADD RSC /l 0x804 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
!ENDIF
# Begin Target
# Name "sm4 - Win32 Release"
# Name "sm4 - Win32 Debug"
# Begin Source File
SOURCE=.\sm4.c
# End Source File
# Begin Source File
SOURCE=.\sm4.h
# End Source File
# Begin Source File
SOURCE=.\sm4test.c
# End Source File
# End Target
# End Project
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM4/sm4.dsw
================================================
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
###############################################################################
Project: "sm4"=.\sm4.dsp - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM4/sm4.h
================================================
/**
* \file sm4.h
*/
#ifndef XYSSL_SM4_H
#define XYSSL_SM4_H
#define SM4_ENCRYPT 1
#define SM4_DECRYPT 0
/**
* \brief SM4 context structure
*/
typedef struct
{
int mode; /*!< encrypt/decrypt */
unsigned long sk[32]; /*!< SM4 subkeys */
}
sm4_context;
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief SM4 key schedule (128-bit, encryption)
*
* \param ctx SM4 context to be initialized
* \param key 16-byte secret key
*/
void sm4_setkey_enc( sm4_context *ctx, unsigned char key[16] );
/**
* \brief SM4 key schedule (128-bit, decryption)
*
* \param ctx SM4 context to be initialized
* \param key 16-byte secret key
*/
void sm4_setkey_dec( sm4_context *ctx, unsigned char key[16] );
/**
* \brief SM4-ECB block encryption/decryption
* \param ctx SM4 context
* \param mode SM4_ENCRYPT or SM4_DECRYPT
* \param length length of the input data
* \param input input block
* \param output output block
*/
void sm4_crypt_ecb( sm4_context *ctx,
int mode,
int length,
unsigned char *input,
unsigned char *output);
/**
* \brief SM4-CBC buffer encryption/decryption
* \param ctx SM4 context
* \param mode SM4_ENCRYPT or SM4_DECRYPT
* \param length length of the input data
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
*/
void sm4_crypt_cbc( sm4_context *ctx,
int mode,
int length,
unsigned char iv[16],
unsigned char *input,
unsigned char *output );
#ifdef __cplusplus
}
#endif
#endif /* sm4.h */
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM4/sm4test.c
================================================
/*
* SM4/SMS4 algorithm test programme
* 2012-4-21
*/
#include <string.h>
#include <stdio.h>
#include "sm4.h"
int main()
{
unsigned char key[16] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
unsigned char input[16] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
unsigned char output[16];
sm4_context ctx;
unsigned long i;
//encrypt standard testing vector
sm4_setkey_enc(&ctx,key);
sm4_crypt_ecb(&ctx,1,16,input,output);
for(i=0;i<16;i++)
printf("%02x ", output[i]);
printf("\n");
//decrypt testing
sm4_setkey_dec(&ctx,key);
sm4_crypt_ecb(&ctx,0,16,output,output);
for(i=0;i<16;i++)
printf("%02x ", output[i]);
printf("\n");
//decrypt 1M times testing vector based on standards.
i = 0;
sm4_setkey_enc(&ctx,key);
while (i<1000000)
{
sm4_crypt_ecb(&ctx,1,16,input,input);
i++;
}
for(i=0;i<16;i++)
printf("%02x ", input[i]);
printf("\n");
return 0;
}
================================================
FILE: C/SM2_SM3_SM4_C语言实现/SM4/sms4.c
================================================
/* sms4.c
** SMS4 Encryption algorithm for wireless networks
**
** $Id: sms4.c 2009-12-31 14:41:57 tao.tang <$">emhmily@gmail.com>$
**
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc.
**/
#include <string.h>
#include <stdio.h>
/*#include "sms4.h"*/
#ifndef unlong
typedef unsigned long unlong;
#endif /* unlong */
#ifndef unchar
typedef unsigned char unchar;
#endif /* unchar */
/* define SMS4CROL for rotating left */
#define SMS4CROL(uval, bits) ((uval << bits) | (uval >> (0x20 - bits)))
/* define MASK code for selecting expected bits from a 32 bits value */
#define SMS4MASK3 0xFF000000
#define SMS4MASK2 0x00FF0000
#define SMS4MASK1 0x0000FF00
#define SMS4MASK0 0x000000FF
/* Sbox table: 8bits input convert to 8 bits output*/
static unchar SboxTable[16][16] =
{
{0xd6,0x90,0xe9,0xfe,0xcc,0xe1,0x3d,0xb7,0x16,0xb6,0x14,0xc2,0x28,0xfb,0x2c,0x05},
{0x2b,0x67,0x9a,0x76,0x2a,0xbe,0x04,0xc3,0xaa,0x44,0x13,0x26,0x49,0x86,0x06,0x99},
{0x9c,0x42,0x50,0xf4,0x91,0xef,0x98,0x7a,0x33,0x54,0x0b,0x43,0xed,0xcf,0xac,0x62},
{0xe4,0xb3,0x1c,0xa9,0xc9,0x08,0xe8,0x95,0x80,0xdf,0x94,0xfa,0x75,0x8f,0x3f,0xa6},
{0x47,0x07,0xa7,0xfc,0xf3,0x73,0x17,0xba,0x83,0x59,0x3c,0x19,0xe6,0x85,0x4f,0xa8},
{0x68,0x6b,0x81,0xb2,0x71,0x64,0xda,0x8b,0xf8,0xeb,0x0f,0x4b,0x70,0x56,0x9d,0x35},
{0x1e,0x24,0x0e,0x5e,0x63,0x58,0xd1,0xa2,0x25,0x22,0x7c,0x3b,0x01,0x21,0x78,0x87},
{0xd4,0x00,0x46,0x57,0x9f,0xd3,0x27,0x52,0x4c,0x36,0x02,0xe7,0xa0,0xc4,0xc8,0x9e},
{0xea,0xbf,0x8a,0xd2,0x40,0xc7,0x38,0xb5,0xa3,0xf7,0xf2,0xce,0xf9,0x61,0x15,0xa1},
{0xe0,0xae,0x5d,0xa4,0x9b,0x34,0x1a,0x55,0xad,0x93,0x32,0x30,0xf5,0x8c,0xb1,0xe3},
{0x1d,0xf6,0xe2,0x2e,0x82,0x66,0xca,0x60,0xc0,0x29,0x23,0xab,0x0d,0x53,0x4e,0x6f},
{0xd5,0xdb,0x37,0x45,0xde,0xfd,0x8e,0x2f,0x03,0xff,0x6a,0x72,0x6d,0x6c,0x5b,0x51},
{0x8d,0x1b,0xaf,0x92,0xbb,0xdd,0xbc,0x7f,0x11,0xd9,0x5c,0x41,0x1f,0x10,0x5a,0xd8},
{0x0a,0xc1,0x31,0x88,0xa5,0xcd,0x7b,0xbd,0x2d,0x74,0xd0,0x12,0xb8,0xe5,0xb4,0xb0},
{0x89,0x69,0x97,0x4a,0x0c,0x96,0x77,0x7e,0x65,0xb9,0xf1,0x09,0xc5,0x6e,0xc6,0x84},
{0x18,0xf0,0x7d,0xec,0x3a,0xdc,0x4d,0x20,0x79,0xee,0x5f,0x3e,0xd7,0xcb,0x39,0x48}
};
/* Encryption key: 128bits */
static unlong MK[4] = {0x01234567,0x89abcdef,0xfedcba98,0x76543210};
/* System parameter */
static unlong FK[4] = {0xa3b1bac6,0x56aa3350,0x677d9197,0xb27022dc};
/* fixed parameter */
static unlong CK[32] =
{
0x00070e15,0x1c232a31,0x383f464d,0x545b6269,
0x70777e85,0x8c939aa1,0xa8afb6bd,0xc4cbd2d9,
0xe0e7eef5,0xfc030a11,0x181f262d,0x343b4249,
0x50575e65,0x6c737a81,0x888f969d,0xa4abb2b9,
0xc0c7ced5,0xdce3eaf1,0xf8ff060d,0x141b2229,
0x30373e45,0x4c535a61,0x686f767d,0x848b9299,
0xa0a7aeb5,0xbcc3cad1,0xd8dfe6ed,0xf4fb0209,
0x10171e25,0x2c333a41,0x484f565d,0x646b7279
};
/* buffer for round encryption key */
static unlong ENRK[32];
static unlong DERK[32];
/* original contents for debugging */
unlong pData[4] =
{
0x01234567,
0x89abcdef,
0xfedcba98,
0x76543210
};
/* original contents for debugging */
unlong pData2[9] =
{
0x01234567,
0x89abcdef,
0xfedcba98,
0x76543210,
0x12121212,
0x34343434,
0x56565656,
0x78787878,
0x12341234
};
/*=============================================================================
** private function:
** look up in SboxTable and get the related value.
** args: [in] inch: 0x00~0xFF (8 bits unsigned value).
**============================================================================*/
static unchar SMS4Sbox(unchar inch)
{
unchar *pTable = (unchar *)SboxTable;
unchar retVal = (unchar)(pTable[inch]);
return retVal;
}
/*=============================================================================
** private function:
** "T algorithm" == "L algorithm" + "t algorithm".
** args: [in] a: a is a 32 bits unsigned value;
** return: c: c is calculated with line algorithm "L" and nonline algorithm "t"
**============================================================================*/
static unlong SMS4Lt(unlong a)
{
unlong b = 0;
unlong c = 0;
unchar a0 = (unchar)(a & SMS4MASK0);
unchar a1 = (unchar)((a & SMS4MASK1) >> 8);
unchar a2 = (unchar)((a & SMS4MASK2) >> 16);
unchar a3 = (unchar)((a & SMS4MASK3) >> 24);
unchar b0 = SMS4Sbox(a0);
unchar b1 = SMS4Sbox(a1);
unchar b2 = SMS4Sbox(a2);
unchar b3 = SMS4Sbox(a3);
b =b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
c =b^(SMS4CROL(b, 2))^(SMS4CROL(b, 10))^(SMS4CROL(b, 18))^(SMS4CROL(b, 24));
return c;
}
/*=============================================================================
** private function:
** Calculating round encryption key.
** args: [in] a: a is a 32 bits unsigned value;
** return: ENRK[i]: i{0,1,2,3,...31}.
**============================================================================*/
static unlong SMS4CalciRK(unlong a)
{
unlong b = 0;
unlong rk = 0;
unchar a0 = (unchar)(a & SMS4MASK0);
unchar a1 = (unchar)((a & SMS4MASK1) >> 8);
unchar a2 = (unchar)((a & SMS4MASK2) >> 16);
unchar a3 = (unchar)((a & SMS4MASK3) >> 24);
unchar b0 = SMS4Sbox(a0);
unchar b1 = SMS4Sbox(a1);
unchar b2 = SMS4Sbox(a2);
unchar b3 = SMS4Sbox(a3);
b = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
rk = b^(SMS4CROL(b, 13))^(SMS4CROL(b, 23));
return rk;
}
/*=============================================================================
** private function:
** Calculating round encryption key.
** args: [in] ulflag: if 0: not calculate DERK , else calculate;
** return: NONE.
**============================================================================*/
static void SMS4CalcRK(unlong ulflag)
{
unlong k[36];
unlong i = 0;
k[0] = MK[0]^FK[0];
k[1] = MK[1]^FK[1];
k[2] = MK[2]^FK[2];
k[3] = MK[3]^FK[3];
for(; i<32; i++)
{
k[i+4] = k[i] ^ (SMS4CalciRK(k[i+1]^k[i+2]^k[i+3]^CK[i]));
ENRK[i] = k[i+4];
}
if (ulflag != 0x00)
{
for (i=0; i<32; i++)
{
DERK[i] = ENRK[31-i];
}
}
}
/*=============================================================================
** private function:
** "T algorithm" == "L algorithm" + "t algorithm".
** args: [in] a: a is a 32 bits unsigned value.
**============================================================================*/
static unlong SMS4T(unlong a)
{
return (SMS4Lt(a));
}
/*=============================================================================
** private function:
** Calculating and getting encryption/decryption contents.
** args: [in] x0: original contents;
** args: [in] x1: original contents;
** args: [in] x2: original contents;
** args: [in] x3: original contents;
** args: [in] rk: encryption/decryption key;
** return the contents of encryption/decryption contents.
**============================================================================*/
static unlong SMS4F(unlong x0, unlong x1, unlong x2, unlong x3, unlong rk)
{
return (x0^SMS4Lt(x1^x2^x3^rk));
}
/*=============================================================================
** public function:
** "T algorithm" == "L algorithm" + "t algorithm".
** args: [in] ulkey: password defined by user(NULL: default encryption key);
** args: [in] flag: if 0: not calculate DERK , else calculate;
** return ulkey: NULL for default encryption key.
**============================================================================*/
unlong *SMS4SetKey(unlong *ulkey, unlong flag)
{
if (ulkey != NULL)
{
memcpy(MK, ulkey, sizeof(MK));
}
SMS4CalcRK(flag);
return ulkey;
}
/*=============================================================================
** public function:
** sms4 encryption algorithm.
** args: [in/out] psrc: a pointer point to original contents;
** args: [in] lgsrc: the length of original contents;
** args: [in] derk: a pointer point to encryption/decryption key;
** return: pRet: a pointer point to encrypted contents.
**============================================================================*/
unlong *SMS4Encrypt(unlong *psrc, unlong lgsrc, unlong rk[])
{
unlong *pRet = NULL;
unlong i = 0;
unlong ulbuf[36];
unlong ulCnter = 0;
unlong ulTotal = (lgsrc >> 4);
if(psrc != NULL)
{
pRet = psrc;
/* !!!It's a temporary scheme: start!!! */
/*========================================
** 16 bytes(128 bits) is deemed as an unit.
**======================================*/
while (ulCnter<ulTotal)
{
/* reset number counter */
i = 0;
/* filled up with 0*/
memset(ulbuf, 0, sizeof(ulbuf));
memcpy(ulbuf, psrc, 16);
#ifdef SMS4DBG0
printf("0x%08x, 0x%08x, 0x%08x, 0x%08x, \n",
ulbuf[0], ulbuf[1], ulbuf[2], ulbuf[3]);
#endif /* SMS4DBG0 */
while(i<32)
{
ulbuf[i+4] = SMS4F(ulbuf[i], ulbuf[i+1],
ulbuf[i+2], ulbuf[i+3], rk[i]);
#ifdef SMS4DBG0
printf("0x%08x, \n", ulbuf[i+4]);
#endif /* SMS4DBG0 */
i++;
}
/* save encrypted contents to original area */
psrc[0] = ulbuf[35];
psrc[1] = ulbuf[34];
psrc[2] = ulbuf[33];
psrc[3] = ulbuf[32];
ulCnter++;
psrc += 4;
}
/* !!!It's a temporary scheme: end!!! */
}
return pRet;
}
/*=============================================================================
** public function:
** sms4 decryption algorithm.
** args: [in/out] psrc: a pointer point to encrypted contents;
** args: [in] lgsrc: the length of encrypted contents;
** args: [in] derk: a pointer point to decryption key;
** return: pRet: a pointer point to decrypted contents.
**============================================================================*/
unlong *SMS4Decrypt(unlong *psrc, unlong lgsrc, unlong derk[])
{
unlong *pRet = NULL;
unlong i = 0;
if(psrc != NULL)
{
pRet = psrc;
/* the same arithmetic, different encryption key sequence. */
SMS4Encrypt(psrc, lgsrc, derk);
}
return pRet;
}
void SMS4Encrypt1M()
{
unlong i = 0;
while (i<1000000)
{
SMS4Encrypt(pData, sizeof(pData), ENRK);
i++;
// if (0 == i%10000)
// {
// printf("encrypted times: %d\n", i);
// }
}
printf("0x%08x, 0x%08x, 0x%08x, 0x%08x. \n",
pData[0], pData[1], pData[2], pData[3]);
}
/* entry-point for debugging */
int main()
{
SMS4SetKey(NULL, 1);
/* cycle1: common test */
printf("0x%08x, 0x%08x, 0x%08x, 0x%08x. \n",
pData[0], pData[1], pData[2], pData[3]);
SMS4Encrypt(pData, sizeof(pData), ENRK);
printf("0x%08x, 0x%08x, 0x%08x, 0x%08x. \n",
pData[0], pData[1], pData[2], pData[3]);
SMS4Decrypt(pData, sizeof(pData), DERK);
printf("0x%08x, 0x%08x, 0x%08x, 0x%08x. \n",
pData[0], pData[1], pData[2], pData[3]);
/* cycle2: encrypted 1000000 times */
SMS4Encrypt1M();
/* cycle3: longer contents */
SMS4Encrypt(pData2, sizeof(pData2), ENRK);
SMS4Decrypt(pData2, sizeof(pData2), DERK);
return 0;
}
================================================
FILE: C/sm4.c
================================================
/*
* SM4 Encryption alogrithm (SMS4 algorithm)
* GM/T 0002-2012 Chinese National Standard ref:http://www.oscca.gov.cn/
* thanks to Xyssl
* thnaks and refers to http://hi.baidu.com/numax/blog/item/80addfefddfb93e4cf1b3e61.html
* author:goldboar
* email:goldboar@163.com
* 2012-4-20
*/
#define SM4_ENCRYPT 1
#define SM4_DECRYPT 0
/**
* \brief SM4 context structure
*/
typedef struct
{
int mode; /*!< encrypt/decrypt */
unsigned long sk[32]; /*!< SM4 subkeys */
}
sm4_context;
/**
* \brief SM4 key schedule (128-bit, encryption)
*
* \param ctx SM4 context to be initialized
* \param key 16-byte secret key
*/
void sm4_setkey_enc( sm4_context *ctx, unsigned char key[16] );
/**
* \brief SM4 key schedule (128-bit, decryption)
*
* \param ctx SM4 context to be initialized
* \param key 16-byte secret key
*/
void sm4_setkey_dec( sm4_context *ctx, unsigned char key[16] );
/**
* \brief SM4-ECB block encryption/decryption
* \param ctx SM4 context
* \param mode SM4_ENCRYPT or SM4_DECRYPT
* \param length length of the input data
* \param input input block
* \param output output block
*/
void sm4_crypt_ecb( sm4_context *ctx,
int mode,
int length,
unsigned char *input,
unsigned char *output);
/**
* \brief SM4-CBC buffer encryption/decryption
* \param ctx SM4 context
* \param mode SM4_ENCRYPT or SM4_DECRYPT
* \param length length of the input data
* \param iv initialization vector (updated after use)
* \param input buffer holding the input data
* \param output buffer holding the output data
*/
void sm4_crypt_cbc( sm4_context *ctx,
int mode,
int length,
unsigned char iv[16],
unsigned char *input,
unsigned char *output );
// Test vector 1
// plain: 01 23 45 67 89 ab cd ef fe dc ba 98 76 54 32 10
// key: 01 23 45 67 89 ab cd ef fe dc ba 98 76 54 32 10
// round key and temp computing result:
// rk[ 0] = f12186f9 X[ 0] = 27fad345
// rk[ 1] = 41662b61 X[ 1] = a18b4cb2
// rk[ 2] = 5a6ab19a X[ 2] = 11c1e22a
// rk[ 3] = 7ba92077 X[ 3] = cc13e2ee
// rk[ 4] = 367360f4 X[ 4] = f87c5bd5
// rk[ 5] = 776a0c61 X[ 5] = 33220757
// rk[ 6] = b6bb89b3 X[ 6] = 77f4c297
// rk[ 7] = 24763151 X[ 7] = 7a96f2eb
// rk[ 8] = a520307c X[ 8] = 27dac07f
// rk[ 9] = b7584dbd X[ 9] = 42dd0f19
// rk[10] = c30753ed X[10] = b8a5da02
// rk[11] = 7ee55b57 X[11] = 907127fa
// rk[12] = 6988608c X[12] = 8b952b83
// rk[13] = 30d895b7 X[13] = d42b7c59
// rk[14] = 44ba14af X[14] = 2ffc5831
// rk[15] = 104495a1 X[15] = f69e6888
// rk[16] = d120b428 X[16] = af2432c4
// rk[17] = 73b55fa3 X[17] = ed1ec85e
// rk[18] = cc874966 X[18] = 55a3ba22
// rk[19] = 92244439 X[19] = 124b18aa
// rk[20] = e89e641f X[20] = 6ae7725f
// rk[21] = 98ca015a X[21] = f4cba1f9
// rk[22] = c7159060 X[22] = 1dcdfa10
// rk[23] = 99e1fd2e X[23] = 2ff60603
// rk[24] = b79bd80c X[24] = eff24fdc
// rk[25] = 1d2115b0 X[25] = 6fe46b75
// rk[26] = 0e228aeb X[26] = 893450ad
// rk[27] = f1780c81 X[27] = 7b938f4c
// rk[28] = 428d3654 X[28] = 536e4246
// rk[29] = 62293496 X[29] = 86b3e94f
// rk[30] = 01cf72e5 X[30] = d206965e
// rk[31] = 9124a012 X[31] = 681edf34
// cypher: 68 1e df 34 d2 06 96 5e 86 b3 e9 4f 53 6e 42 46
//
// test vector 2
// the same key and plain 1000000 times coumpting
// plain: 01 23 45 67 89 ab cd ef fe dc ba 98 76 54 32 10
// key: 01 23 45 67 89 ab cd ef fe dc ba 98 76 54 32 10
// cypher: 59 52 98 c7 c6 fd 27 1f 04 02 f8 04 c3 3d 3f 66
#include <string.h>
#include <stdio.h>
#include <time.h>
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_ULONG_BE
#define GET_ULONG_BE(n,b,i) \
{ \
(n) = ( (unsigned long) (b)[(i) ] << 24 ) \
| ( (unsigned long) (b)[(i) + 1] << 16 ) \
| ( (unsigned long) (b)[(i) + 2] << 8 ) \
| ( (unsigned long) (b)[(i) + 3] ); \
}
#endif
#ifndef PUT_ULONG_BE
#define PUT_ULONG_BE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
}
#endif
/*
*rotate shift left marco definition
*
*/
#define SHL(x,n) (((x) & 0xFFFFFFFF) << n)
#define ROTL(x,n) (SHL((x),n) | ((x) >> (32 - n)))
#define SWAP(a,b) { unsigned long t = a; a = b; b = t; t = 0; }
/*
* Expanded SM4 S-boxes
/* Sbox table: 8bits input convert to 8 bits output*/
static const unsigned char SboxTable[16][16] =
{
{0xd6,0x90,0xe9,0xfe,0xcc,0xe1,0x3d,0xb7,0x16,0xb6,0x14,0xc2,0x28,0xfb,0x2c,0x05},
{0x2b,0x67,0x9a,0x76,0x2a,0xbe,0x04,0xc3,0xaa,0x44,0x13,0x26,0x49,0x86,0x06,0x99},
{0x9c,0x42,0x50,0xf4,0x91,0xef,0x98,0x7a,0x33,0x54,0x0b,0x43,0xed,0xcf,0xac,0x62},
{0xe4,0xb3,0x1c,0xa9,0xc9,0x08,0xe8,0x95,0x80,0xdf,0x94,0xfa,0x75,0x8f,0x3f,0xa6},
{0x47,0x07,0xa7,0xfc,0xf3,0x73,0x17,0xba,0x83,0x59,0x3c,0x19,0xe6,0x85,0x4f,0xa8},
{0x68,0x6b,0x81,0xb2,0x71,0x64,0xda,0x8b,0xf8,0xeb,0x0f,0x4b,0x70,0x56,0x9d,0x35},
{0x1e,0x24,0x0e,0x5e,0x63,0x58,0xd1,0xa2,0x25,0x22,0x7c,0x3b,0x01,0x21,0x78,0x87},
{0xd4,0x00,0x46,0x57,0x9f,0xd3,0x27,0x52,0x4c,0x36,0x02,0xe7,0xa0,0xc4,0xc8,0x9e},
{0xea,0xbf,0x8a,0xd2,0x40,0xc7,0x38,0xb5,0xa3,0xf7,0xf2,0xce,0xf9,0x61,0x15,0xa1},
{0xe0,0xae,0x5d,0xa4,0x9b,0x34,0x1a,0x55,0xad,0x93,0x32,0x30,0xf5,0x8c,0xb1,0xe3},
{0x1d,0xf6,0xe2,0x2e,0x82,0x66,0xca,0x60,0xc0,0x29,0x23,0xab,0x0d,0x53,0x4e,0x6f},
{0xd5,0xdb,0x37,0x45,0xde,0xfd,0x8e,0x2f,0x03,0xff,0x6a,0x72,0x6d,0x6c,0x5b,0x51},
{0x8d,0x1b,0xaf,0x92,0xbb,0xdd,0xbc,0x7f,0x11,0xd9,0x5c,0x41,0x1f,0x10,0x5a,0xd8},
{0x0a,0xc1,0x31,0x88,0xa5,0xcd,0x7b,0xbd,0x2d,0x74,0xd0,0x12,0xb8,0xe5,0xb4,0xb0},
{0x89,0x69,0x97,0x4a,0x0c,0x96,0x77,0x7e,0x65,0xb9,0xf1,0x09,0xc5,0x6e,0xc6,0x84},
{0x18,0xf0,0x7d,0xec,0x3a,0xdc,0x4d,0x20,0x79,0xee,0x5f,0x3e,0xd7,0xcb,0x39,0x48}
};
/* System parameter */
static const unsigned long FK[4] = {0xa3b1bac6,0x56aa3350,0x677d9197,0xb27022dc};
/* fixed parameter */
static const unsigned long CK[32] =
{
0x00070e15,0x1c232a31,0x383f464d,0x545b6269,
0x70777e85,0x8c939aa1,0xa8afb6bd,0xc4cbd2d9,
0xe0e7eef5,0xfc030a11,0x181f262d,0x343b4249,
0x50575e65,0x6c737a81,0x888f969d,0xa4abb2b9,
0xc0c7ced5,0xdce3eaf1,0xf8ff060d,0x141b2229,
0x30373e45,0x4c535a61,0x686f767d,0x848b9299,
0xa0a7aeb5,0xbcc3cad1,0xd8dfe6ed,0xf4fb0209,
0x10171e25,0x2c333a41,0x484f565d,0x646b7279
};
/*
* private function:
* look up in SboxTable and get the related value.
* args: [in] inch: 0x00~0xFF (8 bits unsigned value).
*/
static unsigned char sm4Sbox(unsigned char inch)
{
unsigned char *pTable = (unsigned char *)SboxTable;
unsigned char retVal = (unsigned char)(pTable[inch]);
return retVal;
}
/*
* private F(Lt) function:
* "T algorithm" == "L algorithm" + "t algorithm".
* args: [in] a: a is a 32 bits unsigned value;
* return: c: c is calculated with line algorithm "L" and nonline algorithm "t"
*/
static unsigned long sm4Lt(unsigned long ka)
{
unsigned long bb = 0;
unsigned long c = 0;
unsigned char a[4];
unsigned char b[4];
PUT_ULONG_BE(ka,a,0)
b[0] = sm4Sbox(a[0]);
b[1] = sm4Sbox(a[1]);
b[2] = sm4Sbox(a[2]);
b[3] = sm4Sbox(a[3]);
GET_ULONG_BE(bb,b,0)
c =bb^(ROTL(bb, 2))^(ROTL(bb, 10))^(ROTL(bb, 18))^(ROTL(bb, 24));
return c;
}
/*
* private F function:
* Calculating and getting encryption/decryption contents.
* args: [in] x0: original contents;
* args: [in] x1: original contents;
* args: [in] x2: original contents;
* args: [in] x3: original contents;
* args: [in] rk: encryption/decryption key;
* return the contents of encryption/decryption contents.
*/
static unsigned long sm4F(unsigned long x0, unsigned long x1, unsigned long x2, unsigned long x3, unsigned long rk)
{
return (x0^sm4Lt(x1^x2^x3^rk));
}
/* private function:
* Calculating round encryption key.
* args: [in] a: a is a 32 bits unsigned value;
* return: sk[i]: i{0,1,2,3,...31}.
*/
static unsigned long sm4CalciRK(unsigned long ka)
{
unsigned long bb = 0;
unsigned long rk = 0;
unsigned char a[4];
unsigned char b[4];
PUT_ULONG_BE(ka,a,0)
b[0] = sm4Sbox(a[0]);
b[1] = sm4Sbox(a[1]);
b[2] = sm4Sbox(a[2]);
b[3] = sm4Sbox(a[3]);
GET_ULONG_BE(bb,b,0)
rk = bb^(ROTL(bb, 13))^(ROTL(bb, 23));
return rk;
}
static void sm4_setkey( unsigned long SK[32], unsigned char key[16] )
{
unsigned long MK[4];
unsigned long k[36];
unsigned long i = 0;
GET_ULONG_BE( MK[0], key, 0 );
GET_ULONG_BE( MK[1], key, 4 );
GET_ULONG_BE( MK[2], key, 8 );
GET_ULONG_BE( MK[3], key, 12 );
k[0] = MK[0]^FK[0];
k[1] = MK[1]^FK[1];
k[2] = MK[2]^FK[2];
k[3] = MK[3]^FK[3];
for(; i<32; i++)
{
k[i+4] = k[i] ^ (sm4CalciRK(k[i+1]^k[i+2]^k[i+3]^CK[i]));
SK[i] = k[i+4];
}
}
/*
* SM4 standard one round processing
*
*/
static void sm4_one_round( unsigned long sk[32],
unsigned char input[16],
unsigned char output[16] )
{
unsigned long i = 0;
unsigned long ulbuf[36];
memset(ulbuf, 0, sizeof(ulbuf));
GET_ULONG_BE( ulbuf[0], input, 0 )
GET_ULONG_BE( ulbuf[1], input, 4 )
GET_ULONG_BE( ulbuf[2], input, 8 )
GET_ULONG_BE( ulbuf[3], input, 12 )
while(i<32)
{
ulbuf[i+4] = sm4F(ulbuf[i], ulbuf[i+1], ulbuf[i+2], ulbuf[i+3], sk[i]);
// #ifdef _DEBUG
// printf("rk(%02d) = 0x%08x, X(%02d) = 0x%08x \n",i,sk[i], i, ulbuf[i+4] );
// #endif
i++;
}
PUT_ULONG_BE(ulbuf[35],output,0);
PUT_ULONG_BE(ulbuf[34],output,4);
PUT_ULONG_BE(ulbuf[33],output,8);
PUT_ULONG_BE(ulbuf[32],output,12);
}
/*
* SM4 key schedule (128-bit, encryption)
*/
void sm4_setkey_enc( sm4_context *ctx, unsigned char key[16] )
{
ctx->mode = SM4_ENCRYPT;
sm4_setkey( ctx->sk, key );
}
/*
* SM4 key schedule (128-bit, decryption)
*/
void sm4_setkey_dec( sm4_context *ctx, unsigned char key[16] )
{
int i;
ctx->mode = SM4_ENCRYPT;
sm4_setkey( ctx->sk, key );
for( i = 0; i < 16; i ++ )
{
SWAP( ctx->sk[ i ], ctx->sk[ 31-i] );
}
}
/*
* SM4-ECB block encryption/decryption
*/
void sm4_crypt_ecb( sm4_context *ctx,
int mode,
int length,
unsigned char *input,
unsigned char *output)
{
while( length > 0 )
{
sm4_one_round( ctx->sk, input, output );
input += 16;
output += 16;
length -= 16;
}
}
/*
* SM4-CBC buffer encryption/decryption
*/
void sm4_crypt_cbc( sm4_context *ctx,
int mode,
int length,
unsigned char iv[16],
unsigned char *input,
unsigned char *output )
{
int i;
unsigned char temp[16];
if( mode == SM4_ENCRYPT )
{
while( length > 0 )
{
for( i = 0; i < 16; i++ )
output[i] = (unsigned char)( input[i] ^ iv[i] );
sm4_one_round( ctx->sk, output, output );
memcpy( iv, output, 16 );
input += 16;
output += 16;
length -= 16;
}
}
else /* SM4_DECRYPT */
{
while( length > 0 )
{
memcpy( temp, input, 16 );
sm4_one_round( ctx->sk, input, output );
for( i = 0; i < 16; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, 16 );
input += 16;
output += 16;
length -= 16;
}
}
}
int main()
{
unsigned char key[16] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
unsigned char input[16] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
unsigned char output[16];
sm4_context ctx;
unsigned long i;
//encrypt standard testing vector
// sm4_setkey_enc(&ctx,key);
// sm4_crypt_ecb(&ctx,1,16,input,output);
// for(i=0;i<16;i++)
// printf("%02x ", output[i]);
// printf("\n");
//decrypt testing
// sm4_setkey_dec(&ctx,key);
// sm4_crypt_ecb(&ctx,0,16,output,output);
// for(i=0;i<16;i++)
// printf("%02x ", output[i]);
// printf("\n");
//decrypt 1M times testing vector based on standards.
#include <time.h>
time_t c_start, c_end;
c_start = clock();
i = 0;
sm4_setkey_enc(&ctx,key);
while (i<1000000)
{
sm4_crypt_ecb(&ctx,1,16,input,input);
i++;
}
for(i=0;i<16;i++)
printf("%02x ", input[i]);
printf("\n");
c_end = clock();
printf("run 1000000 times used %f ms \n",difftime(c_end,c_start));
return 0;
}
================================================
FILE: Java/JavaSM4.java
================================================
public class JavaSM4 {
public static int[] key = new int[4];
public static int[] temp = new int[4];
public static int[] rkey = new int[32];
public static int[] fk = {0xa3b1bac6, 0x56AA3350, 0x677d9197, 0xb27022dc};
public static int[] ck = {
0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,
0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,
0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229,
0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209,
0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279};
private static int[] sbi = {
0xd6,0x90,0xe9,0xfe,0xcc,0xe1,0x3d,0xb7,0x16,0xb6,0x14,0xc2,0x28,0xfb,0x2c,0x05,
0x2b,0x67,0x9a,0x76,0x2a,0xbe,0x04,0xc3,0xaa,0x44,0x13,0x26,0x49,0x86,0x06,0x99,
0x9c,0x42,0x50,0xf4,0x91,0xef,0x98,0x7a,0x33,0x54,0x0b,0x43,0xed,0xcf,0xac,0x62,
0xe4,0xb3,0x1c,0xa9,0xc9,0x08,0xe8,0x95,0x80,0xdf,0x94,0xfa,0x75,0x8f,0x3f,0xa6,
0x47,0x07,0xa7,0xfc,0xf3,0x73,0x17,0xba,0x83,0x59,0x3c,0x19,0xe6,0x85,0x4f,0xa8,
0x68,0x6b,0x81,0xb2,0x71,0x64,0xda,0x8b,0xf8,0xeb,0x0f,0x4b,0x70,0x56,0x9d,0x35,
0x1e,0x24,0x0e,0x5e,0x63,0x58,0xd1,0xa2,0x25,0x22,0x7c,0x3b,0x01,0x21,0x78,0x87,
0xd4,0x00,0x46,0x57,0x9f,0xd3,0x27,0x52,0x4c,0x36,0x02,0xe7,0xa0,0xc4,0xc8,0x9e,
0xea,0xbf,0x8a,0xd2,0x40,0xc7,0x38,0xb5,0xa3,0xf7,0xf2,0xce,0xf9,0x61,0x15,0xa1,
0xe0,0xae,0x5d,0xa4,0x9b,0x34,0x1a,0x55,0xad,0x93,0x32,0x30,0xf5,0x8c,0xb1,0xe3,
0x1d,0xf6,0xe2,0x2e,0x82,0x66,0xca,0x60,0xc0,0x29,0x23,0xab,0x0d,0x53,0x4e,0x6f,
0xd5,0xdb,0x37,0x45,0xde,0xfd,0x8e,0x2f,0x03,0xff,0x6a,0x72,0x6d,0x6c,0x5b,0x51,
0x8d,0x1b,0xaf,0x92,0xbb,0xdd,0xbc,0x7f,0x11,0xd9,0x5c,0x41,0x1f,0x10,0x5a,0xd8,
0x0a,0xc1,0x31,0x88,0xa5,0xcd,0x7b,0xbd,0x2d,0x74,0xd0,0x12,0xb8,0xe5,0xb4,0xb0,
0x89,0x69,0x97,0x4a,0x0c,0x96,0x77,0x7e,0x65,0xb9,0xf1,0x09,0xc5,0x6e,0xc6,0x84,
0x18,0xf0,0x7d,0xec,0x3a,0xdc,0x4d,0x20,0x79,0xee,0x5f,0x3e,0xd7,0xcb,0x39,0x48};
public static void main(String[] args)
{
JavaSM4 sm = new JavaSM4();
int[] msg = {0x01234567, 0x89abcdef, 0xfedcba98, 0x76543210};
int[] smsg = {0x595298c7, 0xc6fd271f, 0x0402f804, 0xc33d3f66};
key[0] = 0x01234567;
key[1] = 0x89abcdef;
key[2] = 0xfedcba98;
key[3] = 0x76543210;
// int j=0,n=1000000;
int j=0,n=1000000;
long startTime = System.currentTimeMillis(); // start time
for(j=0; j<n; j++)
{
//msg = sm4(msg,1);// encode
smsg = sm4(smsg,0);// decode
}
long endTime = System.currentTimeMillis(); // end time
System.out.println(" Run "+n+" times: "+(endTime-startTime)+"ms");
}
private static int[] sm4(int[] t,int s)
{
rkey = initrk();
if(s == 0)
{
rkey = r(rkey);
}
int[] x = new int[36];
x[0] = t[0];
x[1] = t[1];
x[2] = t[2];
x[3] = t[3];
int i;
for(i=0;i<32;i++)
{
x[i+4] = f(x[i],x[i+1],x[i+2],x[i+3],rkey[i]);
}
x = r(x);
temp[0] = x[0];
temp[1] = x[1];
temp[2] = x[2];
temp[3] = x[3];
return temp;
}
private static int[] initrk()
{
int i;
int[] k = new int[36];
int[] rk = new int[32];
k[0] = key[0] ^ fk[0];
k[1] = key[1] ^ fk[1];
k[2] = key[2] ^ fk[2];
k[3] = key[3] ^ fk[3];
for(i=0;i<32;i++)
{
rk[i] = k[i+4] = k[i] ^ tn(k[i+1]^k[i+2]^k[i+3]^ck[i]);
}
return rk;
}
private static int[] r(int[] x)
{
int[] t = new int[x.length];
int i;
for(i=0; i<x.length; i++)
{
t[i] = x[x.length - 1 -i];
}
return t;
}
private static int f(int x0,int x1,int x2,int x3,int k)
{
return (x0 ^ t(x1 ^ x2 ^ x3 ^ k));
}
private static int t(int ta)
{
return l(tj(ta));
}
private static int tn(int ta)
{
return ln(tj(ta));
}
private static int l(int temp)
{
return temp ^ Px(temp,2) ^ Px(temp,10) ^ Px(temp,18) ^ Px(temp,24);
}
private static int ln(int temp)
{
return temp ^ Px(temp,13) ^ Px(temp,23);
}
private static int tj(int a)
{
byte[] b = new byte[4];
byte[] c = new byte[4];
c = intToBytes(a);
b[0] = sbox(c[0]);
b[1] = sbox(c[1]);
b[2] = sbox(c[2]);
b[3] = sbox(c[3]);
a = bytesToInt(b[0],b[1],b[2],b[3]);
return a;
}
private static byte sbox(byte a)
{
int t = (a << 24) >>> 24;
return (byte)sbi[t];
}
private static int Px(int x,int n)
{
return ((x<<n)|(x>>>(32-n)));
}
private static int bytesToInt(byte b0,byte b1,byte b2,byte b3) // int = 4 * byte = 32 bit unsigned
{
int tint = 0;
int temp = b0 << 24;
tint = temp;
temp = (b1 << 24) >>> 8;
tint |= temp;
temp = (b2 << 24) >>> 16;
tint |= temp;
temp = (b3 << 24) >>> 24;
tint |= temp;
return tint;
}
private static byte[] intToBytes(int i)
{
byte[] tbyte = new byte[4];
tbyte[0] = (byte)(i >>> 24);
tbyte[1] = (byte)((i<<8)>>>24);
tbyte[2] = (byte)((i<<16)>>>24);
tbyte[3] = (byte)((i<<24)>>>24);
return tbyte;
}
}
================================================
FILE: JavaScript/demo/js/asn1-1.0.js
================================================
/*! asn1-1.0.4.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license
*/
/*
* asn1.js - ASN.1 DER encoder classes
*
* Copyright (c) 2013 Kenji Urushima (kenji.urushima@gmail.com)
*
* This software is licensed under the terms of the MIT License.
* http://kjur.github.com/jsrsasign/license
*
* The above copyright and license notice shall be
* included in all copies or substantial portions of the Software.
*/
/**
* @fileOverview
* @name asn1-1.0.js
* @author Kenji Urushima kenji.urushima@gmail.com
* @version asn1 1.0.4 (2013-Oct-02)
* @since jsrsasign 2.1
* @license <a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
*/
/**
* kjur's class library name space
* <p>
* This name space provides following name spaces:
* <ul>
* <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
* <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
* <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
* class and utilities</li>
* </ul>
* </p>
* NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
* @name KJUR
* @namespace kjur's class library name space
*/
if (typeof KJUR == "undefined" || !KJUR) KJUR = {};
/**
* kjur's ASN.1 class library name space
* <p>
* This is ITU-T X.690 ASN.1 DER encoder class library and
* class structure and methods is very similar to
* org.bouncycastle.asn1 package of
* well known BouncyCaslte Cryptography Library.
*
* <h4>PROVIDING ASN.1 PRIMITIVES</h4>
* Here are ASN.1 DER primitive classes.
* <ul>
* <li>0x01 {@link KJUR.asn1.DERBoolean}</li>
* <li>0x02 {@link KJUR.asn1.DERInteger}</li>
* <li>0x03 {@link KJUR.asn1.DERBitString}</li>
* <li>0x04 {@link KJUR.asn1.DEROctetString}</li>
* <li>0x05 {@link KJUR.asn1.DERNull}</li>
* <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li>
* <li>0x0c {@link KJUR.asn1.DERUTF8String}</li>
* <li>0x12 {@link KJUR.asn1.DERNumericString}</li>
* <li>0x13 {@link KJUR.asn1.DERPrintableString}</li>
* <li>0x14 {@link KJUR.asn1.DERTeletexString}</li>
* <li>0x16 {@link KJUR.asn1.DERIA5String}</li>
* <li>0x17 {@link KJUR.asn1.DERUTCTime}</li>
* <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li>
* <li>0x30 {@link KJUR.asn1.DERSequence}</li>
* <li>0x31 {@link KJUR.asn1.DERSet}</li>
* </ul>
*
* <h4>OTHER ASN.1 CLASSES</h4>
* <ul>
* <li>{@link KJUR.asn1.ASN1Object}</li>
* <li>{@link KJUR.asn1.DERAbstractString}</li>
* <li>{@link KJUR.asn1.DERAbstractTime}</li>
* <li>{@link KJUR.asn1.DERAbstractStructured}</li>
* <li>{@link KJUR.asn1.DERTaggedObject}</li>
* </ul>
* </p>
* NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
* @name KJUR.asn1
* @namespace
*/
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
/**
* ASN1 utilities class
* @name KJUR.asn1.ASN1Util
* @class ASN1 utilities class
* @since asn1 1.0.2
*/
KJUR.asn1.ASN1Util = new function() {
this.integerToByteHex = function(i) {
var h = i.toString(16);
if ((h.length % 2) == 1) h = '0' + h;
return h;
};
this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
var h = bigIntegerValue.toString(16);
if (h.substr(0, 1) != '-') {
if (h.length % 2 == 1) {
h = '0' + h;
} else {
if (! h.match(/^[0-7]/)) {
h = '00' + h;
}
}
} else {
var hPos = h.substr(1);
var xorLen = hPos.length;
if (xorLen % 2 == 1) {
xorLen += 1;
} else {
if (! h.match(/^[0-7]/)) {
xorLen += 2;
}
}
var hMask = '';
for (var i = 0; i < xorLen; i++) {
hMask += 'f';
}
var biMask = new BigInteger(hMask, 16);
var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
h = biNeg.toString(16).replace(/^-/, '');
}
return h;
};
/**
* get PEM string from hexadecimal data and header string
* @name getPEMStringFromHex
* @memberOf KJUR.asn1.ASN1Util
* @function
* @param {String} dataHex hexadecimal string of PEM body
* @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
* @return {String} PEM formatted string of input data
* @description
* @example
* var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
* // value of pem will be:
* -----BEGIN PRIVATE KEY-----
* YWFh
* -----END PRIVATE KEY-----
*/
this.getPEMStringFromHex = function(dataHex, pemHeader) {
var ns1 = KJUR.asn1;
var dataWA = CryptoJS.enc.Hex.parse(dataHex);
var dataB64 = CryptoJS.enc.Base64.stringify(dataWA);
var pemBody = dataB64.replace(/(.{64})/g, "$1\r\n");
pemBody = pemBody.replace(/\r\n$/, '');
return "-----BEGIN " + pemHeader + "-----\r\n" +
pemBody +
"\r\n-----END " + pemHeader + "-----\r\n";
};
/**
* generate ASN1Object specifed by JSON parameters
* @name newObject
* @memberOf KJUR.asn1.ASN1Util
* @function
* @param {Array} param JSON parameter to generate ASN1Object
* @return {KJUR.asn1.ASN1Object} generated object
* @since asn1 1.0.3
* @description
* generate any ASN1Object specified by JSON param
* including ASN.1 primitive or structured.
* Generally 'param' can be described as follows:
* <blockquote>
* {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER}
* </blockquote>
* 'TYPE-OF-ASN1OBJ' can be one of following symbols:
* <ul>
* <li>'bool' - DERBoolean</li>
* <li>'int' - DERInteger</li>
* <li>'bitstr' - DERBitString</li>
* <li>'octstr' - DEROctetString</li>
* <li>'null' - DERNull</li>
* <li>'oid' - DERObjectIdentifier</li>
* <li>'utf8str' - DERUTF8String</li>
* <li>'numstr' - DERNumericString</li>
* <li>'prnstr' - DERPrintableString</li>
* <li>'telstr' - DERTeletexString</li>
* <li>'ia5str' - DERIA5String</li>
* <li>'utctime' - DERUTCTime</li>
* <li>'gentime' - DERGeneralizedTime</li>
* <li>'seq' - DERSequence</li>
* <li>'set' - DERSet</li>
* <li>'tag' - DERTaggedObject</li>
* </ul>
* @example
* newObject({'prnstr': 'aaa'});
* newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]})
* // ASN.1 Tagged Object
* newObject({'tag': {'tag': 'a1',
* 'explicit': true,
* 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}});
* // more simple representation of ASN.1 Tagged Object
* newObject({'tag': ['a1',
* true,
* {'seq': [
* {'int': 3},
* {'prnstr': 'aaa'}]}
* ]});
*/
this.newObject = function(param) {
var ns1 = KJUR.asn1;
var keys = Object.keys(param);
if (keys.length != 1)
throw "key of param shall be only one.";
var key = keys[0];
if (":bool:int:bitstr:octstr:null:oid:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1)
throw "undefined key: " + key;
if (key == "bool") return new ns1.DERBoolean(param[key]);
if (key == "int") return new ns1.DERInteger(param[key]);
if (key == "bitstr") return new ns1.DERBitString(param[key]);
if (key == "octstr") return new ns1.DEROctetString(param[key]);
if (key == "null") return new ns1.DERNull(param[key]);
if (key == "oid") return new ns1.DERObjectIdentifier(param[key]);
if (key == "utf8str") return new ns1.DERUTF8String(param[key]);
if (key == "numstr") return new ns1.DERNumericString(param[key]);
if (key == "prnstr") return new ns1.DERPrintableString(param[key]);
if (key == "telstr") return new ns1.DERTeletexString(param[key]);
if (key == "ia5str") return new ns1.DERIA5String(param[key]);
if (key == "utctime") return new ns1.DERUTCTime(param[key]);
if (key == "gentime") return new ns1.DERGeneralizedTime(param[key]);
if (key == "seq") {
var paramList = param[key];
var a = [];
for (var i = 0; i < paramList.length; i++) {
var asn1Obj = ns1.ASN1Util.newObject(paramList[i]);
a.push(asn1Obj);
}
return new ns1.DERSequence({'array': a});
}
if (key == "set") {
var paramList = param[key];
var a = [];
for (var i = 0; i < paramList.length; i++) {
var asn1Obj = ns1.ASN1Util.newObject(paramList[i]);
a.push(asn1Obj);
}
return new ns1.DERSet({'array': a});
}
if (key == "tag") {
var tagParam = param[key];
if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
tagParam.length == 3) {
var obj = ns1.ASN1Util.newObject(tagParam[2]);
return new ns1.DERTaggedObject({tag: tagParam[0], explicit: tagParam[1], obj: obj});
} else {
var newParam = {};
if (tagParam.explicit !== undefined)
newParam.explicit = tagParam.explicit;
if (tagParam.tag !== undefined)
newParam.tag = tagParam.tag;
if (tagParam.obj === undefined)
throw "obj shall be specified for 'tag'.";
newParam.obj = ns1.ASN1Util.newObject(tagParam.obj);
return new ns1.DERTaggedObject(newParam);
}
}
};
/**
* get encoded hexadecimal string of ASN1Object specifed by JSON parameters
* @name jsonToASN1HEX
* @memberOf KJUR.asn1.ASN1Util
* @function
* @param {Array} param JSON parameter to generate ASN1Object
* @return hexadecimal string of ASN1Object
* @since asn1 1.0.4
* @description
* As for ASN.1 object representation of JSON object,
* please see {@link newObject}.
* @example
* jsonToASN1HEX({'prnstr': 'aaa'});
*/
this.jsonToASN1HEX = function(param) {
var asn1Obj = this.newObject(param);
return asn1Obj.getEncodedHex();
};
};
// ********************************************************************
// Abstract ASN.1 Classes
// ********************************************************************
// ********************************************************************
/**
* base class for ASN.1 DER encoder object
* @name KJUR.asn1.ASN1Object
* @class base class for ASN.1 DER encoder object
* @property {Boolean} isModified flag whether internal data was changed
* @property {String} hTLV hexadecimal string of ASN.1 TLV
* @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
* @property {String} hL hexadecimal string of ASN.1 TLV length(L)
* @property {String} hV hexadecimal string of ASN.1 TLV value(V)
* @description
*/
KJUR.asn1.ASN1Object = function() {
var isModified = true;
var hTLV = null;
var hT = '00';
var hL = '00';
var hV = '';
/**
* get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
* @name getLengthHexFromValue
* @memberOf KJUR.asn1.ASN1Object
* @function
* @return {String} hexadecimal string of ASN.1 TLV length(L)
*/
this.getLengthHexFromValue = function() {
if (typeof this.hV == "undefined" || this.hV == null) {
throw "this.hV is null or undefined.";
}
if (this.hV.length % 2 == 1) {
throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
}
var n = this.hV.length / 2;
var hN = n.toString(16);
if (hN.length % 2 == 1) {
hN = "0" + hN;
}
if (n < 128) {
return hN;
} else {
var hNlen = hN.length / 2;
if (hNlen > 15) {
throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
}
var head = 128 + hNlen;
return head.toString(16) + hN;
}
};
/**
* get hexadecimal string of ASN.1 TLV bytes
* @name getEncodedHex
* @memberOf KJUR.asn1.ASN1Object
* @function
* @return {String} hexadecimal string of ASN.1 TLV
*/
this.getEncodedHex = function() {
if (this.hTLV == null || this.isModified) {
this.hV = this.getFreshValueHex();
this.hL = this.getLengthHexFromValue();
this.hTLV = this.hT + this.hL + this.hV;
this.isModified = false;
//alert("first time: " + this.hTLV);
}
return this.hTLV;
};
/**
* get hexadecimal string of ASN.1 TLV value(V) bytes
* @name getValueHex
* @memberOf KJUR.asn1.ASN1Object
* @function
* @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
*/
this.getValueHex = function() {
this.getEncodedHex();
return this.hV;
}
this.getFreshValueHex = function() {
return '';
};
};
// == BEGIN DERAbstractString ================================================
/**
* base class for ASN.1 DER string classes
* @name KJUR.asn1.DERAbstractString
* @class base class for ASN.1 DER string classes
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @property {String} s internal string of value
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>str - specify initial ASN.1 value(V) by a string</li>
* <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERAbstractString = function(params) {
KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
var s = null;
var hV = null;
/**
* get string value of this string object
* @name getString
* @memberOf KJUR.asn1.DERAbstractString
* @function
* @return {String} string value of this string object
*/
this.getString = function() {
return this.s;
};
/**
* set value by a string
* @name setString
* @memberOf KJUR.asn1.DERAbstractString
* @function
* @param {String} newS value by a string to set
*/
this.setString = function(newS) {
this.hTLV = null;
this.isModified = true;
this.s = newS;
this.hV = stohex(this.s);
};
/**
* set value by a hexadecimal string
* @name setStringHex
* @memberOf KJUR.asn1.DERAbstractString
* @function
* @param {String} newHexString value by a hexadecimal string to set
*/
this.setStringHex = function(newHexString) {
this.hTLV = null;
this.isModified = true;
this.s = null;
this.hV = newHexString;
};
this.getFreshValueHex = function() {
return this.hV;
};
if (typeof params != "undefined") {
if (typeof params == "string") {
this.setString(params);
} else if (typeof params['str'] != "undefined") {
this.setString(params['str']);
} else if (typeof params['hex'] != "undefined") {
this.setStringHex(params['hex']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
// == END DERAbstractString ================================================
// == BEGIN DERAbstractTime ==================================================
/**
* base class for ASN.1 DER Generalized/UTCTime class
* @name KJUR.asn1.DERAbstractTime
* @class base class for ASN.1 DER Generalized/UTCTime class
* @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
* @extends KJUR.asn1.ASN1Object
* @description
* @see KJUR.asn1.ASN1Object - superclass
*/
KJUR.asn1.DERAbstractTime = function(params) {
KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
var s = null;
var date = null;
// --- PRIVATE METHODS --------------------
this.localDateToUTC = function(d) {
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var utcDate = new Date(utc);
return utcDate;
};
this.formatDate = function(dateObject, type) {
var pad = this.zeroPadding;
var d = this.localDateToUTC(dateObject);
var year = String(d.getFullYear());
if (type == 'utc') year = year.substr(2, 2);
var month = pad(String(d.getMonth() + 1), 2);
var day = pad(String(d.getDate()), 2);
var hour = pad(String(d.getHours()), 2);
var min = pad(String(d.getMinutes()), 2);
var sec = pad(String(d.getSeconds()), 2);
return year + month + day + hour + min + sec + 'Z';
};
this.zeroPadding = function(s, len) {
if (s.length >= len) return s;
return new Array(len - s.length + 1).join('0') + s;
};
// --- PUBLIC METHODS --------------------
/**
* get string value of this string object
* @name getString
* @memberOf KJUR.asn1.DERAbstractTime
* @function
* @return {String} string value of this time object
*/
this.getString = function() {
return this.s;
};
/**
* set value by a string
* @name setString
* @memberOf KJUR.asn1.DERAbstractTime
* @function
* @param {String} newS value by a string to set such like "130430235959Z"
*/
this.setString = function(newS) {
this.hTLV = null;
this.isModified = true;
this.s = newS;
this.hV = stohex(newS);
};
/**
* set value by a Date object
* @name setByDateValue
* @memberOf KJUR.asn1.DERAbstractTime
* @function
* @param {Integer} year year of date (ex. 2013)
* @param {Integer} month month of date between 1 and 12 (ex. 12)
* @param {Integer} day day of month
* @param {Integer} hour hours of date
* @param {Integer} min minutes of date
* @param {Integer} sec seconds of date
*/
this.setByDateValue = function(year, month, day, hour, min, sec) {
var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
this.setByDate(dateObject);
};
this.getFreshValueHex = function() {
return this.hV;
};
};
YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
// == END DERAbstractTime ==================================================
// == BEGIN DERAbstractStructured ============================================
/**
* base class for ASN.1 DER structured class
* @name KJUR.asn1.DERAbstractStructured
* @class base class for ASN.1 DER structured class
* @property {Array} asn1Array internal array of ASN1Object
* @extends KJUR.asn1.ASN1Object
* @description
* @see KJUR.asn1.ASN1Object - superclass
*/
KJUR.asn1.DERAbstractStructured = function(params) {
KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
var asn1Array = null;
/**
* set value by array of ASN1Object
* @name setByASN1ObjectArray
* @memberOf KJUR.asn1.DERAbstractStructured
* @function
* @param {array} asn1ObjectArray array of ASN1Object to set
*/
this.setByASN1ObjectArray = function(asn1ObjectArray) {
this.hTLV = null;
this.isModified = true;
this.asn1Array = asn1ObjectArray;
};
/**
* append an ASN1Object to internal array
* @name appendASN1Object
* @memberOf KJUR.asn1.DERAbstractStructured
* @function
* @param {ASN1Object} asn1Object to add
*/
this.appendASN1Object = function(asn1Object) {
this.hTLV = null;
this.isModified = true;
this.asn1Array.push(asn1Object);
};
this.asn1Array = new Array();
if (typeof params != "undefined") {
if (typeof params['array'] != "undefined") {
this.asn1Array = params['array'];
}
}
};
YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
// ********************************************************************
// ASN.1 Object Classes
// ********************************************************************
// ********************************************************************
/**
* class for ASN.1 DER Boolean
* @name KJUR.asn1.DERBoolean
* @class class for ASN.1 DER Boolean
* @extends KJUR.asn1.ASN1Object
* @description
* @see KJUR.asn1.ASN1Object - superclass
*/
KJUR.asn1.DERBoolean = function() {
KJUR.asn1.DERBoolean.superclass.constructor.call(this);
this.hT = "01";
this.hTLV = "0101ff";
};
YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
// ********************************************************************
/**
* class for ASN.1 DER Integer
* @name KJUR.asn1.DERInteger
* @class class for ASN.1 DER Integer
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>int - specify initial ASN.1 value(V) by integer value</li>
* <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
* <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERInteger = function(params) {
KJUR.asn1.DERInteger.superclass.constructor.call(this);
this.hT = "02";
/**
* set value by Tom Wu's BigInteger object
* @name setByBigInteger
* @memberOf KJUR.asn1.DERInteger
* @function
* @param {BigInteger} bigIntegerValue to set
*/
this.setByBigInteger = function(bigIntegerValue) {
this.hTLV = null;
this.isModified = true;
this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
};
/**
* set value by integer value
* @name setByInteger
* @memberOf KJUR.asn1.DERInteger
* @function
* @param {Integer} integer value to set
*/
this.setByInteger = function(intValue) {
var bi = new BigInteger(String(intValue), 10);
this.setByBigInteger(bi);
};
/**
* set value by integer value
* @name setValueHex
* @memberOf KJUR.asn1.DERInteger
* @function
* @param {String} hexadecimal string of integer value
* @description
* <br/>
* NOTE: Value shall be represented by minimum octet length of
* two's complement representation.
* @example
* new KJUR.asn1.DERInteger(123);
* new KJUR.asn1.DERInteger({'int': 123});
* new KJUR.asn1.DERInteger({'hex': '1fad'});
*/
this.setValueHex = function(newHexString) {
this.hV = newHexString;
};
this.getFreshValueHex = function() {
return this.hV;
};
if (typeof params != "undefined") {
if (typeof params['bigint'] != "undefined") {
this.setByBigInteger(params['bigint']);
} else if (typeof params['int'] != "undefined") {
this.setByInteger(params['int']);
} else if (typeof params == "number") {
this.setByInteger(params);
} else if (typeof params['hex'] != "undefined") {
this.setValueHex(params['hex']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
// ********************************************************************
/**
* class for ASN.1 DER encoded BitString primitive
* @name KJUR.asn1.DERBitString
* @class class for ASN.1 DER encoded BitString primitive
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>bin - specify binary string (ex. '10111')</li>
* <li>array - specify array of boolean (ex. [true,false,true,true])</li>
* <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERBitString = function(params) {
KJUR.asn1.DERBitString.superclass.constructor.call(this);
this.hT = "03";
/**
* set ASN.1 value(V) by a hexadecimal string including unused bits
* @name setHexValueIncludingUnusedBits
* @memberOf KJUR.asn1.DERBitString
* @function
* @param {String} newHexStringIncludingUnusedBits
*/
this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
this.hTLV = null;
this.isModified = true;
this.hV = newHexStringIncludingUnusedBits;
};
/**
* set ASN.1 value(V) by unused bit and hexadecimal string of value
* @name setUnusedBitsAndHexValue
* @memberOf KJUR.asn1.DERBitString
* @function
* @param {Integer} unusedBits
* @param {String} hValue
*/
this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
if (unusedBits < 0 || 7 < unusedBits) {
throw "unused bits shall be from 0 to 7: u = " + unusedBits;
}
var hUnusedBits = "0" + unusedBits;
this.hTLV = null;
this.isModified = true;
this.hV = hUnusedBits + hValue;
};
/**
* set ASN.1 DER BitString by binary string
* @name setByBinaryString
* @memberOf KJUR.asn1.DERBitString
* @function
* @param {String} binaryString binary value string (i.e. '10111')
* @description
* Its unused bits will be calculated automatically by length of
* 'binaryValue'. <br/>
* NOTE: Trailing zeros '0' will be ignored.
*/
this.setByBinaryString = function(binaryString) {
binaryString = binaryString.replace(/0+$/, '');
var unusedBits = 8 - binaryString.length % 8;
if (unusedBits == 8) unusedBits = 0;
for (var i = 0; i <= unusedBits; i++) {
binaryString += '0';
}
var h = '';
for (var i = 0; i < binaryString.length - 1; i += 8) {
var b = binaryString.substr(i, 8);
var x = parseInt(b, 2).toString(16);
if (x.length == 1) x = '0' + x;
h += x;
}
this.hTLV = null;
this.isModified = true;
this.hV = '0' + unusedBits + h;
};
/**
* set ASN.1 TLV value(V) by an array of boolean
* @name setByBooleanArray
* @memberOf KJUR.asn1.DERBitString
* @function
* @param {array} booleanArray array of boolean (ex. [true, false, true])
* @description
* NOTE: Trailing falses will be ignored.
*/
this.setByBooleanArray = function(booleanArray) {
var s = '';
for (var i = 0; i < booleanArray.length; i++) {
if (booleanArray[i] == true) {
s += '1';
} else {
s += '0';
}
}
this.setByBinaryString(s);
};
/**
* generate an array of false with specified length
* @name newFalseArray
* @memberOf KJUR.asn1.DERBitString
* @function
* @param {Integer} nLength length of array to generate
* @return {array} array of boolean faluse
* @description
* This static method may be useful to initialize boolean array.
*/
this.newFalseArray = function(nLength) {
var a = new Array(nLength);
for (var i = 0; i < nLength; i++) {
a[i] = false;
}
return a;
};
this.getFreshValueHex = function() {
return this.hV;
};
if (typeof params != "undefined") {
if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
this.setHexValueIncludingUnusedBits(params);
} else if (typeof params['hex'] != "undefined") {
this.setHexValueIncludingUnusedBits(params['hex']);
} else if (typeof params['bin'] != "undefined") {
this.setByBinaryString(params['bin']);
} else if (typeof params['array'] != "undefined") {
this.setByBooleanArray(params['array']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
// ********************************************************************
/**
* class for ASN.1 DER OctetString
* @name KJUR.asn1.DEROctetString
* @class class for ASN.1 DER OctetString
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DEROctetString = function(params) {
KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
this.hT = "04";
};
YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER Null
* @name KJUR.asn1.DERNull
* @class class for ASN.1 DER Null
* @extends KJUR.asn1.ASN1Object
* @description
* @see KJUR.asn1.ASN1Object - superclass
*/
KJUR.asn1.DERNull = function() {
KJUR.asn1.DERNull.superclass.constructor.call(this);
this.hT = "05";
this.hTLV = "0500";
};
YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
// ********************************************************************
/**
* class for ASN.1 DER ObjectIdentifier
* @name KJUR.asn1.DERObjectIdentifier
* @class class for ASN.1 DER ObjectIdentifier
* @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
* <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERObjectIdentifier = function(params) {
var itox = function(i) {
var h = i.toString(16);
if (h.length == 1) h = '0' + h;
return h;
};
var roidtox = function(roid) {
var h = '';
var bi = new BigInteger(roid, 10);
var b = bi.toString(2);
var padLen = 7 - b.length % 7;
if (padLen == 7) padLen = 0;
var bPad = '';
for (var i = 0; i < padLen; i++) bPad += '0';
b = bPad + b;
for (var i = 0; i < b.length - 1; i += 7) {
var b8 = b.substr(i, 7);
if (i != b.length - 7) b8 = '1' + b8;
h += itox(parseInt(b8, 2));
}
return h;
}
KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
this.hT = "06";
/**
* set value by a hexadecimal string
* @name setValueHex
* @memberOf KJUR.asn1.DERObjectIdentifier
* @function
* @param {String} newHexString hexadecimal value of OID bytes
*/
this.setValueHex = function(newHexString) {
this.hTLV = null;
this.isModified = true;
this.s = null;
this.hV = newHexString;
};
/**
* set value by a OID string
* @name setValueOidString
* @memberOf KJUR.asn1.DERObjectIdentifier
* @function
* @param {String} oidString OID string (ex. 2.5.4.13)
*/
this.setValueOidString = function(oidString) {
if (! oidString.match(/^[0-9.]+$/)) {
throw "malformed oid string: " + oidString;
}
var h = '';
var a = oidString.split('.');
var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
h += itox(i0);
a.splice(0, 2);
for (var i = 0; i < a.length; i++) {
h += roidtox(a[i]);
}
this.hTLV = null;
this.isModified = true;
this.s = null;
this.hV = h;
};
/**
* set value by a OID name
* @name setValueName
* @memberOf KJUR.asn1.DERObjectIdentifier
* @function
* @param {String} oidName OID name (ex. 'serverAuth')
* @since 1.0.1
* @description
* OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
* Otherwise raise error.
*/
this.setValueName = function(oidName) {
if (typeof KJUR.asn1.x509.OID.name2oidList[oidName] != "undefined") {
var oid = KJUR.asn1.x509.OID.name2oidList[oidName];
this.setValueOidString(oid);
} else {
throw "DERObjectIdentifier oidName undefined: " + oidName;
}
};
this.getFreshValueHex = function() {
return this.hV;
};
if (typeof params != "undefined") {
if (typeof params == "string" && params.match(/^[0-2].[0-9.]+$/)) {
this.setValueOidString(params);
} else if (KJUR.asn1.x509.OID.name2oidList[params] !== undefined) {
this.setValueOidString(KJUR.asn1.x509.OID.name2oidList[params]);
} else if (typeof params['oid'] != "undefined") {
this.setValueOidString(params['oid']);
} else if (typeof params['hex'] != "undefined") {
this.setValueHex(params['hex']);
} else if (typeof params['name'] != "undefined") {
this.setValueName(params['name']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
// ********************************************************************
/**
* class for ASN.1 DER UTF8String
* @name KJUR.asn1.DERUTF8String
* @class class for ASN.1 DER UTF8String
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DERUTF8String = function(params) {
KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
this.hT = "0c";
};
YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER NumericString
* @name KJUR.asn1.DERNumericString
* @class class for ASN.1 DER NumericString
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DERNumericString = function(params) {
KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
this.hT = "12";
};
YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER PrintableString
* @name KJUR.asn1.DERPrintableString
* @class class for ASN.1 DER PrintableString
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DERPrintableString = function(params) {
KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
this.hT = "13";
};
YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER TeletexString
* @name KJUR.asn1.DERTeletexString
* @class class for ASN.1 DER TeletexString
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DERTeletexString = function(params) {
KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
this.hT = "14";
};
YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER IA5String
* @name KJUR.asn1.DERIA5String
* @class class for ASN.1 DER IA5String
* @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
* @extends KJUR.asn1.DERAbstractString
* @description
* @see KJUR.asn1.DERAbstractString - superclass
*/
KJUR.asn1.DERIA5String = function(params) {
KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
this.hT = "16";
};
YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
// ********************************************************************
/**
* class for ASN.1 DER UTCTime
* @name KJUR.asn1.DERUTCTime
* @class class for ASN.1 DER UTCTime
* @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
* @extends KJUR.asn1.DERAbstractTime
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
* <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
* <li>date - specify Date object.</li>
* </ul>
* NOTE: 'params' can be omitted.
* <h4>EXAMPLES</h4>
* @example
* var d1 = new KJUR.asn1.DERUTCTime();
* d1.setString('130430125959Z');
*
* var d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
* var d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
* var d4 = new KJUR.asn1.DERUTCTime('130430125959Z');
*/
KJUR.asn1.DERUTCTime = function(params) {
KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
this.hT = "17";
/**
* set value by a Date object
* @name setByDate
* @memberOf KJUR.asn1.DERUTCTime
* @function
* @param {Date} dateObject Date object to set ASN.1 value(V)
*/
this.setByDate = function(dateObject) {
this.hTLV = null;
this.isModified = true;
this.date = dateObject;
this.s = this.formatDate(this.date, 'utc');
this.hV = stohex(this.s);
};
if (typeof params != "undefined") {
if (typeof params['str'] != "undefined") {
this.setString(params['str']);
} else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
this.setString(params);
} else if (typeof params['hex'] != "undefined") {
this.setStringHex(params['hex']);
} else if (typeof params['date'] != "undefined") {
this.setByDate(params['date']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
// ********************************************************************
/**
* class for ASN.1 DER GeneralizedTime
* @name KJUR.asn1.DERGeneralizedTime
* @class class for ASN.1 DER GeneralizedTime
* @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
* @extends KJUR.asn1.DERAbstractTime
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
* <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
* <li>date - specify Date object.</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERGeneralizedTime = function(params) {
KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
this.hT = "18";
/**
* set value by a Date object
* @name setByDate
* @memberOf KJUR.asn1.DERGeneralizedTime
* @function
* @param {Date} dateObject Date object to set ASN.1 value(V)
* @example
* When you specify UTC time, use 'Date.UTC' method like this:<br/>
* var o = new DERUTCTime();
* var date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
* o.setByDate(date);
*/
this.setByDate = function(dateObject) {
this.hTLV = null;
this.isModified = true;
this.date = dateObject;
this.s = this.formatDate(this.date, 'gen');
this.hV = stohex(this.s);
};
if (typeof params != "undefined") {
if (typeof params['str'] != "undefined") {
this.setString(params['str']);
} else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
this.setString(params);
} else if (typeof params['hex'] != "undefined") {
this.setStringHex(params['hex']);
} else if (typeof params['date'] != "undefined") {
this.setByDate(params['date']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
// ********************************************************************
/**
* class for ASN.1 DER Sequence
* @name KJUR.asn1.DERSequence
* @class class for ASN.1 DER Sequence
* @extends KJUR.asn1.DERAbstractStructured
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>array - specify array of ASN1Object to set elements of content</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERSequence = function(params) {
KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
this.hT = "30";
this.getFreshValueHex = function() {
var h = '';
for (var i = 0; i < this.asn1Array.length; i++) {
var asn1Obj = this.asn1Array[i];
h += asn1Obj.getEncodedHex();
}
this.hV = h;
return this.hV;
};
};
YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
// ********************************************************************
/**
* class for ASN.1 DER Set
* @name KJUR.asn1.DERSet
* @class class for ASN.1 DER Set
* @extends KJUR.asn1.DERAbstractStructured
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>array - specify array of ASN1Object to set elements of content</li>
* </ul>
* NOTE: 'params' can be omitted.
*/
KJUR.asn1.DERSet = function(params) {
KJUR.asn1.DERSet.superclass.constructor.call(this, params);
this.hT = "31";
this.getFreshValueHex = function() {
var a = new Array();
for (var i = 0; i < this.asn1Array.length; i++) {
var asn1Obj = this.asn1Array[i];
a.push(asn1Obj.getEncodedHex());
}
a.sort();
this.hV = a.join('');
return this.hV;
};
};
YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
// ********************************************************************
/**
* class for ASN.1 DER TaggedObject
* @name KJUR.asn1.DERTaggedObject
* @class class for ASN.1 DER TaggedObject
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
* For example, if you find '[1]' tag in a ASN.1 dump,
* 'tagNoHex' will be 'a1'.
* <br/>
* As for optional argument 'params' for constructor, you can specify *ANY* of
* following properties:
* <ul>
* <li>explicit - specify true if this is explicit tag otherwise false
* (default is 'true').</li>
* <li>tag - specify tag (default is 'a0' which means [0])</li>
* <li>obj - specify ASN1Object which is tagged</li>
* </ul>
* @example
* d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
* d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
* hex = d2.getEncodedHex();
*/
KJUR.asn1.DERTaggedObject = function(params) {
KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
this.hT = "a0";
this.hV = '';
this.isExplicit = true;
this.asn1Object = null;
/**
* set value by an ASN1Object
* @name setString
* @memberOf KJUR.asn1.DERTaggedObject
* @function
* @param {Boolean} isExplicitFlag flag for explicit/implicit tag
* @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
* @param {ASN1Object} asn1Object ASN.1 to encapsulate
*/
this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
this.hT = tagNoHex;
this.isExplicit = isExplicitFlag;
this.asn1Object = asn1Object;
if (this.isExplicit) {
this.hV = this.asn1Object.getEncodedHex();
this.hTLV = null;
this.isModified = true;
} else {
this.hV = null;
this.hTLV = asn1Object.getEncodedHex();
this.hTLV = this.hTLV.replace(/^../, tagNoHex);
this.isModified = false;
}
};
this.getFreshValueHex = function() {
return this.hV;
};
if (typeof params != "undefined") {
if (typeof params['tag'] != "undefined") {
this.hT = params['tag'];
}
if (typeof params['explicit'] != "undefined") {
this.isExplicit = params['explicit'];
}
if (typeof params['obj'] != "undefined") {
this.asn1Object = params['obj'];
this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
}
}
};
YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
================================================
FILE: JavaScript/demo/js/asn1hex-1.1.js
================================================
/*! asn1hex-1.1.4.js (c) 2012-2013 Kenji Urushima | kjur.github.com/jsrsasign/license
*/
/*
* asn1hex.js - Hexadecimal represented ASN.1 string library
*
* Copyright (c) 2010-2013 Kenji Urushima (kenji.urushima@gmail.com)
*
* This software is licensed under the terms of the MIT License.
* http://kjur.github.com/jsrsasign/license/
*
* The above copyright and license notice shall be
* included in all copies or substantial portions of the Software.
*/
/**
* @fileOverview
* @name asn1hex-1.1.js
* @author Kenji Urushima kenji.urushima@gmail.com
* @version asn1hex 1.1.4 (2013-Oct-02)
* @license <a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
*/
/*
* MEMO:
* f('3082025b02...', 2) ... 82025b ... 3bytes
* f('020100', 2) ... 01 ... 1byte
* f('0203001...', 2) ... 03 ... 1byte
* f('02818003...', 2) ... 8180 ... 2bytes
* f('3080....0000', 2) ... 80 ... -1
*
* Requirements:
* - ASN.1 type octet length MUST be 1.
* (i.e. ASN.1 primitives like SET, SEQUENCE, INTEGER, OCTETSTRING ...)
*/
/**
* ASN.1 DER encoded hexadecimal string utility class
* @name ASN1HEX
* @class ASN.1 DER encoded hexadecimal string utility class
* @since jsrsasign 1.1
*/
var ASN1HEX = new function() {
/**
* get byte length for ASN.1 L(length) bytes
* @name getByteLengthOfL_AtObj
* @memberOf ASN1HEX
* @function
* @param {String} s hexadecimal string of ASN.1 DER encoded data
* @param {Number} pos string index
* @return byte length for ASN.1 L(length) bytes
*/
this.getByteLengthOfL_AtObj = function(s, pos) {
if (s.substring(pos + 2, pos + 3) != '8') return 1;
var i = parseInt(s.substring(pos + 3, pos + 4));
if (i == 0) return -1; // length octet '80' indefinite length
if (0 < i && i < 10) return i + 1; // including '8?' octet;
return -2; // malformed format
};
/**
* get hexadecimal string for ASN.1 L(length) bytes
* @name getHexOfL_AtObj
* @memberOf ASN1HEX
* @function
* @param {String} s hexadecimal string of ASN.1 DER encoded data
* @param {Number} pos string index
* @return {String} hexadecimal string for ASN.1 L(length) bytes
*/
this.getHexOfL_AtObj = function(s, pos) {
var len = this.getByteLengthOfL_AtObj(s, pos);
if (len < 1) return '';
return s.substring(pos + 2, pos + 2 + len * 2);
};
// getting ASN.1 length value at the position 'idx' of
// hexa decimal string 's'.
//
// f('3082025b02...', 0) ... 82025b ... ???
// f('020100', 0) ... 01 ... 1
// f('0203001...', 0) ... 03 ... 3
// f('02818003...', 0) ... 8180 ... 128
/**
* get integer value of ASN.1 length for ASN.1 data
* @name getIntOfL_AtObj
* @memberOf ASN1HEX
* @function
* @param {String} s hexadecimal string of ASN.1 DER encoded data
* @param {Number} pos string index
* @return ASN.1 L(length) integer value
*/
this.getIntOfL_AtObj = function(s, pos) {
var hLength = this.getHexOfL_AtObj(s, pos);
if (hLength == '') return -1;
var bi;
if (parseInt(hLength.substring(0, 1)) < 8) {
bi = new BigInteger(hLength, 16);
} else {
bi = new BigInteger(hLength.substring(2), 16);
}
return bi.intValue();
};
/**
* get ASN.1 value starting string position for ASN.1 object refered by index 'idx'.
* @name getStartPosOfV_AtObj
* @memberOf ASN1HEX
* @function
* @param {String} s hexadecimal string of ASN.1 DER encoded data
* @param {Number} pos string index
*/
this.getStartPosOfV_AtObj = function(s, pos) {
var l_len = this.getByteLengthOfL_AtObj(s, pos);
if (l_len < 0) return l_len;
return pos + (l_len + 1) * 2;
};
/**
* get hexadecimal string of ASN.1 V(value)
* @name getHexOfV_AtObj
* @memberOf ASN1HEX
* @function
* @param {String} s hexadecimal string of ASN.1 DER encoded data
* @param {Number} pos string index
* @return {String} hexadecimal string of ASN.1 value.
*/
this.getHexOfV_AtObj = function(s, pos) {
var pos1 = this.getStartPosOfV_AtObj(s, pos);
var len = this.getIntOfL_AtObj(s, pos);
return s.substring(pos1, pos1 + len * 2);
};
/**
* get hexadecimal string of ASN.1 TLV at
* @name getHexOfTLV_AtObj
* @memberOf ASN1HEX
* @function
* @param {String} s hexadecimal string of ASN.1 DER encoded data
* @param {Number} pos string index
* @return {String} hexadecimal string of ASN.1 TLV.
* @since 1.1
*/
this.getHexOfTLV_AtObj = function(s, pos) {
var hT = s.substr(pos, 2);
var hL = this.getHexOfL_AtObj(s, pos);
var hV = this.getHexOfV_AtObj(s, pos);
return hT + hL + hV;
};
/**
* get next sibling starting index for ASN.1 object string
* @name getPosOfNextSibling_AtObj
* @memberOf ASN1HEX
* @function
* @param {String} s hexadecimal string of ASN.1 DER encoded data
* @param {Number} pos string index
* @return next sibling starting index for ASN.1 object string
*/
this.getPosOfNextSibling_AtObj = function(s, pos) {
var pos1 = this.getStartPosOfV_AtObj(s, pos);
var len = this.getIntOfL_AtObj(s, pos);
return pos1 + len * 2;
};
/**
* get array of indexes of child ASN.1 objects
* @name getPosArrayOfChildren_AtObj
* @memberOf ASN1HEX
* @function
* @param {String} s hexadecimal string of ASN.1 DER encoded data
* @param {Number} start string index of ASN.1 object
* @return {Array of Number} array of indexes for childen of ASN.1 objects
*/
this.getPosArrayOfChildren_AtObj = function(h, pos) {
var a = new Array();
var p0 = this.getStartPosOfV_AtObj(h, pos);
a.push(p0);
var len = this.getIntOfL_AtObj(h, pos);
var p = p0;
var k = 0;
while (1) {
var pNext = this.getPosOfNextSibling_AtObj(h, p);
if (pNext == null || (pNext - p0 >= (len * 2))) break;
if (k >= 200) break;
a.push(pNext);
p = pNext;
k++;
}
return a;
};
/**
* get string index of nth child object of ASN.1 object refered by h, idx
* @name getNthChildIndex_AtObj
* @memberOf ASN1HEX
* @function
* @param {String} h hexadecimal string of ASN.1 DER encoded data
* @param {Number} idx start string index of ASN.1 object
* @param {Number} nth for child
* @return {Number} string index of nth child.
* @since 1.1
*/
this.getNthChildIndex_AtObj = function(h, idx, nth) {
var a = this.getPosArrayOfChildren_AtObj(h, idx);
return a[nth];
};
// ========== decendant methods ==============================
/**
* get string index of nth child object of ASN.1 object refered by h, idx
* @name getDecendantIndexByNthList
* @memberOf ASN1HEX
* @function
* @param {String} h hexadecimal string of ASN.1 DER encoded data
* @param {Number} currentIndex start string index of ASN.1 object
* @param {Array of Number} nthList array list of nth
* @return {Number} string index refered by nthList
* @since 1.1
* @example
* The "nthList" is a index list of structured ASN.1 object
* reference. Here is a sample structure and "nthList"s which
* refers each objects.
*
* SQUENCE - [0]
* SEQUENCE - [0, 0]
* IA5STRING 000 - [0, 0, 0]
* UTF8STRING 001 - [0, 0, 1]
* SET - [0, 1]
* IA5STRING 010 - [0, 1, 0]
* UTF8STRING 011 - [0, 1, 1]
*/
this.getDecendantIndexByNthList = function(h, currentIndex, nthList) {
if (nthList.length == 0) {
return currentIndex;
}
var firstNth = nthList.shift();
var a = this.getPosArrayOfChildren_AtObj(h, currentIndex);
return this.getDecendantIndexByNthList(h, a[firstNth], nthList);
};
/**
* get hexadecimal string of ASN.1 TLV refered by current index and nth index list.
* @name getDecendantHexTLVByNthList
* @memberOf ASN1HEX
* @function
* @param {String} h hexadecimal string of ASN.1 DER encoded data
* @param {Number} currentIndex start string index of ASN.1 object
* @param {Array of Number} nthList array list of nth
* @return {Number} hexadecimal string of ASN.1 TLV refered by nthList
* @since 1.1
*/
this.getDecendantHexTLVByNthList = function(h, currentIndex, nthList) {
var idx = this.getDecendantIndexByNthList(h, currentIndex, nthList);
return this.getHexOfTLV_AtObj(h, idx);
};
/**
* get hexadecimal string of ASN.1 V refered by current index and nth index list.
* @name getDecendantHexVByNthList
* @memberOf ASN1HEX
* @function
* @param {String} h hexadecimal string of ASN.1 DER encoded data
* @param {Number} currentIndex start string index of ASN.1 object
* @param {Array of Number} nthList array list of nth
* @return {Number} hexadecimal string of ASN.1 V refered by nthList
* @since 1.1
*/
this.getDecendantHexVByNthList = function(h, currentIndex, nthList) {
var idx = this.getDecendantIndexByNthList(h, currentIndex, nthList);
return this.getHexOfV_AtObj(h, idx);
};
};
/*
* @since asn1hex 1.1.4
*/
ASN1HEX.getVbyList = function(h, currentIndex, nthList, checkingTag) {
var idx = this.getDecendantIndexByNthList(h, currentIndex, nthList);
if (idx === undefined) {
throw "can't find nthList object";
}
if (checkingTag !== undefined) {
if (h.substr(idx, 2) != checkingTag) {
throw "checking tag doesn't match: " + h.substr(idx,2) + "!=" + checkingTag;
}
}
return this.getHexOfV_AtObj(h, idx);
};
================================================
FILE: JavaScript/demo/js/asn1x509-1.0.js
================================================
/*! asn1x509-1.0.7.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license
*/
/*
* asn1x509.js - ASN.1 DER encoder classes for X.509 certificate
*
* Copyright (c) 2013 Kenji Urushima (kenji.urushima@gmail.com)
*
* This software is licensed under the terms of the MIT License.
* http://kjur.github.com/jsrsasign/license
*
* The above copyright and license notice shall be
* included in all copies or substantial portions of the Software.
*/
/**
* @fileOverview
* @name asn1x509-1.0.js
* @author Kenji Urushima kenji.urushima@gmail.com
* @version 1.0.7 (2013-Oct-11)
* @since jsrsasign 2.1
* @license <a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
*/
/**
* kjur's class library name space
* // already documented in asn1-1.0.js
* @name KJUR
* @namespace kjur's class library name space
*/
if (typeof KJUR == "undefined" || !KJUR) KJUR = {};
/**
* kjur's ASN.1 class library name space
* // already documented in asn1-1.0.js
* @name KJUR.asn1
* @namespace
*/
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
/**
* kjur's ASN.1 class for X.509 certificate library name space
* <p>
* <h4>FEATURES</h4>
* <ul>
* <li>easily issue any kind of certificate</li>
* <li>APIs are very similar to BouncyCastle library ASN.1 classes. So easy to learn.</li>
* </ul>
* </p>
* <h4>PROVIDED CLASSES</h4>
* <ul>
* <li>{@link KJUR.asn1.x509.Certificate}</li>
* <li>{@link KJUR.asn1.x509.TBSCertificate}</li>
* <li>{@link KJUR.asn1.x509.Extension}</li>
* <li>{@link KJUR.asn1.x509.X500Name}</li>
* <li>{@link KJUR.asn1.x509.RDN}</li>
* <li>{@link KJUR.asn1.x509.AttributeTypeAndValue}</li>
* <li>{@link KJUR.asn1.x509.SubjectPublicKeyInfo}</li>
* <li>{@link KJUR.asn1.x509.AlgorithmIdentifier}</li>
* <li>{@link KJUR.asn1.x509.GeneralName}</li>
* <li>{@link KJUR.asn1.x509.GeneralNames}</li>
* <li>{@link KJUR.asn1.x509.DistributionPointName}</li>
* <li>{@link KJUR.asn1.x509.DistributionPoint}</li>
* <li>{@link KJUR.asn1.x509.CRL}</li>
* <li>{@link KJUR.asn1.x509.TBSCertList}</li>
* <li>{@link KJUR.asn1.x509.CRLEntry}</li>
* <li>{@link KJUR.asn1.x509.OID}</li>
* </ul>
* <h4>SUPPORTED EXTENSIONS</h4>
* <ul>
* <li>{@link KJUR.asn1.x509.BasicConstraints}</li>
* <li>{@link KJUR.asn1.x509.KeyUsage}</li>
* <li>{@link KJUR.asn1.x509.CRLDistributionPoints}</li>
* <li>{@link KJUR.asn1.x509.ExtKeyUsage}</li>
* </ul>
* NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
* @name KJUR.asn1.x509
* @namespace
*/
if (typeof KJUR.asn1.x509 == "undefined" || !KJUR.asn1.x509) KJUR.asn1.x509 = {};
// === BEGIN Certificate ===================================================
/**
* X.509 Certificate class to sign and generate hex encoded certificate
* @name KJUR.asn1.x509.Certificate
* @class X.509 Certificate class to sign and generate hex encoded certificate
* @param {Array} params associative array of parameters (ex. {'tbscertobj': obj, 'prvkeyobj': key})
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>tbscertobj - specify {@link KJUR.asn1.x509.TBSCertificate} object</li>
* <li>prvkeyobj - specify {@link RSAKey}, {@link KJUR.crypto.ECDSA} or {@link KJUR.crypto.DSA} object for CA private key to sign the certificate</li>
* <li>(DEPRECATED)rsaprvkey - specify {@link RSAKey} object CA private key</li>
* <li>(DEPRECATED)rsaprvpem - specify PEM string of RSA CA private key</li>
* </ul>
* NOTE1: 'params' can be omitted.<br/>
* NOTE2: DSA/ECDSA is also supported for CA signging key from asn1x509 1.0.6.
* @example
* var caKey = KEYUTIL.getKey(caKeyPEM); // CA's private key
* var cert = new KJUR.asn1x509.Certificate({'tbscertobj': tbs, 'prvkeyobj': caKey});
* cert.sign(); // issue certificate by CA's private key
* var certPEM = cert.getPEMString();
*
* // Certificate ::= SEQUENCE {
* // tbsCertificate TBSCertificate,
* // signatureAlgorithm AlgorithmIdentifier,
* // signature BIT STRING }
*/
KJUR.asn1.x509.Certificate = function(params) {
KJUR.asn1.x509.Certificate.superclass.constructor.call(this);
var asn1TBSCert = null;
var asn1SignatureAlg = null;
var asn1Sig = null;
var hexSig = null;
var prvKey = null;
var rsaPrvKey = null; // DEPRECATED
/**
* set PKCS#5 encrypted RSA PEM private key as CA key
* @name setRsaPrvKeyByPEMandPass
* @memberOf KJUR.asn1.x509.Certificate
* @function
* @param {String} rsaPEM string of PKCS#5 encrypted RSA PEM private key
* @param {String} passPEM passcode string to decrypt private key
* @since 1.0.1
* @description
* <br/>
* <h4>EXAMPLES</h4>
* @example
* var cert = new KJUR.asn1.x509.Certificate({'tbscertobj': tbs});
* cert.setRsaPrvKeyByPEMandPass("-----BEGIN RSA PRIVATE..(snip)", "password");
*/
this.setRsaPrvKeyByPEMandPass = function(rsaPEM, passPEM) {
var caKeyHex = PKCS5PKEY.getDecryptedKeyHex(rsaPEM, passPEM);
var caKey = new RSAKey();
caKey.readPrivateKeyFromASN1HexString(caKeyHex);
this.prvKey = caKey;
};
/**
* sign TBSCertificate and set signature value internally
* @name sign
* @memberOf KJUR.asn1.x509.Certificate
* @function
* @description
* @example
* var cert = new KJUR.asn1.x509.Certificate({'tbscertobj': tbs, 'rsaprvkey': prvKey});
* cert.sign();
*/
this.sign = function() {
this.asn1SignatureAlg = this.asn1TBSCert.asn1SignatureAlg;
sig = new KJUR.crypto.Signature({'alg': 'SHA1withRSA'});
sig.init(this.prvKey);
sig.updateHex(this.asn1TBSCert.getEncodedHex());
this.hexSig = sig.sign();
this.asn1Sig = new KJUR.asn1.DERBitString({'hex': '00' + this.hexSig});
var seq = new KJUR.asn1.DERSequence({'array': [this.asn1TBSCert,
this.asn1SignatureAlg,
this.asn1Sig]});
this.hTLV = seq.getEncodedHex();
this.isModified = false;
};
this.getEncodedHex = function() {
if (this.isModified == false && this.hTLV != null) return this.hTLV;
throw "not signed yet";
};
/**
* get PEM formatted certificate string after signed
* @name getPEMString
* @memberOf KJUR.asn1.x509.Certificate
* @function
* @return PEM formatted string of certificate
* @description
* @example
* var cert = new KJUR.asn1.x509.Certificate({'tbscertobj': tbs, 'rsaprvkey': prvKey});
* cert.sign();
* var sPEM = cert.getPEMString();
*/
this.getPEMString = function() {
var hCert = this.getEncodedHex();
var wCert = CryptoJS.enc.Hex.parse(hCert);
var b64Cert = CryptoJS.enc.Base64.stringify(wCert);
var pemBody = b64Cert.replace(/(.{64})/g, "$1\r\n");
return "-----BEGIN CERTIFICATE-----\r\n" + pemBody + "\r\n-----END CERTIFICATE-----\r\n";
};
if (typeof params != "undefined") {
if (typeof params['tbscertobj'] != "undefined") {
this.asn1TBSCert = params['tbscertobj'];
}
if (typeof params['prvkeyobj'] != "undefined") {
this.prvKey = params['prvkeyobj'];
} else if (typeof params['rsaprvkey'] != "undefined") {
this.prvKey = params['rsaprvkey'];
} else if ((typeof params['rsaprvpem'] != "undefined") &&
(typeof params['rsaprvpas'] != "undefined")) {
this.setRsaPrvKeyByPEMandPass(params['rsaprvpem'], params['rsaprvpas']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.Certificate, KJUR.asn1.ASN1Object);
/**
* ASN.1 TBSCertificate structure class
* @name KJUR.asn1.x509.TBSCertificate
* @class ASN.1 TBSCertificate structure class
* @param {Array} params associative array of parameters (ex. {})
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* <h4>EXAMPLE</h4>
* @example
* var o = new KJUR.asn1.x509.TBSCertificate();
* o.setSerialNumberByParam({'int': 4});
* o.setSignatureAlgByParam({'name': 'SHA1withRSA'});
* o.setIssuerByParam({'str': '/C=US/O=a'});
* o.setNotBeforeByParam({'str': '130504235959Z'});
* o.setNotAfterByParam({'str': '140504235959Z'});
* o.setSubjectByParam({'str': '/C=US/CN=b'});
* o.setSubjectPublicKeyByParam({'rsakey': rsaKey});
* o.appendExtension(new KJUR.asn1.x509.BasicConstraints({'cA':true}));
* o.appendExtension(new KJUR.asn1.x509.KeyUsage({'bin':'11'}));
*/
KJUR.asn1.x509.TBSCertificate = function(params) {
KJUR.asn1.x509.TBSCertificate.superclass.constructor.call(this);
this._initialize = function() {
this.asn1Array = new Array();
this.asn1Version =
new KJUR.asn1.DERTaggedObject({'obj': new KJUR.asn1.DERInteger({'int': 2})});
this.asn1SerialNumber = null;
this.asn1SignatureAlg = null;
this.asn1Issuer = null;
this.asn1NotBefore = null;
this.asn1NotAfter = null;
this.asn1Subject = null;
this.asn1SubjPKey = null;
this.extensionsArray = new Array();
};
/**
* set serial number field by parameter
* @name setSerialNumberByParam
* @memberOf KJUR.asn1.x509.TBSCertificate
* @function
* @param {Array} intParam DERInteger param
* @description
* @example
* tbsc.setSerialNumberByParam({'int': 3});
*/
this.setSerialNumberByParam = function(intParam) {
this.asn1SerialNumber = new KJUR.asn1.DERInteger(intParam);
};
/**
* set signature algorithm field by parameter
* @name setSignatureAlgByParam
* @memberOf KJUR.asn1.x509.TBSCertificate
* @function
* @param {Array} algIdParam AlgorithmIdentifier parameter
* @description
* @example
* tbsc.setSignatureAlgByParam({'name': 'SHA1withRSA'});
*/
this.setSignatureAlgByParam = function(algIdParam) {
this.asn1SignatureAlg = new KJUR.asn1.x509.AlgorithmIdentifier(algIdParam);
};
/**
* set issuer name field by parameter
* @name setIssuerByParam
* @memberOf KJUR.asn1.x509.TBSCertificate
* @function
* @param {Array} x500NameParam X500Name parameter
* @description
* @example
* tbsc.setIssuerParam({'str': '/C=US/CN=b'});
* @see KJUR.asn1.x509.X500Name
*/
this.setIssuerByParam = function(x500NameParam) {
this.asn1Issuer = new KJUR.asn1.x509.X500Name(x500NameParam);
};
/**
* set notBefore field by parameter
* @name setNotBeforeByParam
* @memberOf KJUR.asn1.x509.TBSCertificate
* @function
* @param {Array} timeParam Time parameter
* @description
* @example
* tbsc.setNotBeforeByParam({'str': '130508235959Z'});
* @see KJUR.asn1.x509.Time
*/
this.setNotBeforeByParam = function(timeParam) {
this.asn1NotBefore = new KJUR.asn1.x509.Time(timeParam);
};
/**
* set notAfter field by parameter
* @name setNotAfterByParam
* @memberOf KJUR.asn1.x509.TBSCertificate
* @function
* @param {Array} timeParam Time parameter
* @description
* @example
* tbsc.setNotAfterByParam({'str': '130508235959Z'});
* @see KJUR.asn1.x509.Time
*/
this.setNotAfterByParam = function(timeParam) {
this.asn1NotAfter = new KJUR.asn1.x509.Time(timeParam);
};
/**
* set subject name field by parameter
* @name setSubjectByParam
* @memberOf KJUR.asn1.x509.TBSCertificate
* @function
* @param {Array} x500NameParam X500Name parameter
* @description
* @example
* tbsc.setSubjectParam({'str': '/C=US/CN=b'});
* @see KJUR.asn1.x509.X500Name
*/
this.setSubjectByParam = function(x500NameParam) {
this.asn1Subject = new KJUR.asn1.x509.X500Name(x500NameParam);
};
/**
* (DEPRECATED) set subject public key info field by RSA key parameter
* @name setSubjectPublicKeyByParam
* @memberOf KJUR.asn1.x509.TBSCertificate
* @function
* @param {Array} subjPKeyParam SubjectPublicKeyInfo parameter of RSA
* @deprecated
* @description
* @example
* tbsc.setSubjectPublicKeyByParam({'rsakey': pubKey});
* @see KJUR.asn1.x509.SubjectPublicKeyInfo
*/
this.setSubjectPublicKeyByParam = function(subjPKeyParam) {
this.asn1SubjPKey = new KJUR.asn1.x509.SubjectPublicKeyInfo(subjPKeyParam);
};
/**
* set subject public key info by RSA/ECDSA/DSA key parameter
* @name setSubjectPublicKeyByGetKey
* @memberOf KJUR.asn1.x509.TBSCertificate
* @function
* @param {Object} keyParam public key parameter which passed to {@link KEYUTIL.getKey} argument
* @description
* @example
* tbsc.setSubjectPublicKeyByGetKeyParam(certPEMString); // or
* tbsc.setSubjectPublicKeyByGetKeyParam(pkcs8PublicKeyPEMString); // or
* tbsc.setSubjectPublicKeyByGetKeyParam(kjurCryptoECDSAKeyObject); // et.al.
* @see KJUR.asn1.x509.SubjectPublicKeyInfo
* @see KEYUTIL.getKey
* @since asn1x509 1.0.6
*/
this.setSubjectPublicKeyByGetKey = function(keyParam) {
var keyObj = KEYUTIL.getKey(keyParam);
this.asn1SubjPKey = new KJUR.asn1.x509.SubjectPublicKeyInfo(keyObj);
};
/**
* append X.509v3 extension to this object
* @name appendExtension
* @memberOf KJUR.asn1.x509.TBSCertificate
* @function
* @param {Extension} extObj X.509v3 Extension object
* @description
* @example
* tbsc.appendExtension(new KJUR.asn1.x509.BasicConstraints({'cA':true, 'critical': true}));
* tbsc.appendExtension(new KJUR.asn1.x509.KeyUsage({'bin':'11'}));
* @see KJUR.asn1.x509.Extension
*/
this.appendExtension = function(extObj) {
this.extensionsArray.push(extObj);
};
/**
* append X.509v3 extension to this object by name and parameters
* @name appendExtensionByName
* @memberOf KJUR.asn1.x509.TBSCertificate
* @function
* @param {name} name name of X.509v3 Extension object
* @param {Array} extParams parameters as argument of Extension constructor.
* @description
* @example
* tbsc.appendExtensionByName('BasicConstraints', {'cA':true, 'critical': true});
* tbsc.appendExtensionByName('KeyUsage', {'bin':'11'});
* tbsc.appendExtensionByName('CRLDistributionPoints', {uri: 'http://aaa.com/a.crl'});
* tbsc.appendExtensionByName('ExtKeyUsage', {array: [{name: 'clientAuth'}]});
* @see KJUR.asn1.x509.Extension
*/
this.appendExtensionByName = function(name, extParams) {
if (name.toLowerCase() == "basicconstraints") {
var extObj = new KJUR.asn1.x509.BasicConstraints(extParams);
this.appendExtension(extObj);
} else if (name.toLowerCase() == "keyusage") {
var extObj = new KJUR.asn1.x509.KeyUsage(extParams);
this.appendExtension(extObj);
} else if (name.toLowerCase() == "crldistributionpoints") {
var extObj = new KJUR.asn1.x509.CRLDistributionPoints(extParams);
this.appendExtension(extObj);
} else if (name.toLowerCase() == "extkeyusage") {
var extObj = new KJUR.asn1.x509.ExtKeyUsage(extParams);
this.appendExtension(extObj);
} else {
throw "unsupported extension name: " + name;
}
};
this.getEncodedHex = function() {
if (this.asn1NotBefore == null || this.asn1NotAfter == null)
throw "notBefore and/or notAfter not set";
var asn1Validity =
new KJUR.asn1.DERSequence({'array':[this.asn1NotBefore, this.asn1NotAfter]});
this.asn1Array = new Array();
this.asn1Array.push(this.asn1Version);
this.asn1Array.push(this.asn1SerialNumber);
this.asn1Array.push(this.asn1SignatureAlg);
this.asn1Array.push(this.asn1Issuer);
this.asn1Array.push(asn1Validity);
this.asn1Array.push(this.asn1Subject);
this.asn1Array.push(this.asn1SubjPKey);
if (this.extensionsArray.length > 0) {
var extSeq = new KJUR.asn1.DERSequence({"array": this.extensionsArray});
var extTagObj = new KJUR.asn1.DERTaggedObject({'explicit': true,
'tag': 'a3',
'obj': extSeq});
this.asn1Array.push(extTagObj);
}
var o = new KJUR.asn1.DERSequence({"array": this.asn1Array});
this.hTLV = o.getEncodedHex();
this.isModified = false;
return this.hTLV;
};
this._initialize();
};
YAHOO.lang.extend(KJUR.asn1.x509.TBSCertificate, KJUR.asn1.ASN1Object);
// === END TBSCertificate ===================================================
// === BEGIN X.509v3 Extensions Related =======================================
/**
* base Extension ASN.1 structure class
* @name KJUR.asn1.x509.Extension
* @class base Extension ASN.1 structure class
* @param {Array} params associative array of parameters (ex. {'critical': true})
* @extends KJUR.asn1.ASN1Object
* @description
* @example
* // Extension ::= SEQUENCE {
* // extnID OBJECT IDENTIFIER,
* // critical BOOLEAN DEFAULT FALSE,
* // extnValue OCTET STRING }
*/
KJUR.asn1.x509.Extension = function(params) {
KJUR.asn1.x509.Extension.superclass.constructor.call(this);
var asn1ExtnValue = null;
this.getEncodedHex = function() {
var asn1Oid = new KJUR.asn1.DERObjectIdentifier({'oid': this.oid});
var asn1EncapExtnValue =
new KJUR.asn1.DEROctetString({'hex': this.getExtnValueHex()});
var asn1Array = new Array();
asn1Array.push(asn1Oid);
if (this.critical) asn1Array.push(new KJUR.asn1.DERBoolean());
asn1Array.push(asn1EncapExtnValue);
var asn1Seq = new KJUR.asn1.DERSequence({'array': asn1Array});
return asn1Seq.getEncodedHex();
};
this.critical = false;
if (typeof params != "undefined") {
if (typeof params['critical'] != "undefined") {
this.critical = params['critical'];
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.Extension, KJUR.asn1.ASN1Object);
/**
* KeyUsage ASN.1 structure class
* @name KJUR.asn1.x509.KeyUsage
* @class KeyUsage ASN.1 structure class
* @param {Array} params associative array of parameters (ex. {'bin': '11', 'critical': true})
* @extends KJUR.asn1.x509.Extension
* @description
* @example
*/
KJUR.asn1.x509.KeyUsage = function(params) {
KJUR.asn1.x509.KeyUsage.superclass.constructor.call(this, params);
this.getExtnValueHex = function() {
return this.asn1ExtnValue.getEncodedHex();
};
this.oid = "2.5.29.15";
if (typeof params != "undefined") {
if (typeof params['bin'] != "undefined") {
this.asn1ExtnValue = new KJUR.asn1.DERBitString(params);
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.KeyUsage, KJUR.asn1.x509.Extension);
/**
* BasicConstraints ASN.1 structure class
* @name KJUR.asn1.x509.BasicConstraints
* @class BasicConstraints ASN.1 structure class
* @param {Array} params associative array of parameters (ex. {'cA': true, 'critical': true})
* @extends KJUR.asn1.x509.Extension
* @description
* @example
*/
KJUR.asn1.x509.BasicConstraints = function(params) {
KJUR.asn1.x509.BasicConstraints.superclass.constructor.call(this, params);
var cA = false;
var pathLen = -1;
this.getExtnValueHex = function() {
var asn1Array = new Array();
if (this.cA) asn1Array.push(new KJUR.asn1.DERBoolean());
if (this.pathLen > -1)
asn1Array.push(new KJUR.asn1.DERInteger({'int': this.pathLen}));
var asn1Seq = new KJUR.asn1.DERSequence({'array': asn1Array});
this.asn1ExtnValue = asn1Seq;
return this.asn1ExtnValue.getEncodedHex();
};
this.oid = "2.5.29.19";
this.cA = false;
this.pathLen = -1;
if (typeof params != "undefined") {
if (typeof params['cA'] != "undefined") {
this.cA = params['cA'];
}
if (typeof params['pathLen'] != "undefined") {
this.pathLen = params['pathLen'];
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.BasicConstraints, KJUR.asn1.x509.Extension);
/**
* CRLDistributionPoints ASN.1 structure class
* @name KJUR.asn1.x509.CRLDistributionPoints
* @class CRLDistributionPoints ASN.1 structure class
* @param {Array} params associative array of parameters (ex. {'uri': 'http://a.com/', 'critical': true})
* @extends KJUR.asn1.x509.Extension
* @description
* @example
*/
KJUR.asn1.x509.CRLDistributionPoints = function(params) {
KJUR.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this, params);
this.getExtnValueHex = function() {
return this.asn1ExtnValue.getEncodedHex();
};
this.setByDPArray = function(dpArray) {
this.asn1ExtnValue = new KJUR.asn1.DERSequence({'array': dpArray});
};
this.setByOneURI = function(uri) {
var gn1 = new KJUR.asn1.x509.GeneralNames([{'uri': uri}]);
var dpn1 = new KJUR.asn1.x509.DistributionPointName(gn1);
var dp1 = new KJUR.asn1.x509.DistributionPoint({'dpobj': dpn1});
this.setByDPArray([dp1]);
};
this.oid = "2.5.29.31";
if (typeof params != "undefined") {
if (typeof params['array'] != "undefined") {
this.setByDPArray(params['array']);
} else if (typeof params['uri'] != "undefined") {
this.setByOneURI(params['uri']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.CRLDistributionPoints, KJUR.asn1.x509.Extension);
/**
* KeyUsage ASN.1 structure class
* @name KJUR.asn1.x509.ExtKeyUsage
* @class ExtKeyUsage ASN.1 structure class
* @param {Array} params associative array of parameters
* @extends KJUR.asn1.x509.Extension
* @description
* @example
* var e1 =
* new KJUR.asn1.x509.ExtKeyUsage({'critical': true,
* 'array':
* [{'oid': '2.5.29.37.0', // anyExtendedKeyUsage
* 'name': 'clientAuth'}]});
*
* // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
* // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
* // KeyPurposeId ::= OBJECT IDENTIFIER
*/
KJUR.asn1.x509.ExtKeyUsage = function(params) {
KJUR.asn1.x509.ExtKeyUsage.superclass.constructor.call(this, params);
this.setPurposeArray = function(purposeArray) {
this.asn1ExtnValue = new KJUR.asn1.DERSequence();
for (var i = 0; i < purposeArray.length; i++) {
var o = new KJUR.asn1.DERObjectIdentifier(purposeArray[i]);
this.asn1ExtnValue.appendASN1Object(o);
}
};
this.getExtnValueHex = function() {
return this.asn1ExtnValue.getEncodedHex();
};
this.oid = "2.5.29.37";
if (typeof params != "undefined") {
if (typeof params['array'] != "undefined") {
this.setPurposeArray(params['array']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.ExtKeyUsage, KJUR.asn1.x509.Extension);
// === END X.509v3 Extensions Related =======================================
// === BEGIN CRL Related ===================================================
/**
* X.509 CRL class to sign and generate hex encoded CRL
* @name KJUR.asn1.x509.CRL
* @class X.509 CRL class to sign and generate hex encoded certificate
* @param {Array} params associative array of parameters (ex. {'tbsobj': obj, 'rsaprvkey': key})
* @extends KJUR.asn1.ASN1Object
* @since 1.0.3
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>tbsobj - specify {@link KJUR.asn1.x509.TBSCertList} object to be signed</li>
* <li>rsaprvkey - specify {@link RSAKey} object CA private key</li>
* </ul>
* NOTE: 'params' can be omitted.
* <h4>EXAMPLE</h4>
* @example
* var prvKey = new RSAKey(); // CA's private key
* prvKey.readPrivateKeyFromASN1HexString("3080...");
* var crl = new KJUR.asn1x509.CRL({'tbsobj': tbs, 'rsaprvkey': prvKey});
* crl.sign(); // issue CRL by CA's private key
* var hCRL = crl.getEncodedHex();
*
* // CertificateList ::= SEQUENCE {
* // tbsCertList TBSCertList,
* // signatureAlgorithm AlgorithmIdentifier,
* // signatureValue BIT STRING }
*/
KJUR.asn1.x509.CRL = function(params) {
KJUR.asn1.x509.CRL.superclass.constructor.call(this);
var asn1TBSCertList = null;
var asn1SignatureAlg = null;
var asn1Sig = null;
var hexSig = null;
var rsaPrvKey = null;
/**
* set PKCS#5 encrypted RSA PEM private key as CA key
* @name setRsaPrvKeyByPEMandPass
* @memberOf KJUR.asn1.x509.CRL
* @function
* @param {String} rsaPEM string of PKCS#5 encrypted RSA PEM private key
* @param {String} passPEM passcode string to decrypt private key
* @description
* <br/>
* <h4>EXAMPLES</h4>
* @example
*/
this.setRsaPrvKeyByPEMandPass = function(rsaPEM, passPEM) {
var caKeyHex = PKCS5PKEY.getDecryptedKeyHex(rsaPEM, passPEM);
var caKey = new RSAKey();
caKey.readPrivateKeyFromASN1HexString(caKeyHex);
this.rsaPrvKey = caKey;
};
/**
* sign TBSCertList and set signature value internally
* @name sign
* @memberOf KJUR.asn1.x509.CRL
* @function
* @description
* @example
* var cert = new KJUR.asn1.x509.CRL({'tbsobj': tbs, 'rsaprvkey': prvKey});
* cert.sign();
*/
this.sign = function() {
this.asn1SignatureAlg = this.asn1TBSCertList.asn1SignatureAlg;
sig = new KJUR.crypto.Signature({'alg': 'SHA1withRSA', 'prov': 'cryptojs/jsrsa'});
sig.initSign(this.rsaPrvKey);
sig.updateHex(this.asn1TBSCertList.getEncodedHex());
this.hexSig = sig.sign();
this.asn1Sig = new KJUR.asn1.DERBitString({'hex': '00' + this.hexSig});
var seq = new KJUR.asn1.DERSequence({'array': [this.asn1TBSCertList,
this.asn1SignatureAlg,
this.asn1Sig]});
this.hTLV = seq.getEncodedHex();
this.isModified = false;
};
this.getEncodedHex = function() {
if (this.isModified == false && this.hTLV != null) return this.hTLV;
throw "not signed yet";
};
/**
* get PEM formatted CRL string after signed
* @name getPEMString
* @memberOf KJUR.asn1.x509.CRL
* @function
* @return PEM formatted string of certificate
* @description
* @example
* var cert = new KJUR.asn1.x509.CRL({'tbsobj': tbs, 'rsaprvkey': prvKey});
* cert.sign();
* var sPEM = cert.getPEMString();
*/
this.getPEMString = function() {
var hCert = this.getEncodedHex();
var wCert = CryptoJS.enc.Hex.parse(hCert);
var b64Cert = CryptoJS.enc.Base64.stringify(wCert);
var pemBody = b64Cert.replace(/(.{64})/g, "$1\r\n");
return "-----BEGIN X509 CRL-----\r\n" + pemBody + "\r\n-----END X509 CRL-----\r\n";
};
if (typeof params != "undefined") {
if (typeof params['tbsobj'] != "undefined") {
this.asn1TBSCertList = params['tbsobj'];
}
if (typeof params['rsaprvkey'] != "undefined") {
this.rsaPrvKey = params['rsaprvkey'];
}
if ((typeof params['rsaprvpem'] != "undefined") &&
(typeof params['rsaprvpas'] != "undefined")) {
this.setRsaPrvKeyByPEMandPass(params['rsaprvpem'], params['rsaprvpas']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.CRL, KJUR.asn1.ASN1Object);
/**
* ASN.1 TBSCertList structure class for CRL
* @name KJUR.asn1.x509.TBSCertList
* @class ASN.1 TBSCertList structure class for CRL
* @param {Array} params associative array of parameters (ex. {})
* @extends KJUR.asn1.ASN1Object
* @since 1.0.3
* @description
* <br/>
* <h4>EXAMPLE</h4>
* @example
* var o = new KJUR.asn1.x509.TBSCertList();
* o.setSignatureAlgByParam({'name': 'SHA1withRSA'});
* o.setIssuerByParam({'str': '/C=US/O=a'});
* o.setNotThisUpdateByParam({'str': '130504235959Z'});
* o.setNotNextUpdateByParam({'str': '140504235959Z'});
* o.addRevokedCert({'int': 4}, {'str':'130514235959Z'}));
* o.addRevokedCert({'hex': '0f34dd'}, {'str':'130514235959Z'}));
*
* // TBSCertList ::= SEQUENCE {
* // version Version OPTIONAL,
* // -- if present, MUST be v2
* // signature AlgorithmIdentifier,
* // issuer Name,
* // thisUpdate Time,
* // nextUpdate Time OPTIONAL,
* // revokedCertificates SEQUENCE OF SEQUENCE {
* // userCertificate CertificateSerialNumber,
* // revocationDate Time,
* // crlEntryExtensions Extensions OPTIONAL
* // -- if present, version MUST be v2
* // } OPTIONAL,
* // crlExtensions [0] EXPLICIT Extensions OPTIONAL
*/
KJUR.asn1.x509.TBSCertList = function(params) {
KJUR.asn1.x509.TBSCertList.superclass.constructor.call(this);
var aRevokedCert = null;
/**
* set signature algorithm field by parameter
* @name setSignatureAlgByParam
* @memberOf KJUR.asn1.x509.TBSCertList
* @function
* @param {Array} algIdParam AlgorithmIdentifier parameter
* @description
* @example
* tbsc.setSignatureAlgByParam({'name': 'SHA1withRSA'});
*/
this.setSignatureAlgByParam = function(algIdParam) {
this.asn1SignatureAlg = new KJUR.asn1.x509.AlgorithmIdentifier(algIdParam);
};
/**
* set issuer name field by parameter
* @name setIssuerByParam
* @memberOf KJUR.asn1.x509.TBSCertList
* @function
* @param {Array} x500NameParam X500Name parameter
* @description
* @example
* tbsc.setIssuerParam({'str': '/C=US/CN=b'});
* @see KJUR.asn1.x509.X500Name
*/
this.setIssuerByParam = function(x500NameParam) {
this.asn1Issuer = new KJUR.asn1.x509.X500Name(x500NameParam);
};
/**
* set thisUpdate field by parameter
* @name setThisUpdateByParam
* @memberOf KJUR.asn1.x509.TBSCertList
* @function
* @param {Array} timeParam Time parameter
* @description
* @example
* tbsc.setThisUpdateByParam({'str': '130508235959Z'});
* @see KJUR.asn1.x509.Time
*/
this.setThisUpdateByParam = function(timeParam) {
this.asn1ThisUpdate = new KJUR.asn1.x509.Time(timeParam);
};
/**
* set nextUpdate field by parameter
* @name setNextUpdateByParam
* @memberOf KJUR.asn1.x509.TBSCertList
* @function
* @param {Array} timeParam Time parameter
* @description
* @example
* tbsc.setNextUpdateByParam({'str': '130508235959Z'});
* @see KJUR.asn1.x509.Time
*/
this.setNextUpdateByParam = function(timeParam) {
this.asn1NextUpdate = new KJUR.asn1.x509.Time(timeParam);
};
/**
* add revoked certficate by parameter
* @name addRevokedCert
* @memberOf KJUR.asn1.x509.TBSCertList
* @function
* @param {Array} snParam DERInteger parameter for certificate serial number
* @param {Array} timeParam Time parameter for revocation date
* @description
* @example
* tbsc.addRevokedCert({'int': 3}, {'str': '130508235959Z'});
* @see KJUR.asn1.x509.Time
*/
this.addRevokedCert = function(snParam, timeParam) {
var param = {};
if (snParam != undefined && snParam != null) param['sn'] = snParam;
if (timeParam != undefined && timeParam != null) param['time'] = timeParam;
var o = new KJUR.asn1.x509.CRLEntry(param);
this.aRevokedCert.push(o);
};
this.getEncodedHex = function() {
this.asn1Array = new Array();
if (this.asn1Version != null) this.asn1Array.push(this.asn1Version);
this.asn1Array.push(this.asn1SignatureAlg);
this.asn1Array.push(this.asn1Issuer);
this.asn1Array.push(this.asn1ThisUpdate);
if (this.asn1NextUpdate != null) this.asn1Array.push(this.asn1NextUpdate);
if (this.aRevokedCert.length > 0) {
var seq = new KJUR.asn1.DERSequence({'array': this.aRevokedCert});
this.asn1Array.push(seq);
}
var o = new KJUR.asn1.DERSequence({"array": this.asn1Array});
this.hTLV = o.getEncodedHex();
this.isModified = false;
return this.hTLV;
};
this._initialize = function() {
this.asn1Version = null;
this.asn1SignatureAlg = null;
this.asn1Issuer = null;
this.asn1ThisUpdate = null;
this.asn1NextUpdate = null;
this.aRevokedCert = new Array();
};
this._initialize();
};
YAHOO.lang.extend(KJUR.asn1.x509.TBSCertList, KJUR.asn1.ASN1Object);
/**
* ASN.1 CRLEntry structure class for CRL
* @name KJUR.asn1.x509.CRLEntry
* @class ASN.1 CRLEntry structure class for CRL
* @param {Array} params associative array of parameters (ex. {})
* @extends KJUR.asn1.ASN1Object
* @since 1.0.3
* @description
* @example
* var e = new KJUR.asn1.x509.CRLEntry({'time': {'str': '130514235959Z'}, 'sn': {'int': 234}});
*
* // revokedCertificates SEQUENCE OF SEQUENCE {
* // userCertificate CertificateSerialNumber,
* // revocationDate Time,
* // crlEntryExtensions Extensions OPTIONAL
* // -- if present, version MUST be v2 }
*/
KJUR.asn1.x509.CRLEntry = function(params) {
KJUR.asn1.x509.CRLEntry.superclass.constructor.call(this);
var sn = null;
var time = null;
/**
* set DERInteger parameter for serial number of revoked certificate
* @name setCertSerial
* @memberOf KJUR.asn1.x509.CRLEntry
* @function
* @param {Array} intParam DERInteger parameter for certificate serial number
* @description
* @example
* entry.setCertSerial({'int': 3});
*/
this.setCertSerial = function(intParam) {
this.sn = new KJUR.asn1.DERInteger(intParam);
};
/**
* set Time parameter for revocation date
* @name setRevocationDate
* @memberOf KJUR.asn1.x509.CRLEntry
* @function
* @param {Array} timeParam Time parameter for revocation date
* @description
* @example
* entry.setRevocationDate({'str': '130508235959Z'});
*/
this.setRevocationDate = function(timeParam) {
this.time = new KJUR.asn1.x509.Time(timeParam);
};
this.getEncodedHex = function() {
var o = new KJUR.asn1.DERSequence({"array": [this.sn, this.time]});
this.TLV = o.getEncodedHex();
return this.TLV;
};
if (typeof params != "undefined") {
if (typeof params['time'] != "undefined") {
this.setRevocationDate(params['time']);
}
if (typeof params['sn'] != "undefined") {
this.setCertSerial(params['sn']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.CRLEntry, KJUR.asn1.ASN1Object);
// === END CRL Related ===================================================
// === BEGIN X500Name Related =================================================
/**
* X500Name ASN.1 structure class
* @name KJUR.asn1.x509.X500Name
* @class X500Name ASN.1 structure class
* @param {Array} params associative array of parameters (ex. {'str': '/C=US/O=a'})
* @extends KJUR.asn1.ASN1Object
* @description
* @example
*/
KJUR.asn1.x509.X500Name = function(params) {
KJUR.asn1.x509.X500Name.superclass.constructor.call(this);
this.asn1Array = new Array();
this.setByString = function(dnStr) {
var a = dnStr.split('/');
a.shift();
for (var i = 0; i < a.length; i++) {
this.asn1Array.push(new KJUR.asn1.x509.RDN({'str':a[i]}));
}
};
this.getEncodedHex = function() {
var o = new KJUR.asn1.DERSequence({"array": this.asn1Array});
this.TLV = o.getEncodedHex();
return this.TLV;
};
if (typeof params != "undefined") {
if (typeof params['str'] != "undefined") {
this.setByString(params['str']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.X500Name, KJUR.asn1.ASN1Object);
/**
* RDN (Relative Distinguish Name) ASN.1 structure class
* @name KJUR.asn1.x509.RDN
* @class RDN (Relative Distinguish Name) ASN.1 structure class
* @param {Array} params associative array of parameters (ex. {'str': 'C=US'})
* @extends KJUR.asn1.ASN1Object
* @description
* @example
*/
KJUR.asn1.x509.RDN = function(params) {
KJUR.asn1.x509.RDN.superclass.constructor.call(this);
this.asn1Array = new Array();
this.addByString = function(rdnStr) {
this.asn1Array.push(new KJUR.asn1.x509.AttributeTypeAndValue({'str':rdnStr}));
};
this.getEncodedHex = function() {
var o = new KJUR.asn1.DERSet({"array": this.asn1Array});
this.TLV = o.getEncodedHex();
return this.TLV;
};
if (typeof params != "undefined") {
if (typeof params['str'] != "undefined") {
this.addByString(params['str']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.RDN, KJUR.asn1.ASN1Object);
/**
* AttributeTypeAndValue ASN.1 structure class
* @name KJUR.asn1.x509.AttributeTypeAndValue
* @class AttributeTypeAndValue ASN.1 structure class
* @param {Array} params associative array of parameters (ex. {'str': 'C=US'})
* @extends KJUR.asn1.ASN1Object
* @description
* @example
*/
KJUR.asn1.x509.AttributeTypeAndValue = function(params) {
KJUR.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this);
var typeObj = null;
var valueObj = null;
var defaultDSType = "utf8";
this.setByString = function(attrTypeAndValueStr) {
if (attrTypeAndValueStr.match(/^([^=]+)=(.+)$/)) {
this.setByAttrTypeAndValueStr(RegExp.$1, RegExp.$2);
} else {
throw "malformed attrTypeAndValueStr: " + attrTypeAndValueStr;
}
};
this.setByAttrTypeAndValueStr = function(shortAttrType, valueStr) {
this.typeObj = KJUR.asn1.x509.OID.atype2obj(shortAttrType);
var dsType = defaultDSType;
if (shortAttrType == "C") dsType = "prn";
this.valueObj = this.getValueObj(dsType, valueStr);
};
this.getValueObj = function(dsType, valueStr) {
if (dsType == "utf8") return new KJUR.asn1.DERUTF8String({"str": valueStr});
if (dsType == "prn") return new KJUR.asn1.DERPrintableString({"str": valueStr});
if (dsType == "tel") return new KJUR.asn1.DERTeletexString({"str": valueStr});
if (dsType == "ia5") return new KJUR.asn1.DERIA5String({"str": valueStr});
throw "unsupported directory string type: type=" + dsType + " value=" + valueStr;
};
this.getEncodedHex = function() {
var o = new KJUR.asn1.DERSequence({"array": [this.typeObj, this.valueObj]});
this.TLV = o.getEncodedHex();
return this.TLV;
};
if (typeof params != "undefined") {
if (typeof params['str'] != "undefined") {
this.setByString(params['str']);
}
}
};
YAHOO.lang.extend(KJUR.asn1.x509.AttributeTypeAndValue, KJUR.asn1.ASN1Object);
// === END X500Name Related =================================================
// === BEGIN Other ASN1 structure class ======================================
/**
* SubjectPublicKeyInfo ASN.1 structure class
* @name KJUR.asn1.x509.SubjectPublicKeyInfo
* @class SubjectPublicKeyInfo ASN.1 structure class
* @param {Object} params parameter for subject public key
* @extends KJUR.asn1.ASN1Object
* @description
* <br/>
* As for argument 'params' for constructor, you can specify one of
* following properties:
* <ul>
* <li>{@link RSAKey} object</li>
* <li>{@link KJUR.crypto.ECDSA} object</li>
* <li>{@link KJUR.crypto.DSA} object</li>
* <li>(DEPRECATED)rsakey - specify {@link RSAKey} object of subject public key</li>
* <li>(DEPRECATED)rsapem - specify a string of PEM public key of RSA key</li>
* </ul>
* NOTE1: 'params' can be omitted.<br/>
* NOTE2: DSA/ECDSA key object is also supported since asn1x509 1.0.6.<br/>
* <h4>EXAMPLE</h4>
* @example
* var spki = new KJUR.asn1.x509.SubjectPublicKeyInfo(RSAKey_object);
* var spki = new KJUR.asn1.x509.SubjectPublicKeyInfo(KJURcryptoECDSA_object);
* var spki = new KJUR.asn1.x509.SubjectPublicKeyInfo(KJURcryptoDSA_object);
*/
KJUR.asn1.x509.SubjectPublicKeyInfo = function(params) {
KJUR.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);
var asn1AlgId = null;
var asn1SubjPKey = null;
var rsaKey = null;
/**
* (DEPRECATED) set RSAKey object as subject public key
* @name setRSAKey
* @memberOf KJUR.asn1.x509.SubjectPublicKeyInfo
* @function
* @param {RSAKey} rsaKey {@link RSAKey} object for RSA public key
* @description
* @deprecated
* @example
* spki.setRSAKey(rsaKey);
*/
this.setRSAKey = function(rsaKey) {
if (! RSAKey.prototype.isPrototypeOf(rsaKey))
throw "argument is not RSAKey instance";
this.rsaKey = rsaKey;
var asn1RsaN = new KJUR.asn1.DERInteger({'bigint': rsaKey.n});
var asn1RsaE = new KJUR.asn1.DERInteger({'int': rsaKey.e});
var asn1RsaPub = new KJUR.asn1.DERSequence({'array': [asn1RsaN, asn1RsaE]});
var rsaKeyHex = asn1RsaPub.getEncodedHex();
this.asn1AlgId = new KJUR.asn1.x509.AlgorithmIdentifier({'name':'rsaEncryption'});
this.asn1SubjPKey = new KJUR.asn1.DERBitString({'hex':'00'+rsaKeyHex});
};
/**
* (DEPRECATED) set a PEM formatted RSA public key string as RSA public key
* @name setRSAPEM
* @memberOf KJUR.asn1.x509.SubjectPublicKeyInfo
* @function
* @param {String} rsaPubPEM PEM formatted RSA public key string
* @deprecated
* @description
* @example
* spki.setRSAPEM(rsaPubPEM);
*/
this.setRSAPEM = function(rsaPubPEM) {
if (rsaPubPEM.match(/-----BEGIN PUBLIC KEY-----/)) {
var s = rsaPubPEM;
s = s.replace(/^-----[^-]+-----/, '');
s = s.replace(/-----[^-]+-----\s*$/, '');
var rsaB64 = s.replace(/\s+/g, '');
var rsaWA = CryptoJS.enc.Base64.parse(rsaB64);
var rsaP8Hex = CryptoJS.enc.Hex.stringify(rsaWA);
var a = _rsapem_getHexValueArrayOfChildrenFromHex(rsaP8Hex);
var hBitStrVal = a[1];
var rsaHex = hBitStrVal.substr(2);
var a3 = _rsapem_getHexValueArrayOfChildrenFromHex(rsaHex);
var rsaKey = new RSAKey();
rsaKey.setPublic(a3[0], a3[1]);
this.setRSAKey(rsaKey);
} else {
throw "key not supported";
}
};
/*
* @since asn1x509 1.0.7
*/
this.getASN1Object = function() {
if (this.asn1AlgId == null || this.asn1SubjPKey == null)
throw "algId and/or subjPubKey not set";
var o = new KJUR.asn1.DERSequence({'array':
[this.asn1AlgId, this.asn1SubjPKey]});
return o;
};
this.getEncodedHex = function() {
var o = this.getASN1Object();
this.hTLV = o.getEncodedHex();
return this.hTLV;
};
this._setRSAKey = function(key) {
var asn1RsaPub = KJUR.asn1.ASN1Util.newObject({
'seq': [{'int': {'bigint': key.n}}, {'int': {'int': key.e}}]
});
var rsaKeyHex = asn1RsaPub.getEncodedHex();
this.asn1AlgId = new KJUR.
gitextract_g_s27c19/ ├── C/ │ ├── SM2_SM3_SM4_C语言实现/ │ │ ├── SM2/ │ │ │ ├── kdf.h │ │ │ ├── sm2.c │ │ │ ├── sm2.dsp │ │ │ ├── sm2.dsw │ │ │ ├── sm2.h │ │ │ └── sm2test.c │ │ ├── SM3/ │ │ │ ├── sm3.c │ │ │ ├── sm3.h │ │ │ ├── sm3test.c │ │ │ ├── sm3test.dsp │ │ │ └── sm3test.dsw │ │ └── SM4/ │ │ ├── sm4.c │ │ ├── sm4.dsp │ │ ├── sm4.dsw │ │ ├── sm4.h │ │ ├── sm4test.c │ │ └── sms4.c │ └── sm4.c ├── Java/ │ └── JavaSM4.java ├── JavaScript/ │ ├── demo/ │ │ ├── js/ │ │ │ ├── asn1-1.0.js │ │ │ ├── asn1hex-1.1.js │ │ │ ├── asn1x509-1.0.js │ │ │ ├── base64.js │ │ │ ├── cipher-core.js │ │ │ ├── core.js │ │ │ ├── crypto-1.1.js │ │ │ ├── ec-patch.js │ │ │ ├── ec.js │ │ │ ├── ecdsa-modified-1.0.js │ │ │ ├── ecparam-1.0.js │ │ │ ├── enc-base64.js │ │ │ ├── fingerprint.js │ │ │ ├── fingerprint2.js │ │ │ ├── jsbn.js │ │ │ ├── jsbn2.js │ │ │ ├── md5.js │ │ │ ├── pkcs5pkey-1.0.js │ │ │ ├── prng4.js │ │ │ ├── rng.js │ │ │ ├── rsa.js │ │ │ ├── rsa2.js │ │ │ ├── rsapem-1.1.js │ │ │ ├── rsasign-1.2.js │ │ │ ├── sha1.js │ │ │ ├── sha256.js │ │ │ ├── sm2-guomi.js │ │ │ ├── sm2.js │ │ │ ├── sm3-guomi.js │ │ │ ├── sm3-sm2-1.0.js │ │ │ ├── sm3.js │ │ │ ├── sm4.js │ │ │ ├── tripledes.js │ │ │ ├── utils.js │ │ │ ├── x509-1.1.js │ │ │ └── yahoo-min.js │ │ └── performance.html │ ├── des/ │ │ └── JavaScript DES Example.html │ ├── js/ │ │ └── sm4.js │ ├── sm2/ │ │ ├── js/ │ │ │ ├── asn1-1.0.js │ │ │ ├── asn1hex-1.1.js │ │ │ ├── asn1x509-1.0.js │ │ │ ├── base64.js │ │ │ ├── cipher-core.js │ │ │ ├── core.js │ │ │ ├── crypto-1.1.js │ │ │ ├── ec-patch.js │ │ │ ├── ec.js │ │ │ ├── ecdsa-modified-1.0.js │ │ │ ├── ecparam-1.0.js │ │ │ ├── enc-base64.js │ │ │ ├── fingerprint.js │ │ │ ├── jsbn.js │ │ │ ├── jsbn2.js │ │ │ ├── md5.js │ │ │ ├── pkcs5pkey-1.0.js │ │ │ ├── prng4.js │ │ │ ├── rng.js │ │ │ ├── rsa.js │ │ │ ├── rsa2.js │ │ │ ├── rsapem-1.1.js │ │ │ ├── rsasign-1.2.js │ │ │ ├── sha1.js │ │ │ ├── sha256.js │ │ │ ├── sm2-guomi.js │ │ │ ├── sm2.js │ │ │ ├── sm3-guomi.js │ │ │ ├── sm3-sm2-1.0.js │ │ │ ├── sm3.js │ │ │ ├── tripledes.js │ │ │ ├── x509-1.1.js │ │ │ └── yahoo-min.js │ │ ├── sm2.html │ │ └── sm2_decrypt.html │ └── sm4.html ├── Python/ │ └── sm4.py └── README.md
SYMBOL INDEX (527 symbols across 62 files)
FILE: C/SM2_SM3_SM4_C语言实现/SM2/kdf.h
function x9_63_kdf (line 8) | int x9_63_kdf(const EVP_MD *md, const unsigned char *share, size_t share...
FILE: C/SM2_SM3_SM4_C语言实现/SM2/sm2.c
function BNPrintf (line 20) | static void BNPrintf(BIGNUM* bn)
function sm2_sign_setup (line 29) | static int sm2_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kp, BI...
function ECDSA_SIG (line 150) | static ECDSA_SIG *sm2_do_sign(const unsigned char *dgst, int dgst_len, c...
function sm2_do_verify (line 326) | static int sm2_do_verify(const unsigned char *dgst, int dgst_len,
function EC_POINT (line 456) | EC_POINT *sm2_compute_key(const EC_POINT *b_pub_key_r, const EC_POINT *b...
function SM2_sign_setup (line 640) | int SM2_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNU...
function SM2_sign_ex (line 661) | int SM2_sign_ex(int type, const unsigned char *dgst, int dlen, unsigne...
function SM2_sign (line 689) | int SM2_sign(int type, const unsigned char *dgst, int dlen, unsigned char
function SM2_verify (line 709) | int SM2_verify(int type, const unsigned char *dgst, int dgst_len,
function SM2_DH_key (line 724) | int SM2_DH_key(const EC_GROUP * group, const EC_POINT *b_pub_key_r, cons...
FILE: C/SM2_SM3_SM4_C语言实现/SM2/sm2test.c
function BNPrintf (line 25) | void BNPrintf(BIGNUM* bn)
function SM2_Test_Vecotor (line 34) | int SM2_Test_Vecotor()
function SM2_Test_Vecotor2 (line 179) | int SM2_Test_Vecotor2()
function main (line 429) | int main()
FILE: C/SM2_SM3_SM4_C语言实现/SM3/sm3.c
function sm3_starts (line 49) | void sm3_starts( sm3_context *ctx )
function sm3_process (line 65) | static void sm3_process( sm3_context *ctx, unsigned char data[64] )
function sm3_update (line 233) | void sm3_update( sm3_context *ctx, unsigned char *input, int ilen )
function sm3_finish (line 285) | void sm3_finish( sm3_context *ctx, unsigned char output[32] )
function sm3 (line 317) | void sm3( unsigned char *input, int ilen,
function sm3_file (line 332) | int sm3_file( char *path, unsigned char output[32] )
function sm3_hmac_starts (line 364) | void sm3_hmac_starts( sm3_context *ctx, unsigned char *key, int keylen )
function sm3_hmac_update (line 395) | void sm3_hmac_update( sm3_context *ctx, unsigned char *input, int ilen )
function sm3_hmac_finish (line 403) | void sm3_hmac_finish( sm3_context *ctx, unsigned char output[32] )
function sm3_hmac (line 423) | void sm3_hmac( unsigned char *key, int keylen,
FILE: C/SM2_SM3_SM4_C语言实现/SM3/sm3.h
type sm3_context (line 16) | typedef struct
FILE: C/SM2_SM3_SM4_C语言实现/SM3/sm3test.c
function main (line 6) | int main( int argc, char *argv[] )
FILE: C/SM2_SM3_SM4_C语言实现/SM4/sm4.c
function sm4Sbox (line 137) | static unsigned char sm4Sbox(unsigned char inch)
function sm4Lt (line 150) | static unsigned long sm4Lt(unsigned long ka)
function sm4F (line 176) | static unsigned long sm4F(unsigned long x0, unsigned long x1, unsigned l...
function sm4CalciRK (line 187) | static unsigned long sm4CalciRK(unsigned long ka)
function sm4_setkey (line 203) | static void sm4_setkey( unsigned long SK[32], unsigned char key[16] )
function sm4_one_round (line 229) | static void sm4_one_round( unsigned long sk[32],
function sm4_setkey_enc (line 258) | void sm4_setkey_enc( sm4_context *ctx, unsigned char key[16] )
function sm4_setkey_dec (line 267) | void sm4_setkey_dec( sm4_context *ctx, unsigned char key[16] )
function sm4_crypt_ecb (line 283) | void sm4_crypt_ecb( sm4_context *ctx,
function sm4_crypt_cbc (line 302) | void sm4_crypt_cbc( sm4_context *ctx,
FILE: C/SM2_SM3_SM4_C语言实现/SM4/sm4.h
type sm4_context (line 13) | typedef struct
FILE: C/SM2_SM3_SM4_C语言实现/SM4/sm4test.c
function main (line 10) | int main()
FILE: C/SM2_SM3_SM4_C语言实现/SM4/sms4.c
type unlong (line 27) | typedef unsigned long unlong;
type unchar (line 31) | typedef unsigned char unchar;
function unchar (line 115) | static unchar SMS4Sbox(unchar inch)
function unlong (line 129) | static unlong SMS4Lt(unlong a)
function unlong (line 154) | static unlong SMS4CalciRK(unlong a)
function SMS4CalcRK (line 179) | static void SMS4CalcRK(unlong ulflag)
function unlong (line 209) | static unlong SMS4T(unlong a)
function unlong (line 224) | static unlong SMS4F(unlong x0, unlong x1, unlong x2, unlong x3, unlong rk)
function unlong (line 236) | unlong *SMS4SetKey(unlong *ulkey, unlong flag)
function unlong (line 256) | unlong *SMS4Encrypt(unlong *psrc, unlong lgsrc, unlong rk[])
function unlong (line 321) | unlong *SMS4Decrypt(unlong *psrc, unlong lgsrc, unlong derk[])
function SMS4Encrypt1M (line 338) | void SMS4Encrypt1M()
function main (line 359) | int main()
FILE: C/sm4.c
type sm4_context (line 16) | typedef struct
function sm4Sbox (line 195) | static unsigned char sm4Sbox(unsigned char inch)
function sm4Lt (line 208) | static unsigned long sm4Lt(unsigned long ka)
function sm4F (line 234) | static unsigned long sm4F(unsigned long x0, unsigned long x1, unsigned l...
function sm4CalciRK (line 245) | static unsigned long sm4CalciRK(unsigned long ka)
function sm4_setkey (line 261) | static void sm4_setkey( unsigned long SK[32], unsigned char key[16] )
function sm4_one_round (line 287) | static void sm4_one_round( unsigned long sk[32],
function sm4_setkey_enc (line 316) | void sm4_setkey_enc( sm4_context *ctx, unsigned char key[16] )
function sm4_setkey_dec (line 325) | void sm4_setkey_dec( sm4_context *ctx, unsigned char key[16] )
function sm4_crypt_ecb (line 341) | void sm4_crypt_ecb( sm4_context *ctx,
function sm4_crypt_cbc (line 360) | void sm4_crypt_cbc( sm4_context *ctx,
function main (line 404) | int main()
FILE: Java/JavaSM4.java
class JavaSM4 (line 1) | public class JavaSM4 {
method main (line 35) | public static void main(String[] args)
method sm4 (line 56) | private static int[] sm4(int[] t,int s)
method initrk (line 81) | private static int[] initrk()
method r (line 97) | private static int[] r(int[] x)
method f (line 108) | private static int f(int x0,int x1,int x2,int x3,int k)
method t (line 113) | private static int t(int ta)
method tn (line 118) | private static int tn(int ta)
method l (line 123) | private static int l(int temp)
method ln (line 127) | private static int ln(int temp)
method tj (line 132) | private static int tj(int a)
method sbox (line 145) | private static byte sbox(byte a)
method Px (line 151) | private static int Px(int x,int n)
method bytesToInt (line 155) | private static int bytesToInt(byte b0,byte b1,byte b2,byte b3) // int ...
method intToBytes (line 168) | private static byte[] intToBytes(int i)
FILE: JavaScript/demo/js/base64.js
function hex2b64 (line 6) | function hex2b64(h) {
function b64tohex (line 27) | function b64tohex(s) {
function b64toBA (line 65) | function b64toBA(s) {
FILE: JavaScript/demo/js/cipher-core.js
function selectCipherStrategy (line 181) | function selectCipherStrategy(key) {
function xorBlock (line 344) | function xorBlock(words, offset, blockSize) {
FILE: JavaScript/demo/js/core.js
function F (line 25) | function F() {}
FILE: JavaScript/demo/js/ec.js
function ECFieldElementFp (line 13) | function ECFieldElementFp(q,x) {
function feFpEquals (line 19) | function feFpEquals(other) {
function feFpToBigInteger (line 24) | function feFpToBigInteger() {
function feFpNegate (line 28) | function feFpNegate() {
function feFpAdd (line 32) | function feFpAdd(b) {
function feFpSubtract (line 36) | function feFpSubtract(b) {
function feFpMultiply (line 40) | function feFpMultiply(b) {
function feFpSquare (line 44) | function feFpSquare() {
function feFpDivide (line 48) | function feFpDivide(b) {
function ECPointFp (line 65) | function ECPointFp(curve,x,y,z) {
function pointFpGetX (line 81) | function pointFpGetX() {
function pointFpGetY (line 88) | function pointFpGetY() {
function pointFpEquals (line 95) | function pointFpEquals(other) {
function pointFpIsInfinity (line 108) | function pointFpIsInfinity() {
function pointFpNegate (line 113) | function pointFpNegate() {
function pointFpAdd (line 117) | function pointFpAdd(b) {
function pointFpTwice (line 154) | function pointFpTwice() {
function pointFpMultiply (line 185) | function pointFpMultiply(k) {
function pointFpMultiplyTwo (line 211) | function pointFpMultiplyTwo(j,x,k) {
function ECCurveFp (line 255) | function ECCurveFp(q,a,b) {
function curveFpGetQ (line 262) | function curveFpGetQ() {
function curveFpGetA (line 266) | function curveFpGetA() {
function curveFpGetB (line 270) | function curveFpGetB() {
function curveFpEquals (line 274) | function curveFpEquals(other) {
function curveFpGetInfinity (line 279) | function curveFpGetInfinity() {
function curveFpFromBigInteger (line 283) | function curveFpFromBigInteger(x) {
function curveFpDecodePointHex (line 288) | function curveFpDecodePointHex(s) {
FILE: JavaScript/demo/js/ecdsa-modified-1.0.js
function implShamirsTrick (line 56) | function implShamirsTrick(P, k, Q, l) {
FILE: JavaScript/demo/js/ecparam-1.0.js
function hex2bi (line 54) | function hex2bi(hex) {
FILE: JavaScript/demo/js/jsbn.js
function BigInteger (line 17) | function BigInteger(a,b,c) {
function nbi (line 25) | function nbi() { return new BigInteger(null); }
function am1 (line 35) | function am1(i,x,w,j,c,n) {
function am2 (line 46) | function am2(i,x,w,j,c,n) {
function am3 (line 60) | function am3(i,x,w,j,c,n) {
function int2char (line 105) | function int2char(n) { return BI_RM.charAt(n); }
function intAt (line 106) | function intAt(s,i) {
function bnpCopyTo (line 112) | function bnpCopyTo(r) {
function bnpFromInt (line 119) | function bnpFromInt(x) {
function nbv (line 128) | function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
function bnpFromString (line 131) | function bnpFromString(s,b) {
function bnpClamp (line 170) | function bnpClamp() {
function bnToString (line 176) | function bnToString(b) {
function bnNegate (line 206) | function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); retu...
function bnAbs (line 209) | function bnAbs() { return (this.s<0)?this.negate():this; }
function bnCompareTo (line 212) | function bnCompareTo(a) {
function nbits (line 223) | function nbits(x) {
function bnBitLength (line 234) | function bnBitLength() {
function bnpDLShiftTo (line 240) | function bnpDLShiftTo(n,r) {
function bnpDRShiftTo (line 249) | function bnpDRShiftTo(n,r) {
function bnpLShiftTo (line 256) | function bnpLShiftTo(n,r) {
function bnpRShiftTo (line 273) | function bnpRShiftTo(n,r) {
function bnpSubTo (line 291) | function bnpSubTo(a,r) {
function bnpMultiplyTo (line 325) | function bnpMultiplyTo(a,r) {
function bnpSquareTo (line 337) | function bnpSquareTo(r) {
function bnpDivRemTo (line 355) | function bnpDivRemTo(m,q,r) {
function bnMod (line 403) | function bnMod(a) {
function Classic (line 411) | function Classic(m) { this.m = m; }
function cConvert (line 412) | function cConvert(x) {
function cRevert (line 416) | function cRevert(x) { return x; }
function cReduce (line 417) | function cReduce(x) { x.divRemTo(this.m,null,x); }
function cMulTo (line 418) | function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
function cSqrTo (line 419) | function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
function bnpInvDigit (line 437) | function bnpInvDigit() {
function Montgomery (line 453) | function Montgomery(m) {
function montConvert (line 463) | function montConvert(x) {
function montRevert (line 472) | function montRevert(x) {
function montReduce (line 480) | function montReduce(x) {
function montSqrTo (line 499) | function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
function montMulTo (line 502) | function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
function bnpIsEven (line 511) | function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
function bnpExp (line 514) | function bnpExp(e,z) {
function bnModPowInt (line 527) | function bnModPowInt(e,m) {
FILE: JavaScript/demo/js/jsbn2.js
function bnClone (line 13) | function bnClone() { var r = nbi(); this.copyTo(r); return r; }
function bnIntValue (line 16) | function bnIntValue() {
function bnByteValue (line 28) | function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }
function bnShortValue (line 31) | function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
function bnpChunkSize (line 34) | function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r...
function bnSigNum (line 37) | function bnSigNum() {
function bnpToRadix (line 44) | function bnpToRadix(b) {
function bnpFromRadix (line 59) | function bnpFromRadix(s,b) {
function bnpFromNumber (line 86) | function bnpFromNumber(a,b,c) {
function bnToByteArray (line 112) | function bnToByteArray() {
function bnEquals (line 136) | function bnEquals(a) { return(this.compareTo(a)==0); }
function bnMin (line 137) | function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
function bnMax (line 138) | function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
function bnpBitwiseTo (line 141) | function bnpBitwiseTo(a,op,r) {
function op_and (line 159) | function op_and(x,y) { return x&y; }
function bnAnd (line 160) | function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
function op_or (line 163) | function op_or(x,y) { return x|y; }
function bnOr (line 164) | function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
function op_xor (line 167) | function op_xor(x,y) { return x^y; }
function bnXor (line 168) | function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
function op_andnot (line 171) | function op_andnot(x,y) { return x&~y; }
function bnAndNot (line 172) | function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); ret...
function bnNot (line 175) | function bnNot() {
function bnShiftLeft (line 184) | function bnShiftLeft(n) {
function bnShiftRight (line 191) | function bnShiftRight(n) {
function lbit (line 198) | function lbit(x) {
function bnGetLowestSetBit (line 210) | function bnGetLowestSetBit() {
function cbit (line 218) | function cbit(x) {
function bnBitCount (line 225) | function bnBitCount() {
function bnTestBit (line 232) | function bnTestBit(n) {
function bnpChangeBit (line 239) | function bnpChangeBit(n,op) {
function bnSetBit (line 246) | function bnSetBit(n) { return this.changeBit(n,op_or); }
function bnClearBit (line 249) | function bnClearBit(n) { return this.changeBit(n,op_andnot); }
function bnFlipBit (line 252) | function bnFlipBit(n) { return this.changeBit(n,op_xor); }
function bnpAddTo (line 255) | function bnpAddTo(a,r) {
function bnAdd (line 288) | function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
function bnSubtract (line 291) | function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
function bnMultiply (line 294) | function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
function bnSquare (line 297) | function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
function bnDivide (line 300) | function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
function bnRemainder (line 303) | function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return...
function bnDivideAndRemainder (line 306) | function bnDivideAndRemainder(a) {
function bnpDMultiply (line 313) | function bnpDMultiply(n) {
function bnpDAddOffset (line 320) | function bnpDAddOffset(n,w) {
function NullExp (line 332) | function NullExp() {}
function nNop (line 333) | function nNop(x) { return x; }
function nMulTo (line 334) | function nMulTo(x,y,r) { x.multiplyTo(y,r); }
function nSqrTo (line 335) | function nSqrTo(x,r) { x.squareTo(r); }
function bnPow (line 343) | function bnPow(e) { return this.exp(e,new NullExp()); }
function bnpMultiplyLowerTo (line 347) | function bnpMultiplyLowerTo(a,n,r) {
function bnpMultiplyUpperTo (line 360) | function bnpMultiplyUpperTo(a,n,r) {
function Barrett (line 372) | function Barrett(m) {
function barrettConvert (line 381) | function barrettConvert(x) {
function barrettRevert (line 387) | function barrettRevert(x) { return x; }
function barrettReduce (line 390) | function barrettReduce(x) {
function barrettSqrTo (line 401) | function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
function barrettMulTo (line 404) | function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
function bnModPow (line 413) | function bnModPow(e,m) {
function bnGCD (line 472) | function bnGCD(a) {
function bnpModInt (line 500) | function bnpModInt(n) {
function bnModInverse (line 510) | function bnModInverse(m) {
function bnIsProbablePrime (line 555) | function bnIsProbablePrime(t) {
function bnpMillerRabin (line 574) | function bnpMillerRabin(t) {
FILE: JavaScript/demo/js/md5.js
function FF (line 203) | function FF(a, b, c, d, x, s, t) {
function GG (line 208) | function GG(a, b, c, d, x, s, t) {
function HH (line 213) | function HH(a, b, c, d, x, s, t) {
function II (line 218) | function II(a, b, c, d, x, s, t) {
FILE: JavaScript/demo/js/prng4.js
function Arcfour (line 5) | function Arcfour() {
function ARC4init (line 12) | function ARC4init(key) {
function ARC4next (line 27) | function ARC4next() {
function prng_newstate (line 41) | function prng_newstate() {
FILE: JavaScript/demo/js/rng.js
function rng_seed_int (line 14) | function rng_seed_int(x) {
function rng_seed_time (line 23) | function rng_seed_time() {
function rng_get_byte (line 49) | function rng_get_byte() {
function rng_get_bytes (line 63) | function rng_get_bytes(ba) {
function SecureRandom (line 68) | function SecureRandom() {}
FILE: JavaScript/demo/js/rsa.js
function parseBigInt (line 8) | function parseBigInt(str,r) {
function linebrk (line 12) | function linebrk(s,n) {
function byte2Hex (line 22) | function byte2Hex(b) {
function pkcs1pad2 (line 30) | function pkcs1pad2(s,n) {
function oaep_mgf1_arr (line 66) | function oaep_mgf1_arr(seed, len, hash)
function oaep_pad (line 86) | function oaep_pad(s, n, hash)
function RSAKey (line 124) | function RSAKey() {
function RSASetPublic (line 136) | function RSASetPublic(N,E) {
function RSADoPublic (line 152) | function RSADoPublic(x) {
function RSAEncrypt (line 157) | function RSAEncrypt(text) {
function RSAEncryptOAEP (line 167) | function RSAEncryptOAEP(text, hash) {
FILE: JavaScript/demo/js/rsa2.js
function pkcs1unpad2 (line 8) | function pkcs1unpad2(d,n) {
function oaep_mgf1_str (line 36) | function oaep_mgf1_str(seed, len, hash)
function oaep_unpad (line 56) | function oaep_unpad(d, n, hash)
function RSASetPrivate (line 121) | function RSASetPrivate(N,E,D) {
function RSASetPrivateEx (line 139) | function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
function RSAGenerate (line 161) | function RSAGenerate(B,E) {
function RSADoPrivate (line 195) | function RSADoPrivate(x) {
function RSADecrypt (line 214) | function RSADecrypt(ctext) {
function RSADecryptOAEP (line 223) | function RSADecryptOAEP(ctext, hash) {
FILE: JavaScript/demo/js/rsapem-1.1.js
function _rsapem_pemToBase64 (line 35) | function _rsapem_pemToBase64(sPEMPrivateKey) {
function _rsapem_getPosArrayOfChildrenFromHex (line 43) | function _rsapem_getPosArrayOfChildrenFromHex(hPrivateKey) {
function _rsapem_getHexValueArrayOfChildrenFromHex (line 58) | function _rsapem_getHexValueArrayOfChildrenFromHex(hPrivateKey) {
function _rsapem_readPrivateKeyFromASN1HexString (line 82) | function _rsapem_readPrivateKeyFromASN1HexString(keyHex) {
function _rsapem_readPrivateKeyFromPEMString (line 94) | function _rsapem_readPrivateKeyFromPEMString(keyPEM) {
FILE: JavaScript/demo/js/rsasign-1.2.js
function _rsasign_getHexPaddedDigestInfoForString (line 32) | function _rsasign_getHexPaddedDigestInfoForString(s, keySize, hashAlg) {
function _zeroPaddingOfSignature (line 39) | function _zeroPaddingOfSignature(hex, bitLength) {
function _rsasign_signString (line 57) | function _rsasign_signString(s, hashAlg) {
function _rsasign_signWithMessageHash (line 74) | function _rsasign_signWithMessageHash(sHashHex, hashAlg) {
function _rsasign_signStringWithSHA1 (line 82) | function _rsasign_signStringWithSHA1(s) {
function _rsasign_signStringWithSHA256 (line 86) | function _rsasign_signStringWithSHA256(s) {
function pss_mgf1_str (line 91) | function pss_mgf1_str(seed, len, hash) {
function _rsasign_signStringPSS (line 123) | function _rsasign_signStringPSS(s, hashAlg, sLen) {
function _rsasign_signWithMessageHashPSS (line 149) | function _rsasign_signWithMessageHashPSS(hHash, hashAlg, sLen) {
function _rsasign_getDecryptSignatureBI (line 209) | function _rsasign_getDecryptSignatureBI(biSig, hN, hE) {
function _rsasign_getHexDigestInfoFromSig (line 216) | function _rsasign_getHexDigestInfoFromSig(biSig, hN, hE) {
function _rsasign_getAlgNameAndHashFromHexDisgestInfo (line 222) | function _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo) {
function _rsasign_verifySignatureWithArgs (line 234) | function _rsasign_verifySignatureWithArgs(sMsg, biSig, hN, hE) {
function _rsasign_verifyHexSignatureForMessage (line 245) | function _rsasign_verifyHexSignatureForMessage(hSig, sMsg) {
function _rsasign_verifyString (line 263) | function _rsasign_verifyString(sMsg, hSig) {
function _rsasign_verifyWithMessageHash (line 291) | function _rsasign_verifyWithMessageHash(sHashHex, hSig) {
function _rsasign_verifyStringPSS (line 324) | function _rsasign_verifyStringPSS(sMsg, hSig, hashAlg, sLen) {
function _rsasign_verifyWithMessageHashPSS (line 351) | function _rsasign_verifyWithMessageHashPSS(hHash, hSig, hashAlg, sLen) {
FILE: JavaScript/demo/js/sha256.js
function isPrime (line 21) | function isPrime(n) {
function getFractionalBits (line 32) | function getFractionalBits(n) {
FILE: JavaScript/demo/js/sm2-guomi.js
function SM2Cipher (line 1) | function SM2Cipher(cipherMode) {
FILE: JavaScript/demo/js/sm2.js
function SM2Cipher (line 1) | function SM2Cipher(cipherMode){this.ct=1;this.p2=null;this.sm3keybase=nu...
FILE: JavaScript/demo/js/sm3-guomi.js
function SM3Digest (line 70) | function SM3Digest() {
FILE: JavaScript/demo/js/sm3-sm2-1.0.js
function implShamirsTrick (line 50) | function implShamirsTrick(P, k, Q, l) {
FILE: JavaScript/demo/js/sm3.js
function SM3Digest (line 1) | function SM3Digest(){this.BYTE_LENGTH=64;this.xBuf=new Array();this.xBuf...
FILE: JavaScript/demo/js/sm4.js
function bigxor (line 78) | function bigxor(a, b){
function leftshift (line 94) | function leftshift(a, n, size=32) {
function prefixInteger (line 99) | function prefixInteger(str, length) {
function sm4Sbox (line 116) | function sm4Sbox(a) {
function GET_ULONG_BE (line 124) | function GET_ULONG_BE (a) {
function PUT_ULONG_BE (line 129) | function PUT_ULONG_BE(b) {
function sm4_getkey (line 134) | function sm4_getkey (MK) {
function KJUR_encrypt_sm4 (line 149) | function KJUR_encrypt_sm4 (messsage, key, method) {
function KJUR_decrypt_sm4 (line 160) | function KJUR_decrypt_sm4 (ciphertext, key, method) {
FILE: JavaScript/demo/js/tripledes.js
function exchangeLR (line 691) | function exchangeLR(offset, mask) {
function exchangeRL (line 697) | function exchangeRL(offset, mask) {
FILE: JavaScript/demo/js/utils.js
function encode (line 15) | function encode(s) {
function decode (line 21) | function decode(s) {
function PKCS7_padding_encode (line 27) | function PKCS7_padding_encode(data){
function PKCS7_padding_decode (line 39) | function PKCS7_padding_decode(data){
function randomkey (line 51) | function randomkey(key) {
function xorkey (line 61) | function xorkey(key) {
function sm4_encode_cbc (line 69) | function sm4_encode_cbc(data, key) {
function bigxor (line 87) | function bigxor(a, b) {
function sm4_decode_cbc (line 100) | function sm4_decode_cbc(data, key) {
FILE: JavaScript/demo/js/x509-1.1.js
function X509 (line 42) | function X509() {
FILE: JavaScript/js/sm4.js
function bigxor (line 78) | function bigxor(a, b){
function leftshift (line 94) | function leftshift(a, n, size=32) {
function prefixInteger (line 99) | function prefixInteger(str, length) {
function sm4Sbox (line 116) | function sm4Sbox(a) {
function GET_ULONG_BE (line 124) | function GET_ULONG_BE (a) {
function PUT_ULONG_BE (line 129) | function PUT_ULONG_BE(b) {
function sm4_getkey (line 134) | function sm4_getkey (MK) {
function KJUR_encrypt_sm4 (line 149) | function KJUR_encrypt_sm4 (messsage, key, method="cbc") {
function KJUR_decrypt_sm4 (line 160) | function KJUR_decrypt_sm4 (ciphertext, key, method="cbc") {
FILE: JavaScript/sm2/js/base64.js
function hex2b64 (line 6) | function hex2b64(h) {
function b64tohex (line 27) | function b64tohex(s) {
function b64toBA (line 65) | function b64toBA(s) {
FILE: JavaScript/sm2/js/cipher-core.js
function selectCipherStrategy (line 181) | function selectCipherStrategy(key) {
function xorBlock (line 344) | function xorBlock(words, offset, blockSize) {
FILE: JavaScript/sm2/js/core.js
function F (line 25) | function F() {}
FILE: JavaScript/sm2/js/ec.js
function ECFieldElementFp (line 13) | function ECFieldElementFp(q,x) {
function feFpEquals (line 19) | function feFpEquals(other) {
function feFpToBigInteger (line 24) | function feFpToBigInteger() {
function feFpNegate (line 28) | function feFpNegate() {
function feFpAdd (line 32) | function feFpAdd(b) {
function feFpSubtract (line 36) | function feFpSubtract(b) {
function feFpMultiply (line 40) | function feFpMultiply(b) {
function feFpSquare (line 44) | function feFpSquare() {
function feFpDivide (line 48) | function feFpDivide(b) {
function ECPointFp (line 65) | function ECPointFp(curve,x,y,z) {
function pointFpGetX (line 81) | function pointFpGetX() {
function pointFpGetY (line 88) | function pointFpGetY() {
function pointFpEquals (line 95) | function pointFpEquals(other) {
function pointFpIsInfinity (line 108) | function pointFpIsInfinity() {
function pointFpNegate (line 113) | function pointFpNegate() {
function pointFpAdd (line 117) | function pointFpAdd(b) {
function pointFpTwice (line 154) | function pointFpTwice() {
function pointFpMultiply (line 185) | function pointFpMultiply(k) {
function pointFpMultiplyTwo (line 211) | function pointFpMultiplyTwo(j,x,k) {
function ECCurveFp (line 255) | function ECCurveFp(q,a,b) {
function curveFpGetQ (line 262) | function curveFpGetQ() {
function curveFpGetA (line 266) | function curveFpGetA() {
function curveFpGetB (line 270) | function curveFpGetB() {
function curveFpEquals (line 274) | function curveFpEquals(other) {
function curveFpGetInfinity (line 279) | function curveFpGetInfinity() {
function curveFpFromBigInteger (line 283) | function curveFpFromBigInteger(x) {
function curveFpDecodePointHex (line 288) | function curveFpDecodePointHex(s) {
FILE: JavaScript/sm2/js/ecdsa-modified-1.0.js
function implShamirsTrick (line 56) | function implShamirsTrick(P, k, Q, l) {
FILE: JavaScript/sm2/js/ecparam-1.0.js
function hex2bi (line 54) | function hex2bi(hex) {
FILE: JavaScript/sm2/js/jsbn.js
function BigInteger (line 17) | function BigInteger(a,b,c) {
function nbi (line 25) | function nbi() { return new BigInteger(null); }
function am1 (line 35) | function am1(i,x,w,j,c,n) {
function am2 (line 46) | function am2(i,x,w,j,c,n) {
function am3 (line 60) | function am3(i,x,w,j,c,n) {
function int2char (line 105) | function int2char(n) { return BI_RM.charAt(n); }
function intAt (line 106) | function intAt(s,i) {
function bnpCopyTo (line 112) | function bnpCopyTo(r) {
function bnpFromInt (line 119) | function bnpFromInt(x) {
function nbv (line 128) | function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
function bnpFromString (line 131) | function bnpFromString(s,b) {
function bnpClamp (line 170) | function bnpClamp() {
function bnToString (line 176) | function bnToString(b) {
function bnNegate (line 206) | function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); retu...
function bnAbs (line 209) | function bnAbs() { return (this.s<0)?this.negate():this; }
function bnCompareTo (line 212) | function bnCompareTo(a) {
function nbits (line 223) | function nbits(x) {
function bnBitLength (line 234) | function bnBitLength() {
function bnpDLShiftTo (line 240) | function bnpDLShiftTo(n,r) {
function bnpDRShiftTo (line 249) | function bnpDRShiftTo(n,r) {
function bnpLShiftTo (line 256) | function bnpLShiftTo(n,r) {
function bnpRShiftTo (line 273) | function bnpRShiftTo(n,r) {
function bnpSubTo (line 291) | function bnpSubTo(a,r) {
function bnpMultiplyTo (line 325) | function bnpMultiplyTo(a,r) {
function bnpSquareTo (line 337) | function bnpSquareTo(r) {
function bnpDivRemTo (line 355) | function bnpDivRemTo(m,q,r) {
function bnMod (line 403) | function bnMod(a) {
function Classic (line 411) | function Classic(m) { this.m = m; }
function cConvert (line 412) | function cConvert(x) {
function cRevert (line 416) | function cRevert(x) { return x; }
function cReduce (line 417) | function cReduce(x) { x.divRemTo(this.m,null,x); }
function cMulTo (line 418) | function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
function cSqrTo (line 419) | function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
function bnpInvDigit (line 437) | function bnpInvDigit() {
function Montgomery (line 453) | function Montgomery(m) {
function montConvert (line 463) | function montConvert(x) {
function montRevert (line 472) | function montRevert(x) {
function montReduce (line 480) | function montReduce(x) {
function montSqrTo (line 499) | function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
function montMulTo (line 502) | function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
function bnpIsEven (line 511) | function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
function bnpExp (line 514) | function bnpExp(e,z) {
function bnModPowInt (line 527) | function bnModPowInt(e,m) {
FILE: JavaScript/sm2/js/jsbn2.js
function bnClone (line 13) | function bnClone() { var r = nbi(); this.copyTo(r); return r; }
function bnIntValue (line 16) | function bnIntValue() {
function bnByteValue (line 28) | function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }
function bnShortValue (line 31) | function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
function bnpChunkSize (line 34) | function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r...
function bnSigNum (line 37) | function bnSigNum() {
function bnpToRadix (line 44) | function bnpToRadix(b) {
function bnpFromRadix (line 59) | function bnpFromRadix(s,b) {
function bnpFromNumber (line 86) | function bnpFromNumber(a,b,c) {
function bnToByteArray (line 112) | function bnToByteArray() {
function bnEquals (line 136) | function bnEquals(a) { return(this.compareTo(a)==0); }
function bnMin (line 137) | function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
function bnMax (line 138) | function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
function bnpBitwiseTo (line 141) | function bnpBitwiseTo(a,op,r) {
function op_and (line 159) | function op_and(x,y) { return x&y; }
function bnAnd (line 160) | function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
function op_or (line 163) | function op_or(x,y) { return x|y; }
function bnOr (line 164) | function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
function op_xor (line 167) | function op_xor(x,y) { return x^y; }
function bnXor (line 168) | function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
function op_andnot (line 171) | function op_andnot(x,y) { return x&~y; }
function bnAndNot (line 172) | function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); ret...
function bnNot (line 175) | function bnNot() {
function bnShiftLeft (line 184) | function bnShiftLeft(n) {
function bnShiftRight (line 191) | function bnShiftRight(n) {
function lbit (line 198) | function lbit(x) {
function bnGetLowestSetBit (line 210) | function bnGetLowestSetBit() {
function cbit (line 218) | function cbit(x) {
function bnBitCount (line 225) | function bnBitCount() {
function bnTestBit (line 232) | function bnTestBit(n) {
function bnpChangeBit (line 239) | function bnpChangeBit(n,op) {
function bnSetBit (line 246) | function bnSetBit(n) { return this.changeBit(n,op_or); }
function bnClearBit (line 249) | function bnClearBit(n) { return this.changeBit(n,op_andnot); }
function bnFlipBit (line 252) | function bnFlipBit(n) { return this.changeBit(n,op_xor); }
function bnpAddTo (line 255) | function bnpAddTo(a,r) {
function bnAdd (line 288) | function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
function bnSubtract (line 291) | function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
function bnMultiply (line 294) | function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
function bnSquare (line 297) | function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
function bnDivide (line 300) | function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
function bnRemainder (line 303) | function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return...
function bnDivideAndRemainder (line 306) | function bnDivideAndRemainder(a) {
function bnpDMultiply (line 313) | function bnpDMultiply(n) {
function bnpDAddOffset (line 320) | function bnpDAddOffset(n,w) {
function NullExp (line 332) | function NullExp() {}
function nNop (line 333) | function nNop(x) { return x; }
function nMulTo (line 334) | function nMulTo(x,y,r) { x.multiplyTo(y,r); }
function nSqrTo (line 335) | function nSqrTo(x,r) { x.squareTo(r); }
function bnPow (line 343) | function bnPow(e) { return this.exp(e,new NullExp()); }
function bnpMultiplyLowerTo (line 347) | function bnpMultiplyLowerTo(a,n,r) {
function bnpMultiplyUpperTo (line 360) | function bnpMultiplyUpperTo(a,n,r) {
function Barrett (line 372) | function Barrett(m) {
function barrettConvert (line 381) | function barrettConvert(x) {
function barrettRevert (line 387) | function barrettRevert(x) { return x; }
function barrettReduce (line 390) | function barrettReduce(x) {
function barrettSqrTo (line 401) | function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
function barrettMulTo (line 404) | function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
function bnModPow (line 413) | function bnModPow(e,m) {
function bnGCD (line 472) | function bnGCD(a) {
function bnpModInt (line 500) | function bnpModInt(n) {
function bnModInverse (line 510) | function bnModInverse(m) {
function bnIsProbablePrime (line 555) | function bnIsProbablePrime(t) {
function bnpMillerRabin (line 574) | function bnpMillerRabin(t) {
FILE: JavaScript/sm2/js/md5.js
function FF (line 203) | function FF(a, b, c, d, x, s, t) {
function GG (line 208) | function GG(a, b, c, d, x, s, t) {
function HH (line 213) | function HH(a, b, c, d, x, s, t) {
function II (line 218) | function II(a, b, c, d, x, s, t) {
FILE: JavaScript/sm2/js/prng4.js
function Arcfour (line 5) | function Arcfour() {
function ARC4init (line 12) | function ARC4init(key) {
function ARC4next (line 27) | function ARC4next() {
function prng_newstate (line 41) | function prng_newstate() {
FILE: JavaScript/sm2/js/rng.js
function rng_seed_int (line 14) | function rng_seed_int(x) {
function rng_seed_time (line 23) | function rng_seed_time() {
function rng_get_byte (line 49) | function rng_get_byte() {
function rng_get_bytes (line 63) | function rng_get_bytes(ba) {
function SecureRandom (line 68) | function SecureRandom() {}
FILE: JavaScript/sm2/js/rsa.js
function parseBigInt (line 8) | function parseBigInt(str,r) {
function linebrk (line 12) | function linebrk(s,n) {
function byte2Hex (line 22) | function byte2Hex(b) {
function pkcs1pad2 (line 30) | function pkcs1pad2(s,n) {
function oaep_mgf1_arr (line 66) | function oaep_mgf1_arr(seed, len, hash)
function oaep_pad (line 86) | function oaep_pad(s, n, hash)
function RSAKey (line 124) | function RSAKey() {
function RSASetPublic (line 136) | function RSASetPublic(N,E) {
function RSADoPublic (line 152) | function RSADoPublic(x) {
function RSAEncrypt (line 157) | function RSAEncrypt(text) {
function RSAEncryptOAEP (line 167) | function RSAEncryptOAEP(text, hash) {
FILE: JavaScript/sm2/js/rsa2.js
function pkcs1unpad2 (line 8) | function pkcs1unpad2(d,n) {
function oaep_mgf1_str (line 36) | function oaep_mgf1_str(seed, len, hash)
function oaep_unpad (line 56) | function oaep_unpad(d, n, hash)
function RSASetPrivate (line 121) | function RSASetPrivate(N,E,D) {
function RSASetPrivateEx (line 139) | function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
function RSAGenerate (line 161) | function RSAGenerate(B,E) {
function RSADoPrivate (line 195) | function RSADoPrivate(x) {
function RSADecrypt (line 214) | function RSADecrypt(ctext) {
function RSADecryptOAEP (line 223) | function RSADecryptOAEP(ctext, hash) {
FILE: JavaScript/sm2/js/rsapem-1.1.js
function _rsapem_pemToBase64 (line 35) | function _rsapem_pemToBase64(sPEMPrivateKey) {
function _rsapem_getPosArrayOfChildrenFromHex (line 43) | function _rsapem_getPosArrayOfChildrenFromHex(hPrivateKey) {
function _rsapem_getHexValueArrayOfChildrenFromHex (line 58) | function _rsapem_getHexValueArrayOfChildrenFromHex(hPrivateKey) {
function _rsapem_readPrivateKeyFromASN1HexString (line 82) | function _rsapem_readPrivateKeyFromASN1HexString(keyHex) {
function _rsapem_readPrivateKeyFromPEMString (line 94) | function _rsapem_readPrivateKeyFromPEMString(keyPEM) {
FILE: JavaScript/sm2/js/rsasign-1.2.js
function _rsasign_getHexPaddedDigestInfoForString (line 32) | function _rsasign_getHexPaddedDigestInfoForString(s, keySize, hashAlg) {
function _zeroPaddingOfSignature (line 39) | function _zeroPaddingOfSignature(hex, bitLength) {
function _rsasign_signString (line 57) | function _rsasign_signString(s, hashAlg) {
function _rsasign_signWithMessageHash (line 74) | function _rsasign_signWithMessageHash(sHashHex, hashAlg) {
function _rsasign_signStringWithSHA1 (line 82) | function _rsasign_signStringWithSHA1(s) {
function _rsasign_signStringWithSHA256 (line 86) | function _rsasign_signStringWithSHA256(s) {
function pss_mgf1_str (line 91) | function pss_mgf1_str(seed, len, hash) {
function _rsasign_signStringPSS (line 123) | function _rsasign_signStringPSS(s, hashAlg, sLen) {
function _rsasign_signWithMessageHashPSS (line 149) | function _rsasign_signWithMessageHashPSS(hHash, hashAlg, sLen) {
function _rsasign_getDecryptSignatureBI (line 209) | function _rsasign_getDecryptSignatureBI(biSig, hN, hE) {
function _rsasign_getHexDigestInfoFromSig (line 216) | function _rsasign_getHexDigestInfoFromSig(biSig, hN, hE) {
function _rsasign_getAlgNameAndHashFromHexDisgestInfo (line 222) | function _rsasign_getAlgNameAndHashFromHexDisgestInfo(hDigestInfo) {
function _rsasign_verifySignatureWithArgs (line 234) | function _rsasign_verifySignatureWithArgs(sMsg, biSig, hN, hE) {
function _rsasign_verifyHexSignatureForMessage (line 245) | function _rsasign_verifyHexSignatureForMessage(hSig, sMsg) {
function _rsasign_verifyString (line 263) | function _rsasign_verifyString(sMsg, hSig) {
function _rsasign_verifyWithMessageHash (line 291) | function _rsasign_verifyWithMessageHash(sHashHex, hSig) {
function _rsasign_verifyStringPSS (line 324) | function _rsasign_verifyStringPSS(sMsg, hSig, hashAlg, sLen) {
function _rsasign_verifyWithMessageHashPSS (line 351) | function _rsasign_verifyWithMessageHashPSS(hHash, hSig, hashAlg, sLen) {
FILE: JavaScript/sm2/js/sha256.js
function isPrime (line 21) | function isPrime(n) {
function getFractionalBits (line 32) | function getFractionalBits(n) {
FILE: JavaScript/sm2/js/sm2-guomi.js
function SM2Cipher (line 1) | function SM2Cipher(cipherMode) {
FILE: JavaScript/sm2/js/sm2.js
function SM2Cipher (line 1) | function SM2Cipher(cipherMode){this.ct=1;this.p2=null;this.sm3keybase=nu...
FILE: JavaScript/sm2/js/sm3-guomi.js
function SM3Digest (line 70) | function SM3Digest() {
FILE: JavaScript/sm2/js/sm3-sm2-1.0.js
function implShamirsTrick (line 50) | function implShamirsTrick(P, k, Q, l) {
FILE: JavaScript/sm2/js/sm3.js
function SM3Digest (line 1) | function SM3Digest(){this.BYTE_LENGTH=64;this.xBuf=new Array();this.xBuf...
FILE: JavaScript/sm2/js/tripledes.js
function exchangeLR (line 691) | function exchangeLR(offset, mask) {
function exchangeRL (line 697) | function exchangeRL(offset, mask) {
FILE: JavaScript/sm2/js/x509-1.1.js
function X509 (line 42) | function X509() {
FILE: Python/sm4.py
function leftshift (line 47) | def leftshift(a, n, size=32):
function PUT_ULONG_BE (line 51) | def PUT_ULONG_BE(b):
function GET_ULONG_BE (line 55) | def GET_ULONG_BE(b):
function sm4Sbox (line 70) | def sm4Sbox(a):
function generate_key (line 77) | def generate_key(MK):
function sm4_encrypt (line 91) | def sm4_encrypt(message, key, method='cbc'):
function sm4_decrypt (line 103) | def sm4_decrypt(crphertext, key, method='cbc'):
Condensed preview — 96 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,256K chars).
[
{
"path": "C/SM2_SM3_SM4_C语言实现/SM2/kdf.h",
"chars": 1301,
"preview": "\n#include <memory.h>\n#include <openssl/evp.h>\n\n// ----- KDF FUNCTIONS START -----\n//typedef void *(*KDF)(const void *in,"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM2/sm2.c",
"chars": 18385,
"preview": "// \\file:sm2.c\n//SM2 Algorithm\n//2011-11-10\n//author:goldboar\n//email:goldboar@163.com\n//depending:opnessl library\n\n//SM"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM2/sm2.dsp",
"chars": 3445,
"preview": "# Microsoft Developer Studio Project File - Name=\"sm2\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build "
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM2/sm2.dsw",
"chars": 500,
"preview": "Microsoft Developer Studio Workspace File, Format Version 6.00\n# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\n\n##"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM2/sm2.h",
"chars": 884,
"preview": "// \\file:sm2.h\n//SM2 Algorithm\n//2011-11-09\n//author:goldboar\n//email:goldboar@163.com\n//comment:2011-11-10 sm2-sign-ver"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM2/sm2test.c",
"chars": 13112,
"preview": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <openssl/bn.h>\n#include <openssl/e"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM3/sm3.c",
"chars": 10157,
"preview": "/*\n * SM3 Hash alogrith \n * thanks to Xyssl\n * author:goldboar\n * email:goldboar@163.com\n * 2011-10-26\n */\n\n//Testing da"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM3/sm3.h",
"chars": 2897,
"preview": "/**\n * \\file sm3.h\n * thanks to Xyssl\n * SM3 standards:http://www.oscca.gov.cn/News/201012/News_1199.htm\n * author:goldb"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM3/sm3test.c",
"chars": 802,
"preview": "\n#include <string.h>\n#include <stdio.h>\n#include \"sm3.h\"\n\nint main( int argc, char *argv[] )\n{\n\tunsigned char *input = \""
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM3/sm3test.dsp",
"chars": 3483,
"preview": "# Microsoft Developer Studio Project File - Name=\"sm3test\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Bu"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM3/sm3test.dsw",
"chars": 510,
"preview": "Microsoft Developer Studio Workspace File, Format Version 6.00\n# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\n\n##"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM4/sm4.c",
"chars": 10356,
"preview": "/*\n * SM4 Encryption alogrithm (SMS4 algorithm)\n * GM/T 0002-2012 Chinese National Standard ref:http://www.oscca.gov.cn/"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM4/sm4.dsp",
"chars": 3387,
"preview": "# Microsoft Developer Studio Project File - Name=\"sm4\" - Package Owner=<4>\n# Microsoft Developer Studio Generated Build "
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM4/sm4.dsw",
"chars": 500,
"preview": "Microsoft Developer Studio Workspace File, Format Version 6.00\n# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\n\n##"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM4/sm4.h",
"chars": 1839,
"preview": "/**\n * \\file sm4.h\n */\n#ifndef XYSSL_SM4_H\n#define XYSSL_SM4_H\n\n#define SM4_ENCRYPT 1\n#define SM4_DECRYPT 0\n\n/**"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM4/sm4test.c",
"chars": 979,
"preview": "/*\n * SM4/SMS4 algorithm test programme\n * 2012-4-21\n */\n\n#include <string.h>\n#include <stdio.h>\n#include \"sm4.h\"\n\nint m"
},
{
"path": "C/SM2_SM3_SM4_C语言实现/SM4/sms4.c",
"chars": 11846,
"preview": "/* sms4.c\n** SMS4 Encryption algorithm for wireless networks\n**\n** $Id: sms4.c 2009-12-31 14:41:57 tao.tang <$\">emhmily@"
},
{
"path": "C/sm4.c",
"chars": 13255,
"preview": "/*\n * SM4 Encryption alogrithm (SMS4 algorithm)\n * GM/T 0002-2012 Chinese National Standard ref:http://www.oscca.gov.cn/"
},
{
"path": "Java/JavaSM4.java",
"chars": 5819,
"preview": "public class JavaSM4 {\n \n public static int[] key = new int[4];\n public static int[] temp = new int[4];\n"
},
{
"path": "JavaScript/demo/js/asn1-1.0.js",
"chars": 42237,
"preview": "/*! asn1-1.0.4.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * asn1.js - ASN.1 DER encoder clas"
},
{
"path": "JavaScript/demo/js/asn1hex-1.1.js",
"chars": 9646,
"preview": "/*! asn1hex-1.1.4.js (c) 2012-2013 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * asn1hex.js - Hexadecimal"
},
{
"path": "JavaScript/demo/js/asn1x509-1.0.js",
"chars": 59784,
"preview": "/*! asn1x509-1.0.7.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * asn1x509.js - ASN.1 DER enco"
},
{
"path": "JavaScript/demo/js/base64.js",
"chars": 1713,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\nvar b64map=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn"
},
{
"path": "JavaScript/demo/js/cipher-core.js",
"chars": 29182,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/demo/js/core.js",
"chars": 21468,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/demo/js/crypto-1.1.js",
"chars": 40519,
"preview": "/*! crypto-1.1.5.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license\r\n */\r\n/*\r\n * crypto.js - Cryptographic A"
},
{
"path": "JavaScript/demo/js/ec-patch.js",
"chars": 5774,
"preview": "/*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib\r\n */\r\n/*\r\n * splitted from bitcoin-lib/ecdsa.js\r\n *\r\n"
},
{
"path": "JavaScript/demo/js/ec.js",
"chars": 9126,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Basic Javascript Elliptic Curve implementation\n//"
},
{
"path": "JavaScript/demo/js/ecdsa-modified-1.0.js",
"chars": 18227,
"preview": "/*! ecdsa-modified-1.0.4.js (c) Stephan Thomas, Kenji Urushima | github.com/bitcoinjs/bitcoinjs-lib/blob/master/LICENSE\n"
},
{
"path": "JavaScript/demo/js/ecparam-1.0.js",
"chars": 10440,
"preview": "/*! ecparam-1.0.0.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license\r\n */\r\n/*\r\n * ecparam.js - Elliptic Curv"
},
{
"path": "JavaScript/demo/js/enc-base64.js",
"chars": 3338,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/demo/js/fingerprint.js",
"chars": 9885,
"preview": "/*\n* fingerprintJS 0.5.4 - Fast browser fingerprint library\n* https://github.com/Valve/fingerprintjs\n* Copyright (c) 201"
},
{
"path": "JavaScript/demo/js/fingerprint2.js",
"chars": 62010,
"preview": "/*\r\n* Fingerprintjs2 1.4.2 - Modern & flexible browser fingerprint library v2\r\n* https://github.com/Valve/fingerprintjs2"
},
{
"path": "JavaScript/demo/js/jsbn.js",
"chars": 15248,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Copyright (c) 2005 Tom Wu\n// All Rights Reserved"
},
{
"path": "JavaScript/demo/js/jsbn2.js",
"chars": 18651,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Copyright (c) 2005-2009 Tom Wu\n// All Rights Res"
},
{
"path": "JavaScript/demo/js/md5.js",
"chars": 9232,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/demo/js/pkcs5pkey-1.0.js",
"chars": 44748,
"preview": "/*! pkcs5pkey-1.0.5.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * pkcs5pkey.js - reading pass"
},
{
"path": "JavaScript/demo/js/prng4.js",
"chars": 1077,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// prng4.js - uses Arcfour as a PRNG\n\nfunction Arcfo"
},
{
"path": "JavaScript/demo/js/rng.js",
"chars": 1951,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Random number generator - requires a PRNG backend"
},
{
"path": "JavaScript/demo/js/rsa.js",
"chars": 4594,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Depends on jsbn.js and rng.js\n\n// Version 1.1: su"
},
{
"path": "JavaScript/demo/js/rsa2.js",
"chars": 7018,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Depends on rsa.js and jsbn2.js\n\n// Version 1.1: s"
},
{
"path": "JavaScript/demo/js/rsapem-1.1.js",
"chars": 3680,
"preview": "/*! rsapem-1.1.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n//\n// rsa-pem.js - adding function for"
},
{
"path": "JavaScript/demo/js/rsasign-1.2.js",
"chars": 15686,
"preview": "/*! rsasign-1.2.7.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * rsa-sign.js - adding signing "
},
{
"path": "JavaScript/demo/js/sha1.js",
"chars": 3862,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/demo/js/sha256.js",
"chars": 5346,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/demo/js/sm2-guomi.js",
"chars": 5478,
"preview": "function SM2Cipher(cipherMode) {\r\n this.ct = 1;\r\n this.p2 = null;\r\n this.sm3keybase = null;\r\n this.sm3c3 = n"
},
{
"path": "JavaScript/demo/js/sm2.js",
"chars": 3806,
"preview": "function SM2Cipher(cipherMode){this.ct=1;this.p2=null;this.sm3keybase=null;this.sm3c3=null;this.key=new Array(32);this.k"
},
{
"path": "JavaScript/demo/js/sm3-guomi.js",
"chars": 15311,
"preview": "(function() {\r\n var C = CryptoJS;\r\n var C_lib = C.lib;\r\n var WordArray = C_lib.WordArray;\r\n var Hasher = C_l"
},
{
"path": "JavaScript/demo/js/sm3-sm2-1.0.js",
"chars": 10498,
"preview": "/*! sm3-sm2-1.0.js (c) Jonllen Peng | http://www.jonllen.com/\r\n */\r\n/*\r\n * sm3-sm2-1.0.js\r\n * \r\n * Copyright (c) 2014 Jo"
},
{
"path": "JavaScript/demo/js/sm3.js",
"chars": 9825,
"preview": "(function(){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var Hasher=C_lib.Hasher;var C_algo=C.algo;var W"
},
{
"path": "JavaScript/demo/js/sm4.js",
"chars": 6728,
"preview": "/*! sm4-1.0.js (c) Windard Yang | https://www.windard.com/\r\n */\r\n/*\r\n * sm4-1.0.js\r\n * \r\n * Copyright (c) 2014 Windard Y"
},
{
"path": "JavaScript/demo/js/tripledes.js",
"chars": 23977,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/demo/js/utils.js",
"chars": 3351,
"preview": "/*! utils-1.0.js (c) Windard Yang | https://www.windard.com/\n */\n/*\n * utils-1.0.js\n * \n * Copyright (c) 2014 Windard Ya"
},
{
"path": "JavaScript/demo/js/x509-1.1.js",
"chars": 11694,
"preview": "/*! x509-1.1.2.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/* \n * x509.js - X509 class to read su"
},
{
"path": "JavaScript/demo/js/yahoo-min.js",
"chars": 7083,
"preview": "/*\nCopyright (c) 2011, Yahoo! Inc. All rights reserved.\nCode licensed under the BSD License:\nhttp://developer.yahoo.com/"
},
{
"path": "JavaScript/demo/performance.html",
"chars": 5204,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>国密算法实现</title>\n <!-- for pkcs5pkey -->\n"
},
{
"path": "JavaScript/des/JavaScript DES Example.html",
"chars": 23626,
"preview": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<!-- saved from url=(0048)http://people.eku.edu/styere/E"
},
{
"path": "JavaScript/js/sm4.js",
"chars": 6669,
"preview": "/*! sm4-1.0.js (c) Windard Yang | https://www.windard.com/\n */\n/*\n * sm4-1.0.js\n * \n * Copyright (c) 2014 Windard Yang ("
},
{
"path": "JavaScript/sm2/js/asn1-1.0.js",
"chars": 42237,
"preview": "/*! asn1-1.0.4.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * asn1.js - ASN.1 DER encoder clas"
},
{
"path": "JavaScript/sm2/js/asn1hex-1.1.js",
"chars": 9646,
"preview": "/*! asn1hex-1.1.4.js (c) 2012-2013 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * asn1hex.js - Hexadecimal"
},
{
"path": "JavaScript/sm2/js/asn1x509-1.0.js",
"chars": 59784,
"preview": "/*! asn1x509-1.0.7.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * asn1x509.js - ASN.1 DER enco"
},
{
"path": "JavaScript/sm2/js/base64.js",
"chars": 1713,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\nvar b64map=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn"
},
{
"path": "JavaScript/sm2/js/cipher-core.js",
"chars": 28325,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/sm2/js/core.js",
"chars": 20762,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/sm2/js/crypto-1.1.js",
"chars": 39313,
"preview": "/*! crypto-1.1.5.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * crypto.js - Cryptographic Algo"
},
{
"path": "JavaScript/sm2/js/ec-patch.js",
"chars": 5565,
"preview": "/*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib\n */\n/*\n * splitted from bitcoin-lib/ecdsa.js\n *\n * ve"
},
{
"path": "JavaScript/sm2/js/ec.js",
"chars": 9126,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Basic Javascript Elliptic Curve implementation\n//"
},
{
"path": "JavaScript/sm2/js/ecdsa-modified-1.0.js",
"chars": 18227,
"preview": "/*! ecdsa-modified-1.0.4.js (c) Stephan Thomas, Kenji Urushima | github.com/bitcoinjs/bitcoinjs-lib/blob/master/LICENSE\n"
},
{
"path": "JavaScript/sm2/js/ecparam-1.0.js",
"chars": 10181,
"preview": "/*! ecparam-1.0.0.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * ecparam.js - Elliptic Curve C"
},
{
"path": "JavaScript/sm2/js/enc-base64.js",
"chars": 3338,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/sm2/js/fingerprint.js",
"chars": 9885,
"preview": "/*\n* fingerprintJS 0.5.4 - Fast browser fingerprint library\n* https://github.com/Valve/fingerprintjs\n* Copyright (c) 201"
},
{
"path": "JavaScript/sm2/js/jsbn.js",
"chars": 15248,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Copyright (c) 2005 Tom Wu\n// All Rights Reserved"
},
{
"path": "JavaScript/sm2/js/jsbn2.js",
"chars": 18651,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Copyright (c) 2005-2009 Tom Wu\n// All Rights Res"
},
{
"path": "JavaScript/sm2/js/md5.js",
"chars": 8984,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/sm2/js/pkcs5pkey-1.0.js",
"chars": 44748,
"preview": "/*! pkcs5pkey-1.0.5.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * pkcs5pkey.js - reading pass"
},
{
"path": "JavaScript/sm2/js/prng4.js",
"chars": 1077,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// prng4.js - uses Arcfour as a PRNG\n\nfunction Arcfo"
},
{
"path": "JavaScript/sm2/js/rng.js",
"chars": 1951,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Random number generator - requires a PRNG backend"
},
{
"path": "JavaScript/sm2/js/rsa.js",
"chars": 4594,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Depends on jsbn.js and rng.js\n\n// Version 1.1: su"
},
{
"path": "JavaScript/sm2/js/rsa2.js",
"chars": 7018,
"preview": "/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/\n */\n// Depends on rsa.js and jsbn2.js\n\n// Version 1.1: s"
},
{
"path": "JavaScript/sm2/js/rsapem-1.1.js",
"chars": 3680,
"preview": "/*! rsapem-1.1.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n//\n// rsa-pem.js - adding function for"
},
{
"path": "JavaScript/sm2/js/rsasign-1.2.js",
"chars": 15686,
"preview": "/*! rsasign-1.2.7.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/*\n * rsa-sign.js - adding signing "
},
{
"path": "JavaScript/sm2/js/sha1.js",
"chars": 3732,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/sm2/js/sha256.js",
"chars": 5167,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/sm2/js/sm2-guomi.js",
"chars": 5332,
"preview": "function SM2Cipher(cipherMode) {\n this.ct = 1;\n this.p2 = null;\n this.sm3keybase = null;\n this.sm3c3 = null;"
},
{
"path": "JavaScript/sm2/js/sm2.js",
"chars": 3806,
"preview": "function SM2Cipher(cipherMode){this.ct=1;this.p2=null;this.sm3keybase=null;this.sm3c3=null;this.key=new Array(32);this.k"
},
{
"path": "JavaScript/sm2/js/sm3-guomi.js",
"chars": 14913,
"preview": "(function() {\n var C = CryptoJS;\n var C_lib = C.lib;\n var WordArray = C_lib.WordArray;\n var Hasher = C_lib.H"
},
{
"path": "JavaScript/sm2/js/sm3-sm2-1.0.js",
"chars": 10125,
"preview": "/*! sm3-sm2-1.0.js (c) Jonllen Peng | http://www.jonllen.com/\n */\n/*\n * sm3-sm2-1.0.js\n * \n * Copyright (c) 2014 Jonllen"
},
{
"path": "JavaScript/sm2/js/sm3.js",
"chars": 9825,
"preview": "(function(){var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var Hasher=C_lib.Hasher;var C_algo=C.algo;var W"
},
{
"path": "JavaScript/sm2/js/tripledes.js",
"chars": 23227,
"preview": "/*\nCryptoJS v3.1.2\ncode.google.com/p/crypto-js\n(c) 2009-2013 by Jeff Mott. All rights reserved.\ncode.google.com/p/crypto"
},
{
"path": "JavaScript/sm2/js/x509-1.1.js",
"chars": 11694,
"preview": "/*! x509-1.1.2.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license\n */\n/* \n * x509.js - X509 class to read su"
},
{
"path": "JavaScript/sm2/js/yahoo-min.js",
"chars": 7083,
"preview": "/*\nCopyright (c) 2011, Yahoo! Inc. All rights reserved.\nCode licensed under the BSD License:\nhttp://developer.yahoo.com/"
},
{
"path": "JavaScript/sm2/sm2.html",
"chars": 5599,
"preview": "<!DOCTYPE html>\n<!-- saved from url=(0075)http://www.jonllen.com/upload/jonllen/case/jsrsasign-master/sample-sm2.html --"
},
{
"path": "JavaScript/sm2/sm2_decrypt.html",
"chars": 8952,
"preview": "<!DOCTYPE html>\n<!-- saved from url=(0081)http://www.jonllen.com/upload/jonllen/case/jsrsasign-master/sample-sm2_crypt.h"
},
{
"path": "JavaScript/sm4.html",
"chars": 1118,
"preview": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n<head>\n <meta charset=\"UTF-8\">\n <title>SM4 国密算法实现</title>\n\n <!-- sm4 -->\n "
},
{
"path": "Python/sm4.py",
"chars": 4412,
"preview": "# coding=utf-8\n# time:2016-11-20\n# author:windard\n\nimport time\n\nSboxTable = [\n[0xd6,0x90,0xe9,0xfe,0xcc,0xe1,0x3d,0xb7,0"
},
{
"path": "README.md",
"chars": 3731,
"preview": "\n## 国密算法\n\n因最近一个项目需要用到国密算法,所以在网上找了一下国密算法的相关资料。国密算法并不是特指一种算法,而是指国家密码局认定的国产密码算法。它包括 SM2,SM3,SM4 祖冲之算法等一系列算法,可以参考~~[这篇公告](ht"
}
]
About this extraction
This page contains the full source code of the windard/sm4 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 96 files (1.1 MB), approximately 380.9k tokens, and a symbol index with 527 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.