add gmapi impls

This commit is contained in:
Zhi Guan
2017-02-15 17:49:21 +08:00
parent 5eedfacd04
commit 99f331039d
67 changed files with 11434 additions and 2 deletions

4
crypto/saf/build.info Normal file
View File

@@ -0,0 +1,4 @@
LIBS=../../libcrypto
SOURCE[../../libcrypto]=saf_lib.c saf_errstr.c saf_app.c saf_keyhandle.c \
saf_ec.c saf_sm2.c saf_rand.c saf_hash.c saf_enc.c saf_mac.c saf_symmkeyobj.c \
saf_base64.c saf_cert.c saf_err.c

133
crypto/saf/saf_app.c Normal file
View File

@@ -0,0 +1,133 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
/*
* the software implementation of SAF application and related storage
* is determined by a standard OpenSSL configuration file `openssl.cnf`.
* If no config file is given, the default openssl config file will be
* used. This means that the SAF API is only a wrapper of the EVP API.
*
* The OpenSSL use file-level access control, i.e. private keys are
* encrypted by passwords, there is no default container-level access
* control mechnsims such as the Java Keytool for the application-level
* access control of SAF API.
*
* We use the AppHandle to preserve the CONF object.
*
* So we dont provide such access control. The Login() will always
* success. And the ChangePin() has no effects.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/gmsaf.h>
/* 7.1.2 */
int SAF_Initialize(
void **phAppHandle,
char *pubCfgFilePath)
{
return SAR_Ok;
}
/* 7.1.3 */
int SAF_Finalize(
void *hAppHandle)
{
return SAR_Ok;
}
/* 7.1.4 */
int SAF_GetVersion(
unsigned int *puiVersion)
{
*puiVersion = 0x01000000;
return SAR_Ok;
}
/* 7.1.5 */
int SAF_Login(
void *hAppHandle,
unsigned int uiUsrType,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned char *pucPin,
unsigned int uiPinLen,
unsigned int *puiRemainCount)
{
*puiRemainCount = 100;
return SAR_Ok;
}
/* 7.1.6 */
int SAF_ChangePin(
void *hAppHandle,
unsigned int uiUsrType,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned char *pucOldPin,
unsigned int uiOldPinLen,
unsigned char *pucNewPin,
unsigned int uiNewPinLen,
unsigned int *puiRemainCount)
{
*puiRemainCount = 100;
return SAR_Ok;
}
/* 7.1.7 */
int SAF_Logout(
void *hAppHandle,
unsigned int uiUsrType)
{
return SAR_Ok;
}

412
crypto/saf/saf_base64.c Normal file
View File

@@ -0,0 +1,412 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/gmsaf.h>
#include <openssl/gmapi.h>
#include "saf_lcl.h"
/* 7.3.4 */
int SAF_Base64_CreateBase64Obj(
void **phBase64Obj)
{
int ret = SAR_UnknownErr;
SAF_BASE64OBJ *obj = NULL;
if (!(obj = OPENSSL_malloc(sizeof(*obj)))) {
SAFerr(SAF_F_SAF_BASE64_CREATEBASE64OBJ, ERR_R_MALLOC_FAILURE);
return SAR_MemoryErr;
}
if (!(obj->ctx = EVP_ENCODE_CTX_new())) {
SAFerr(SAF_F_SAF_BASE64_CREATEBASE64OBJ, ERR_R_MALLOC_FAILURE);
ret = SAR_MemoryErr;
goto end;
}
obj->inited = 0;
*phBase64Obj = obj;
ret = SAR_OK;
end:
if (ret != SAR_OK) {
EVP_ENCODE_CTX_free(obj->ctx);
OPENSSL_free(obj);
}
return ret;
}
/* 7.3.5 */
/* always return success for software implementation */
int SAF_Base64_DestroyBase64Obj(
void *hBase64Obj)
{
SAF_BASE64OBJ *obj = (SAF_BASE64OBJ *)hBase64Obj;
if (obj) {
EVP_ENCODE_CTX_free(obj->ctx);
}
OPENSSL_free(obj);
return SAR_OK;
}
/* 7.3.6 */
int SAF_Base64_EncodeUpdate(
void *hBase64Obj,
unsigned char *pucInData,
unsigned int puiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
SAF_BASE64OBJ *obj = (SAF_BASE64OBJ *)hBase64Obj;
int inlen, outlen;
if (!hBase64Obj || !pucInData || !pucOutData || !puiOutDataLen) {
SAFerr(SAF_F_SAF_BASE64_ENCODEUPDATE, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
/* GMAPI dont check function specific length, leave to EVP */
if (puiInDataLen > INT_MAX) {
SAFerr(SAF_F_SAF_BASE64_ENCODEUPDATE, SAF_R_INT_OVERFLOW);
return SAR_IndataLenErr;
}
/* GMAPI dont check function specific length, leave to EVP */
if (*puiOutDataLen > INT_MAX) {
SAFerr(SAF_F_SAF_BASE64_ENCODEUPDATE, SAF_R_INT_OVERFLOW);
return SAR_IndataLenErr;
}
/* check handle */
if (!obj->ctx) {
SAFerr(SAF_F_SAF_BASE64_ENCODEUPDATE, SAF_R_INVALID_HANDLE);
return SAR_ObjErr;
}
if (!obj->inited) {
EVP_EncodeInit(obj->ctx);
obj->inited = 1;
}
inlen = (int)puiInDataLen;
outlen = (int)(*puiOutDataLen);
//TODO: check outlen, or EVP will fail without error messages
if (!EVP_EncodeUpdate(obj->ctx, pucOutData, &outlen, pucInData, inlen)) {
SAFerr(SAF_F_SAF_BASE64_ENCODEUPDATE, ERR_R_EVP_LIB);
return SAR_UnknownErr;
}
*puiOutDataLen = (unsigned int)outlen;
return SAR_OK;
}
/* 7.3.7 */
int SAF_Base64_EncodeFinal(
void *hBase64Obj,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
SAF_BASE64OBJ *obj = (SAF_BASE64OBJ *)hBase64Obj;
int len;
if (!hBase64Obj || !pucOutData || !puiOutDataLen) {
SAFerr(SAF_F_SAF_BASE64_ENCODEFINAL, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (*puiOutDataLen > INT_MAX) {
SAFerr(SAF_F_SAF_BASE64_ENCODEFINAL, SAF_R_INT_OVERFLOW);
return SAR_IndataLenErr;
}
if (*puiOutDataLen < 66) {
SAFerr(SAF_F_SAF_BASE64_ENCODEFINAL, SAF_R_BUFFER_TOO_SMALL);
return SAR_IndataLenErr;
}
if (!obj->ctx || !obj->inited) {
SAFerr(SAF_F_SAF_BASE64_ENCODEFINAL, SAF_R_INVALID_HANDLE);
return SAR_ObjErr;
}
/* the max output length of EVP_EncodeFinal() is 66
* this function return void, so we need to check `*outlen`
*/
len = (int)(*puiOutDataLen);
//TODO: check outlen, or EVP will fail without error messages
EVP_EncodeFinal(obj->ctx, pucOutData, &len);
*puiOutDataLen = (unsigned int)len;
return SAR_OK;
}
/* 7.3.8 */
int SAF_Base64_DecodeUpdate(
void *hBase64Obj,
unsigned char *pucInData,
unsigned int puiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
SAF_BASE64OBJ *obj = (SAF_BASE64OBJ *)hBase64Obj;
int inlen, outlen;
if (!hBase64Obj || !pucInData || !pucOutData || !puiOutDataLen) {
SAFerr(SAF_F_SAF_BASE64_DECODEUPDATE, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
/* GMAPI dont check function specific length, leave to EVP */
if (puiInDataLen > INT_MAX) {
SAFerr(SAF_F_SAF_BASE64_DECODEUPDATE, SAF_R_INT_OVERFLOW);
return SAR_IndataLenErr;
}
/* GMAPI dont check function specific length, leave to EVP */
if (*puiOutDataLen > INT_MAX) {
SAFerr(SAF_F_SAF_BASE64_DECODEUPDATE, SAF_R_INT_OVERFLOW);
return SAR_IndataLenErr;
}
if (!obj->ctx) {
SAFerr(SAF_F_SAF_BASE64_DECODEUPDATE, SAF_R_INVALID_HANDLE);
return SAR_ObjErr;
}
if (!obj->inited) {
EVP_DecodeInit(obj->ctx);
obj->inited = 1;
}
inlen = (int)puiInDataLen;
outlen = (int)(*puiOutDataLen);
//TODO: check outlen, or EVP will fail without error messages
/*
* EVP_DecodeUpdate() return -1 for error, 0 or 1 for success
* 0 means the last char of the input is `=`
*/
if (EVP_DecodeUpdate(obj->ctx, pucOutData, &outlen, pucInData, inlen) < 0) {
SAFerr(SAF_F_SAF_BASE64_DECODEUPDATE, ERR_R_EVP_LIB);
return SAR_UnknownErr;
}
*puiOutDataLen = (unsigned int)outlen;
return SAR_OK;
}
/* 7.3.9 */
int SAF_Base64_DecodeFinal(
void *hBase64Obj,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
SAF_BASE64OBJ *obj = (SAF_BASE64OBJ *)hBase64Obj;
int len;
if (!hBase64Obj || !pucOutData || !puiOutDataLen) {
SAFerr(SAF_F_SAF_BASE64_DECODEFINAL, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (*puiOutDataLen > INT_MAX) {
SAFerr(SAF_F_SAF_BASE64_DECODEFINAL, SAF_R_INT_OVERFLOW);
return SAR_IndataLenErr;
}
if (!obj->ctx || !obj->inited) {
SAFerr(SAF_F_SAF_BASE64_DECODEFINAL, SAF_R_INVALID_HANDLE);
return SAR_ObjErr;
}
len = (int)(*puiOutDataLen);
//TODO: check outlen, or EVP will fail without error messages
if (!EVP_DecodeFinal(obj->ctx, pucOutData, &len)) {
SAFerr(SAF_F_SAF_BASE64_DECODEFINAL, ERR_R_EVP_LIB);
return SAR_UnknownErr;
}
*puiOutDataLen = (unsigned int)len;
return SAR_OK;
}
/* 7.3.2 */
int SAF_Base64_Encode(
unsigned char *pucInData,
unsigned int puiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
int ret = SAR_UnknownErr;
void *handle = NULL;
unsigned char *p;
unsigned int len;
if (!pucInData || !pucOutData || !puiOutDataLen) {
SAFerr(SAF_F_SAF_BASE64_ENCODE, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if ((ret = SAF_Base64_CreateBase64Obj(&handle)) != SAR_OK) {
SAFerr(SAF_F_SAF_BASE64_ENCODE, ERR_R_GMAPI_LIB);
goto end;
}
p = pucOutData;
len = *puiOutDataLen;
if ((ret = SAF_Base64_EncodeUpdate(handle, pucInData, puiInDataLen,
p, &len)) != SAR_OK) {
SAFerr(SAF_F_SAF_BASE64_ENCODE, ERR_R_GMAPI_LIB);
goto end;
}
p += len;
len = *puiOutDataLen - len;
if ((ret = SAF_Base64_EncodeFinal(handle, p, &len)) != SAR_OK) {
SAFerr(SAF_F_SAF_BASE64_ENCODE, ERR_R_GMAPI_LIB);
goto end;
}
p += len;
*puiOutDataLen = p - pucOutData;
ret = SAR_OK;
end:
SAF_Base64_DestroyBase64Obj(handle);
return ret;
}
/* 7.3.3 */
int SAF_Base64_Decode(
unsigned char *pucInData,
unsigned int puiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
int ret = SAR_UnknownErr;
void *handle = NULL;
unsigned char *p;
unsigned int len;
if ((ret = SAF_Base64_CreateBase64Obj(&handle)) != SAR_OK) {
SAFerr(SAF_F_SAF_BASE64_DECODE, ERR_R_GMAPI_LIB);
goto end;
}
p = pucOutData;
len = *puiOutDataLen;
if ((ret = SAF_Base64_DecodeUpdate(handle, pucInData, puiInDataLen,
p, &len)) != SAR_OK) {
SAFerr(SAF_F_SAF_BASE64_DECODE, ERR_R_GMAPI_LIB);
goto end;
}
p += len;
len = *puiOutDataLen - len;
if ((ret = SAF_Base64_DecodeFinal(handle, p, &len)) != SAR_OK) {
SAFerr(SAF_F_SAF_BASE64_DECODE, ERR_R_GMAPI_LIB);
goto end;
}
p += len;
*puiOutDataLen = p - pucOutData;
ret = SAR_OK;
end:
SAF_Base64_DestroyBase64Obj(handle);
return ret;
}
int SAF_Base64_test(int verbose)
{
int ret = SAR_UnknownErr;
/* sizeof(buf1)%3 == 1 makes base64 ended with "==" */
unsigned char buf1[121];
unsigned char buf2[512];
unsigned char buf3[512];
unsigned int len1, len2, len3;
/* generate some random binary for testing */
RAND_bytes(buf1, sizeof(buf1));
memset(buf2, 0, sizeof(buf2));
memset(buf3, 0, sizeof(buf3));
len1 = (unsigned int)sizeof(buf1);
len2 = (unsigned int)sizeof(buf2);
if ((ret = SAF_Base64_Encode(buf1, len1, buf2, &len2)) != SAR_OK) {
ERR_print_errors_fp(stderr);
goto end;
}
if (verbose) {
printf("%s\n", buf2);
}
len3 = sizeof(buf3);
if ((ret = SAF_Base64_Decode(buf2, len2, buf3, &len3)) != SAR_OK) {
ERR_print_errors_fp(stderr);
goto end;
}
/* check correctness */
if (len1 == len3 && memcmp(buf1, buf3, len1) == 0) {
ret = SAR_OK;
} else {
/* make sure to assign `ret`, or it might be set as OK by
* previous functions */
ret = SAR_UnknownErr;
}
end:
if (verbose) {
printf("%s %s\n", __FUNCTION__,
ret == SAR_OK ? "passed" : "failed");
}
return SAR_OK;
}

254
crypto/saf/saf_cert.c Normal file
View File

@@ -0,0 +1,254 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/conf.h>
#include <openssl/gmsaf.h>
/* 7.2.2 */
int SAF_AddTrustedRootCaCertificate(
void *hAppHandle,
unsigned char *pucCertificate,
unsigned int uiCertificateLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.3 */
int SAF_GetRootCaCertificateCount(
void *hAppHandle,
unsigned int *puiCount)
{
*puiCount = 0;
return SAR_Ok;
}
/* 7.2.4 */
int SAF_GetRootCaCertificate(
void *hAppHandle,
unsigned int uiIndex,
unsigned char *pucCertificate,
unsigned int *puiCertificateLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.5 */
int SAF_RemoveRootCaCertificate(
void *hAppHandle,
unsigned int uiIndex)
{
return SAR_NotSupportYetErr;
}
/* 7.2.6 */
int SAF_AddCaCertificate(
void *hAppHandle,
unsigned char *pucCertificate,
unsigned int *puiCertificateLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.7 */
int SAF_GetCaCertificateCount(
void *hAppHandle,
unsigned int *puiCount)
{
return SAR_NotSupportYetErr;
}
/* 7.2.8 */
int SAF_GetCaCertificate(
void *hAppHandle,
unsigned int uiIndex,
unsigned char *pucCertificate,
unsigned int *puiCertificateLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.9 */
int SAF_RemoveCaCertificate(
void *hAppHandle,
unsigned int uiIndex)
{
return SAR_NotSupportYetErr;
}
/* 7.2.10 */
int SAF_AddCrl(
void *hAppHandle,
unsigned char *pucDerCrl,
unsigned int uiDerCrlLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.11 */
int SAF_VerifyCertificate(
void *hAppHandle,
unsigned char *pucUsrCertificate,
unsigned int uiUsrCertificateLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.12 */
int SAF_VerifyCertificateByCrl(
void *hAppHandle,
unsigned char *pucUsrCertificate,
unsigned int uiUsrCertificateLen,
unsigned char *pucDerCrl,
unsigned int uiDerCrlLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.13 */
int SAF_GetCertificateStateByOCSP(
void *hAppHandle,
unsigned char *pcOcspHostURL,
unsigned int uiOcspHostURLLen,
unsigned char *pucUsrCertificate,
unsigned int uiUsrCertificateLen,
unsigned char *pucCACertificate,
unsigned int uiCACertficateLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.14 */
int SAF_GetCertFromLdap(
void *hAppHandle,
char *pcLdapHostURL,
unsigned int uiLdapHostURLLen,
unsigned char *pucQueryDN,
unsigned int uiQueryDNLen,
unsigned char *pucOutCert,
unsigned int *puiOutCertLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.15 */
int SAF_GetCrlFromLdap(
void *hAppHandle,
char *pcLdapHostURL,
unsigned int uiLdapHostURLLen,
unsigned char *pucCertificate,
unsigned int uiCertificateLen,
unsigned char *pucCrlData,
unsigned int *puiCrlDataLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.16 */
int SAF_GetCertificateInfo(
void *hAppHandle,
unsigned char *pucCertificate,
unsigned int uiCertificateLen,
unsigned int uiInfoType,
unsigned char *pucInfo,
unsigned int *puiInfoLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.17 */
int SAF_GetExtTypeInfo(
void *hAppHandle,
unsigned char *pucDerCert,
unsigned int uiDerCertLen,
unsigned int uiInfoType,
unsigned char *pucPriOid,
unsigned int uiPriOidLen,
unsigned char *pucInfo,
unsigned int *puiInfoLen)
{
return SAR_NotSupportYetErr;
}
/* 7.2.18 */
int SAF_EnumCertificates(
void *hAppHandle,
SGD_USR_CERT_ENUMLIST *usrCerts)
{
return SAR_NotSupportYetErr;
}
/* 7.2.19 */
int SAF_EnumKeyContainerInfo(
void *hAppHandle,
SGD_KEYCONTAINERINFO_ENUMLIST *keyContainerInfo)
{
return SAR_NotSupportYetErr;
}
/* 7.2.20 */
int SAF_EnumCertificatesFree(
void *hAppHandle,
SGD_USR_CERT_ENUMLIST *usrCerts)
{
return SAR_NotSupportYetErr;
}
/* 7.2.21 */
int SAF_EnumKeyContainerInfoFree(
void *hAppHandle,
SGD_KEYCONTAINERINFO_ENUMLIST *keyContainerInfo)
{
return SAR_NotSupportYetErr;
}

719
crypto/saf/saf_ec.c Normal file
View File

@@ -0,0 +1,719 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
/* GM/T 0019-2012: 7.3.23 */
/*
* uiKeyUsage in {SGD_SM2_1, SGD_SM2_2, SGD_SM2_3}
* uiExportFlag = 1 means exportable, 0 means non-exportable
* we will generate a key pair and import into ENGINE
* or use ENGINE to generate key pair
*/
#include <openssl/gmapi.h>
#include <openssl/gmsdf.h>
#include <openssl/gmsaf.h>
int saf_save_ec_keypair(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyBits,
unsigned int uiKeyUsage,
unsigned int uiExportFlag,
ECCrefPublicKey *pucPublicKey,
ECCrefPrivateKey *pucPrivateKey)
{
return -1;
}
/* 7.3.23 */
int SAF_GenEccKeyPair(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyBits,
unsigned int uiKeyUsage,
unsigned int uiExportFlag)
{
int ret = -1;
ECCrefPublicKey publicKey;
ECCrefPrivateKey privateKey;
/* check arguments */
if (!hAppHandle || !pucContainerName) {
SAFerr(SAF_F_SAF_GENECCKEYPAIR,
ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (uiContainerNameLen <= 0 || uiContainerName > SGD_MAX_NAME_SIZE ||
strlen((char *)pucContainerName) != uiContainerNameLen) {
SAFerr(SAF_F_SAF_GENECCKEYPAIR,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_NameLenErr;
}
if (uiKeyBits < 160 || uiKeyBits > ECCref_MAX_BITS) {
SAFerr(SAF_F_SAF_GENECCKEYPAIR,
SAF_R_INVALID_KEY_LENGTH);
return SAR_ModulusLenErr;
}
if (uiKeyUsage != SGD_SM2_1 && uiKeyUsage != SGD_SM2_2 &&
uiKeyUsage != SGD_SM2_3) {
SAFerr(SAF_F_SAF_GENECCKEYPAIR,
SAF_R_INVALID_KEY_USAGE);
return SAR_KeyUsageErr;
}
/* generate keypair */
if (SDF_GenerateKeyPair_ECC(
NULL,
uiKeyUsage,
uiKeyBits,
&publicKey,
&privateKey) != SDR_OK) {
SAFerr(SAF_F_SAF_GENECCKEYPAIR, SAF_R_SAF_ERROR);
goto end;
}
/* save keypair */
if (saf_save_ec_keypair(
hAppHandle,
pucContainerName,
uiContainerNameLen,
uiKeyBits,
uiKeyUsage,
uiExportFlag,
&publicKey,
&privateKey) != SAR_Ok) {
SAFerr(SAF_F_SAF_GENECCKEYPAIR, ERR_R_GMAPI_LIB);
goto end;
}
/* set return value */
ret = SAR_Ok;
end:
/* clear private key */
memset(&privateKey, 0, sizeof(ECCrefPrivateKey));
return ret;
}
int saf_get_sdf_session_and_keyindex(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyUsage,
void *phSessionHandle,
unsigned int puiKeyIndex)
{
return -1;
}
void saf_release_sdf_session(
void *hSessionHandle)
{
}
/*
* `crypto/ec` only support `i2o_ECPublicKey` and `o2i_ECPublicKey`, there
* are no DER encoding/decoding routines for EC public key. The encoding of
* `i2o` is just the result of `EC_POINT_point2oct` on the public key point.
*/
/* 7.3.24 */
int SAF_GetEccPublicKey(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyUsage,
unsigned char *pucPublicKey,
unsigned int *puiPublicKeyLen)
{
int ret = -1;
void *hSessionHandle = NULL;
unsigned int uiKeyIndex;
int rv;
/* check arguments */
if (!hAppHandle || !pucContainerNamae || !pucPUblicKey ||
!puiPublicKeyLen) {
SAFerr(SAF_F_SAF_GETECCPUBLICKEY,
ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (uiContainerNameLen <= 0 ||
uiContainerNameLen > SGD_MAX_NAME_SIZE ||
strlen((char *)pucContainerName) != uiContainerNameLen) {
SAFerr(SAF_F_SAF_GETECCPUBLICKEY,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_NameLenErr;
}
if (uiKeyUsage != SGD_SM2_1 && uiKeyUsage != SGD_SM2_2 &&
uiKeyUsage != SGD_SM2_3) {
SAFerr(SAF_F_SAF_GETECCPUBLICKEY,
SAF_R_INVALID_KEY_USAGE);
return SAR_KeyUsageErr;
}
if ((size_t)*puiPublicKeyLen != sizeof(ECCrefPublicKey)) {
SAFerr(SAF_F_SAF_GETECCPUBLICKEY,
SAF_R_BUFFER_TOO_SMALL);
return SAR_IndataErr;
}
/* get session and key index*/
if ((rv = saf_get_sdf_session_and_keyindex(
hAppHandle,
pucContainerName,
uiContainerNameLen,
uiKeyUsage,
&hSessionHandle,
&uiKeyIndex)) != SAR_Ok) {
SAFerr(SAF_F_SAF_GETECCPUBLICKEY, ERR_R_GMAPI_LIB);
ret = rv;
goto end;
}
/* load key */
if (uiKeyUsage == SGD_SM2_1) {
if (SDF_ExportSignPublicKey_ECC(
hSessionHandle,
uiKeyIndex,
(ECCrefPublicKey *)pucPublicKey) != SDR_OK) {
SAFerr(SAF_F_SAF_GETECCPUBLICKEY, ERR_R_GMAPI_LIB);
goto end;
}
} else {
if (SDF_ExportEncPublicKey_ECC(
hSessionHandle,
uiKeyIndex,
(ECCrefPublicKey *)pucPublicKey) != SDR_OK) {
SAFerr(SAF_F_SAF_GETECCPUBLICKEY, ERR_R_GMAPI_LIB);
goto end;
}
}
/* set return value */
*puiPublicKeyLen = (unsigned int)sizeof(ECCrefPublicKey);
ret = SAR_Ok;
end:
sdf_release_sdf_session(hSessionHandle);
return ret;
}
/* 7.3.25 */
/* input data is message, not digest
* otuput is the DER encoding of the signature
*
* WHY do we need a seperate function for EC and RSA?
*/
int saf_get_sdf_session_and_ecsignkey(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiAlgorithmID, /* SGD_SM2_1 */
void **phSessionhandle,
unsigned int *puiISKIndex);
int SAF_EccSign(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiAlgorithmID, /* SGD_SM2_1 */
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucSignData,
unsigned int *puiSignDataLen)
{
int ret = SAR_UnknownErr;
void *hSessionHandle = NULL;
unsigned int uiISKIndex;
/* check arguments */
if (!hAppHandle || !pucContainerNamae || !pucPUblicKey ||
!pucSignData || !pucSignDataLen) {
SAFerr(SAF_F_SAF_ECCSIGN,
ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (uiContainerNameLen <= 0 ||
uiContainerNameLen > SGD_MAX_NAME_SIZE ||
strlen((char *)pucContainerName) != uiContainerNameLen) {
SAFerr(SAF_F_SAF_ECCSIGN, SAF_R_INVALID_INPUT_LENGTH);
return SAR_NameLenErr;
}
if (uiAlgorithmID != SGD_SM2_1) {
SAFerr(SAF_F_SAF_ECCSIGN, SAF_R_INVALID_ALGOR);
return SAR_AlgoTypeErr;
}
if (uiInDataLen != SM3_DIGEST_LENGTH) {
SAFerr(SAF_F_SAF_ECCSIGN, SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
if ((size_t)*puiSignDataLen != sizeof(ECCSignature)) {
SAFerr(SAF_F_SAF_ECCSIGN, SAF_R_BUFFER_TOO_SMALL);
return SAR_IndataErr;
}
/* get session and ec sign key */
if ((rv = saf_get_sdf_session_and_ecsignkey(
hAppHandle,
pucContainerName,
uiContainerNameLen,
uiAlgorithmID,
&hSessionHandle,
&uiISKIndex)) != SAR_Ok) {
SAFerr(SAF_F_SAF_ECCSIGN, ERR_R_GMAPI_LIB);
ret = rv;
goto end;
}
/* sign */
if (SDF_InternalSign_ECC(
hSessionHandle,
uiISKIndex,
pucInData,
uiInDataLen,
(ECCSignature *)pucSignData) != SDR_OK) {
SAFerr(SAF_F_SAF_ECCSIGN, ERR_R_GMAPI_LIB);
goto end;
}
/* set return value */
*puiSignDataLen = (unsigned int)sizeof(ECCSignature);
ret = SAR_Ok;
end:
saf_release_sdf_session(hSessionhandle);
return ret;
}
/* 7.3.26 */
/* it seems that we need the public key has more info */
int SAF_EccVerifySign(
unsigned char *pucPublicKey,
unsigned int uiPublicKeyLen,
unsigned int uiAlgorithmID,
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucSignData,
unsigned int uiSignDataLen)
{
int ret = SAR_UnknownErr;
/* check arguments */
if (!pucPublicKey || !pucInData || !pucSignData) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGN, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr);
}
if (uiPublicKeyLen != sizeof(ECCrefPublic)) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGN, SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
if (uiAlgorithmID != SGD_SM2_1) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGN, SAF_R_INVALID_ALGOR);
return SAR_AlgoTypeErr;
}
if (uiInDataLen != SM3_DIGEST_LENGTH) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGN, SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
if (uiSignDataLen != sizeof(ECCSignature)) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGN, SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
if (SDF_ExternalVerify_ECC(
NULL, /* hSessionHandle */
uiAlgorithmID,
(ECCrefPublicKey *)pucPublicKey,
pucInData,
uiInDataLen,
(ECCSignature *)pucSignData) != SDR_OK) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGN, ERR_R_GMAPI_LIB);
goto end;
}
ret = SAR_Ok;
end:
return ret;
}
/* 7.3.27 */
int SAF_EccPublicKeyEnc(
unsigned char *pucPublicKey,
unsigned int uiPublicKeyLen,
unsigned int uiAlgorithmID,
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
/* check arguments */
if (!pucPublicKey || !pucInData || !pucOutData || !puiOutDataLen) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENC,
ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (uiPublicKeyLen != sizeof(ECCrefPublic)) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENC,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
if (uiAlgorithmID != SGD_SM2_3) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENC,
SAF_R_INVALID_ALGOR);
return SAR_AlgoTypeErr;
}
if (uiInDataLen <= 0 || uiInDataLen > ECCref_MAX_CIPHER_LEN) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENC,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
if (*puiOutDataLen != sizeof(ECCCipher)) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENC,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
/* encrypt */
if (SDF_ExternalEncrypt_ECC(
NULL, /* hSessionHandle */
uiAlgorithmID,
(ECCrefPublicKey *)pucPublicKey,
pucInData,
uiInDataLen,
(ECCCipher *)pucOutData) != SDR_OK) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENC, ERR_R_GMAPI_LIB);
goto end;
}
ret = SAR_Ok;
end:
return ret;
}
int saf_get_ec_public_key_from_cert(
unsigned char *pucCertificate,
unsigned int uiCertificateLen,
ECCrefPublicKey *pucPublicKey)
{
return -1;
}
/* 7.3.28 */
int SAF_EccPublicKeyEncByCert(
unsigned char *pucCertificate,
unsigned int uiCertificateLen,
unsigned int uiAlgorithmID,
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
int ret = SAR_UnknownErr;
ECCrefPublicKey publicKey;
int rv;
/* check arguments */
if (!pucCertificate || !pucInData || !pucOutData || !puiOutDataLen) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENCBYCERT,
ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr);
}
if (uiCertificateLen <= 0 || uiCertificate > INT_MAX) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENCBYCERT,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
if (uiAlgorithmID != SGD_SM2_3) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENCBYCERT,
SAF_R_INVALID_ALGOR);
return SAR_AlgoTypeErr;
}
if (uiInDataLen <= 0 || uiInDataLen > ECCref_MAX_CIPHER_LEN) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENCBYCERT,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
if (*puiOutDataLen != sizeof(ECCCipher)) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENCBYCERT,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
/* get public key from cert */
if ((rv = saf_get_ec_public_key_from_cert(
pucCertificate,
uiCertificateLen,
&publicKey)) != SAR_OK) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENCBYCERT, ERR_R_GMAPI_LIB);
ret = rv;
goto end;
}
/* encrypt */
if (SAF_EccPublicKeyEnc(
(unsigned char *)&publicKey,
(unsigned int)sizeof(ECCrefPublicKey),
uiAlgorithmID,
pucInData,
uiInDataLen,
pucOutData,
puiOutDataLen) != SAR_OK) {
SAFerr(SAF_F_SAF_ECCPUBLICKEYENCBYCERT, ERR_R_GMAPI_LIB);
goto end;
}
/* set return value */
ret = SAR_Ok;
end:
return ret;
}
/* 7.3.29 */
int SAF_EccVerifySignByCert(
unsigned int uiAlgorithmID,
unsigned char *pucCertificate,
unsigned int uiCertificateLen,
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucSignData,
unsigned int uiSignDataLen)
{
int ret = SAR_UnknownErr;
ECCrefPublicKey publicKey;
int rv;
/* check arguments */
if (!pucCertificate || !pucInData || !pucSignData) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGNBYCERT,
ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr);
}
if (uiCertificateLen <= 0 || uiCertificate > INT_MAX) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGNBYCERT,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
if (uiAlgorithmID != SGD_SM2_1) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGNBYCERT,
SAF_R_INVALID_ALGOR);
return SAR_AlgoTypeErr;
}
if (uiInDataLen != SM3_DIGEST_LENGTH) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGNBYCERT,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
if (uiSignDataLen != sizeof(ECCSignature)) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGNBYCERT,
SAF_R_INVALID_INPUT_LENGTH);
return SAR_IndataLenErr;
}
/* load public key form cert */
if ((rv = saf_get_ec_public_key_from_cert(
pucCertificate,
uiCertificateLen,
&publicKey))!= SAR_OK) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGNBYCERT, ERR_R_GMAPI_LIB);
ret = rv;
goto end;
}
/* verify */
if (SAF_EccVerifySign(
(unsigned char *)&publicKey,
(unsigned int )sizeof(ECCrefPublicKey),
uiAlgorithmID,
pucInData,
uiInDataLen,
pucSignData,
uiSignDataLen)!= SAR_Ok) {
SAFerr(SAF_F_SAF_ECCVERIFYSIGNBYCERT, ERR_R_GMAPI_LIB);
goto end;
}
/* set return value */
ret = SAR_Ok;
end:
return ret;
}
/* 7.3.33 */
int SAF_GenerateAgreementDataWithECC(
void *hSymmKeyObj,
unsigned int uiISKIndex,
unsigned int uiKeyBits,
unsigned char *pucSponsorID,
unsigned int uiSponsorIDLength,
unsigned char *pucSponsorPublicKey,
unsigned int *puiSponsorPublicKeyLen,
unsigned char *pucSponsorTmpPublicKey,
unsigned int *puiSponsorTmpPublicKeyLen,
void **phAgreementHandle)
{
int ret = -1;
void *hSessionHandle = NULL;
unsigned int uiISKIndex;
if (SDF_GenerateAgreementDataWithECC(
hSessionHandle,
uiISKIndex,
uiKeyBits,
pucSponsorID,
uiSponsorIDLength,
(ECCrefPublicKey *)pucSponsorPublicKey,
(ECCrefPublicKey *)pucSponsorTmpPublicKey,
phAgreementHandle) != SDR_OK) {
SAFerr(SAF_F_SAF_GENERATEAGREEMENTDATAWITHECC,
ERR_R_GMAPI_LIB);
goto end;
}
ret = SAR_Ok;
end:
return ret;
}
/* 7.3.34 */
int SAF_GenerateKeyWithECC(
void *phAgreementHandle,
unsigned char *pucResponseID,
unsigned int uiResponseIDLength,
unsigned char *pucResponsePublicKey,
unsigned int uiResponsePublicKeyLen,
unsigned char *pucResponseTmpPublicKey,
unsigned int uiResponseTmpPublicKeyLen,
void **phKeyHandle)
{
int ret = -1;
if (SDF_GenerateKeyWithECC(
NULL, /*hSessionHandle */
pucResponseID,
uiResponseIDLength,
(ECCrefPublicKey *)pucResponsePublicKey,
(ECCrefPublicKey *)pucResponseTmpPublicKey,
phAgreementHandle,
phKeyHandle) != SDR_OK) {
SAFerr(SAF_F_SAF_GENERATEKEYWITHECC, ERR_R_GMAPI_LIB);
goto end;
}
return 0;
}
/* 7.3.35 */
int SAF_GenerateAgreementDataAdnKeyWithECC(
void *hSymmKeyObj,
unsigned int uiISKIndex,
unsigned int uiKeyBits,
unsigned char *pucResponseID,
unsigned int uiResponseIDLength,
unsigned char *pucSponsorID,
unsigned int uiSponsorIDLength,
unsigned char *pucSponsorPublicKey,
unsigned int *puiSponsorPublicKeyLen,
unsigned char *pucSponsorTmpPublicKey,
unsigned int *puiSponsorTmpPublicKeyLen,
unsigned char *pucResponsePublicKey,
unsigned int uiResponsePublicKeyLen,
unsigned char *pucResponseTmpPublicKey,
unsigned int uiResponseTmpPublicKeyLen,
void **phKeyHandle)
{
int ret;
void *hAgreementHandle = NULL;
if ((ret = SAF_GenerateAgreementDataWithECC(
hSymmKeyObj,
uiISKIndex,
uiKeyBits,
pucSponsorID,
uiSponsorIDLength,
pucSponsorPublicKey,
puiSponsorPublicKeyLen,
pucSponsorTmpPublicKey,
puiSponsorTmpPublicKeyLen,
&hAgreementHandle)) != SAR_OK) {
}
if ((ret = SAF_GenerateKeyWithECC(
hAgreementHandle,
pucResponseID,
uiResponseIDLength,
pucResponsePublicKey,
uiResponsePublicKeyLen,
pucResponseTmpPublicKey,
uiResponseTmpPublicKeyLen,
phKeyHandle)) != SAR_OK) {
}
return 0;
}

16
crypto/saf/saf_ec.d.tmp Normal file
View File

@@ -0,0 +1,16 @@
crypto/saf/saf_ec.o: crypto/saf/saf_ec.c include/openssl/gmapi.h \
include/openssl/ec.h include/openssl/opensslconf.h \
include/openssl/asn1.h include/openssl/e_os2.h include/openssl/bio.h \
include/openssl/crypto.h include/openssl/stack.h \
include/openssl/safestack.h include/openssl/opensslv.h \
include/openssl/ossl_typ.h include/openssl/symhacks.h \
include/openssl/bn.h include/openssl/sm2.h include/openssl/err.h \
include/openssl/lhash.h include/openssl/evp.h \
include/openssl/objects.h include/openssl/obj_mac.h \
include/openssl/kdf2.h include/openssl/kdf.h include/openssl/x509.h \
include/openssl/buffer.h include/openssl/rsa.h include/openssl/dsa.h \
include/openssl/dh.h include/openssl/sha.h include/openssl/x509_vfy.h \
include/openssl/pkcs7.h include/openssl/ecdsa.h include/openssl/sm3.h \
include/openssl/sgd.h include/openssl/saf.h include/openssl/sdf.h \
include/openssl/skf.h include/openssl/sof.h include/openssl/gmsdf.h \
include/openssl/gmsaf.h

272
crypto/saf/saf_enc.c Normal file
View File

@@ -0,0 +1,272 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/gmsaf.h>
#include <openssl/gmapi.h>
/* 7.3.39 */
int SAF_SymmEncryptUpdate(
void *hKeyHandle,
const unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
int ret = SAR_UnknownErr;
SAF_KEY_HANDLE *hkey = (SAF_KEY_HANDLE *)hKeyHandle;
unsigned char *out = pucOutData;
int inlen, outlen;
if (!hKeyHandle || !pucInData || !pucOutData || !puiOutDataLen) {
SAFerr(SAF_F_SAF_SYMMENCRYPTUPDATE, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (uiInDataLen > INT_MAX) {
SAFerr(SAF_F_SAF_SYMMENCRYPTUPDATE, SAF_R_INVALID_LENGTH);
return SAR_IndataLenErr;
}
if (!hkey->cipher_ctx) {
unsigned char iv[32];
int ivlen;
if (!(hkey->cipher_ctx = EVP_CIPHER_CTX_new())) {
SAFerr(SAF_F_SAF_SYMMENCRYPTUPDATE, ERR_R_MALLOC_FAILURE);
ret = SAR_MemoryErr;
goto end;
}
/* generate random iv and output */
ivlen = EVP_CIPHER_block_size(hkey->cipher);
if (ivlen <= 0 || ivlen > sizeof(iv)) {
SAFerr(SAF_F_SAF_SYMMENCRYPTUPDATE, SAF_R_INVALID_CONTEXT);
ret = SAR_ObjErr;
goto end;
}
if (!RAND_bytes(iv, ivlen)) {
SAFerr(SAF_F_SAF_SYMMENCRYPTUPDATE, SAF_R_GEN_RANDOM);
ret = SAR_GenRandErr;
goto end;
}
/* output iv, update out pointer */
memcpy(out, iv, ivlen);
out += ivlen;
if (!EVP_EncryptInit(hkey->cipher_ctx, hkey->cipher, hkey->key, iv)) {
SAFerr(SAF_F_SAF_SYMMENCRYPTUPDATE, ERR_R_EVP_LIB);
goto end;
}
}
inlen = (int)uiInDataLen;
if (!EVP_EncryptUpdate(hkey->cipher_ctx, out, &outlen, pucInData, inlen)) {
SAFerr(SAF_F_SAF_SYMMENCRYPTUPDATE, ERR_R_EVP_LIB);
goto end;
}
*puiOutDataLen = (unsigned int)outlen;
ret = SAR_OK;
end:
if (ret != SAR_OK && hkey->cipher_ctx) {
EVP_CIPHER_CTX_free(hkey->cipher_ctx);
hkey->cipher_ctx = NULL;
}
return ret;
}
/* 7.3.40 */
int SAF_SymmEncryptFinal(
void *hKeyHandle,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
return 0;
}
/* 7.3.42 */
int SAF_SymmDecryptUpdate(
void *hKeyHandle,
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
int ret = SAR_UnknownErr;
SAF_KEY_HANDLE *hkey = (SAF_KEY_HANDLE *)hKeyHandle;
unsigned char *in = pucInData;
int inlen, outlen;
if (!hKeyHandle || !pucInData || !pucOutData || !puiOutDataLen) {
SAFerr(SAF_F_SAF_SYMMDECRYPTUPDATE, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (uiInDataLen > INT_MAX) {
SAFerr(SAF_F_SAF_SYMMDECRYPTUPDATE, SAF_R_INVALID_LENGTH);
return SAR_IndataLenErr;
}
inlen = (int)uiInDataLen;
if (!hkey->cipher_ctx) {
unsigned char iv[32];
int ivlen;
if (!(hkey->cipher_ctx = EVP_CIPHER_CTX_new())) {
SAFerr(SAF_F_SAF_SYMMDECRYPTUPDATE, ERR_R_MALLOC_FAILURE);
ret = SAR_MemoryErr;
goto end;
}
/* get iv from input */
ivlen = EVP_CIPHER_block_size(hkey->cipher);
if (ivlen <= 0 || ivlen > sizeof(iv)) {
SAFerr(SAF_F_SAF_SYMMDECRYPTUPDATE, SAF_R_INVALID_CONTEXT);
ret = SAR_ObjErr;
goto end;
}
memcpy(iv, in, ivlen);
in += ivlen;
inlen -= ivlen;
if (!EVP_DecryptInit(hkey->cipher_ctx, hkey->cipher, hkey->key, iv)) {
SAFerr(SAF_F_SAF_SYMMDECRYPTUPDATE, ERR_R_EVP_LIB);
goto end;
}
}
if (!EVP_DecryptUpdate(hkey->cipher_ctx, pucOutData, &outlen, in, inlen)) {
SAFerr(SAF_F_SAF_SYMMDECRYPTUPDATE, ERR_R_EVP_LIB);
goto end;
}
*puiOutDataLen = (unsigned int)outlen;
ret = SAR_OK;
end:
if (ret != SAR_OK && hkey->cipher_ctx) {
EVP_CIPHER_CTX_free(hkey->cipher_ctx);
hkey->cipher_ctx = NULL;
}
return ret;
}
/* 7.3.43 */
int SAF_SymmDecryptFinal(
void *hKeyHandle,
const unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
return 0;
}
/* 7.3.38 */
int SAF_SymmEncrypt(
void *hKeyHandle,
const unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
int ret;
unsigned char *out;
unsigned int outlen;
out = pucOutData;
outlen = *puiOutDataLen;
if ((ret = SAF_SymmEncryptUpdate(hKeyHandle, pucInData, uiInDataLen,
out, &outlen)) != SAR_OK) {
return ret;
}
out += outlen;
if ((ret = SAF_SymmEncryptFinal(hKeyHandle, out, &outlen)) != SAR_OK) {
return ret;
}
out += outlen;
*puiOutDataLen = out - pucOutData;
return SAR_OK;
}
/* 7.3.41 */
int SAF_SymmDecrypt(
void *hKeyHandle,
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
int ret;
unsigned char *out;
unsigned int outlen;
out = pucOutData;
outlen = *puiOutDataLen;
if ((ret = SAF_SymmDecryptUpdate(hKeyHandle, pucInData, uiInDataLen,
out, &outlen)) != SAR_OK) {
return ret;
}
out += outlen;
if ((ret = SAF_SymmDecryptFinal(hKeyHandle, out, &outlen)) != SAR_OK) {
return ret;
}
out += outlen;
*puiOutDataLen = out - pucOutData;
return SAR_OK;
}

84
crypto/saf/saf_err.c Normal file
View File

@@ -0,0 +1,84 @@
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/gmsaf.h>
/* BEGIN ERROR CODES */
#ifndef OPENSSL_NO_ERR
# define ERR_FUNC(func) ERR_PACK(ERR_LIB_SAF,func,0)
# define ERR_REASON(reason) ERR_PACK(ERR_LIB_SAF,0,reason)
static ERR_STRING_DATA SAF_str_functs[] = {
{ERR_FUNC(SAF_F_SAF_BASE64_CREATEBASE64OBJ),
"SAF_Base64_CreateBase64Obj"},
{ERR_FUNC(SAF_F_SAF_BASE64_DECODE), "SAF_Base64_Decode"},
{ERR_FUNC(SAF_F_SAF_BASE64_DECODEFINAL), "SAF_Base64_DecodeFinal"},
{ERR_FUNC(SAF_F_SAF_BASE64_DECODEUPDATE), "SAF_Base64_DecodeUpdate"},
{ERR_FUNC(SAF_F_SAF_BASE64_ENCODE), "SAF_Base64_Encode"},
{ERR_FUNC(SAF_F_SAF_BASE64_ENCODEFINAL), "SAF_Base64_EncodeFinal"},
{ERR_FUNC(SAF_F_SAF_BASE64_ENCODEUPDATE), "SAF_Base64_EncodeUpdate"},
{ERR_FUNC(SAF_F_SAF_CREATESYMMKEYOBJ), "SAF_CreateSymmKeyObj"},
{ERR_FUNC(SAF_F_SAF_ECCPUBLICKEYENC), "SAF_EccPublicKeyEnc"},
{ERR_FUNC(SAF_F_SAF_ECCPUBLICKEYENCBYCERT), "SAF_EccPublicKeyEncByCert"},
{ERR_FUNC(SAF_F_SAF_ECCSIGN), "SAF_EccSign"},
{ERR_FUNC(SAF_F_SAF_ECCVERIFYSIGN), "SAF_EccVerifySign"},
{ERR_FUNC(SAF_F_SAF_ECCVERIFYSIGNBYCERT), "SAF_EccVerifySignByCert"},
{ERR_FUNC(SAF_F_SAF_GENECCKEYPAIR), "SAF_GenEccKeyPair"},
{ERR_FUNC(SAF_F_SAF_GENERATEAGREEMENTDATAWITHECC),
"SAF_GenerateAgreementDataWithECC"},
{ERR_FUNC(SAF_F_SAF_GENERATEKEYWITHECC), "SAF_GenerateKeyWithECC"},
{ERR_FUNC(SAF_F_SAF_GETECCPUBLICKEY), "SAF_GetEccPublicKey"},
{ERR_FUNC(SAF_F_SAF_MACFINAL), "SAF_MacFinal"},
{ERR_FUNC(SAF_F_SAF_MACUPDATE), "SAF_MacUpdate"},
{ERR_FUNC(SAF_F_SAF_PKCS7_DECODEDIGESTEDDATA),
"SAF_Pkcs7_DecodeDigestedData"},
{ERR_FUNC(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA),
"SAF_Pkcs7_EncodeDigestedData"},
{ERR_FUNC(SAF_F_SAF_SYMMDECRYPTUPDATE), "SAF_SymmDecryptUpdate"},
{ERR_FUNC(SAF_F_SAF_SYMMENCRYPTUPDATE), "SAF_SymmEncryptUpdate"},
{0, NULL}
};
static ERR_STRING_DATA SAF_str_reasons[] = {
{ERR_REASON(SAF_R_BUFFER_TOO_SMALL), "buffer too small"},
{ERR_REASON(SAF_R_CBCMAC_FAILURE), "cbcmac failure"},
{ERR_REASON(SAF_R_GEN_RANDOM), "gen random"},
{ERR_REASON(SAF_R_INT_OVERFLOW), "int overflow"},
{ERR_REASON(SAF_R_INVALID_ALGOR), "invalid algor"},
{ERR_REASON(SAF_R_INVALID_CONTEXT), "invalid context"},
{ERR_REASON(SAF_R_INVALID_DIGEST_ALGOR), "invalid digest algor"},
{ERR_REASON(SAF_R_INVALID_HANDLE), "invalid handle"},
{ERR_REASON(SAF_R_INVALID_INPUT_LENGTH), "invalid input length"},
{ERR_REASON(SAF_R_INVALID_KEY_LENGTH), "invalid key length"},
{ERR_REASON(SAF_R_INVALID_KEY_USAGE), "invalid key usage"},
{ERR_REASON(SAF_R_INVALID_LENGTH), "invalid length"},
{ERR_REASON(SAF_R_MAC_FAILURE), "mac failure"},
{ERR_REASON(SAF_R_OPERATION_NOT_INITIALIZED),
"operation not initialized"},
{ERR_REASON(SAF_R_SAF_ERROR), "saf error"},
{0, NULL}
};
#endif
int ERR_load_SAF_strings(void)
{
#ifndef OPENSSL_NO_ERR
if (ERR_func_error_string(SAF_str_functs[0].error) == NULL) {
ERR_load_strings(0, SAF_str_functs);
ERR_load_strings(0, SAF_str_reasons);
}
#endif
return 1;
}

105
crypto/saf/saf_errstr.c Normal file
View File

@@ -0,0 +1,105 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <openssl/err.h>
#include <openssl/gmsaf.h>
#include "../../e_os.h"
static ERR_STRING_DATA saf_errstr[] = {
{ SAR_Ok, "Success" },
{ SAR_UnknownErr, "Unknown error" },
{ SAR_NotSupportYetErr, "Not supported yet error" },
{ SAR_FileErr, "File error" },
{ SAR_ProviderTypeErr, "Provider type error" },
{ SAR_LoadProviderErr, "Load provider error" },
{ SAR_LoadDevMngApiErr, "Load Device management API error" },
{ SAR_AlgoTypeErr, "Algorithm type error" },
{ SAR_NameLenErr, "Name length error" },
{ SAR_KeyUsageErr, "Key usage error" },
{ SAR_ModulusLenErr, "Modulus length error" },
{ SAR_NotInitializeErr, "Not initialized error" },
{ SAR_ObjErr, "Object error" },
{ SAR_MemoryErr, "Memory error" },
{ SAR_TimeoutErr, "Timeout error" },
{ SAR_IndataLenErr, "Input data length error" },
{ SAR_IndataErr, "Input data error" },
{ SAR_GenRandErr, "Generate random error" },
{ SAR_HashObjErr, "Hash object error" },
{ SAR_HashErr, "Hash error" },
{ SAR_GenRsaKeyErr, "Generate RSA key error" },
{ SAR_RsaModulusLenErr, "RSA modulus length error" },
{ SAR_CspImportPubKeyErr,"CSP import public key error" },
{ SAR_RsaEncErr, "RSA encryption error" },
{ SAR_RsaDecErr, "RSA decryption error" },
{ SAR_HashNotEqualErr, "Hash not equal error" },
{ SAR_KeyNotFoundErr, "Key not found error" },
{ SAR_CertNotFoundErr, "Certificate not found error" },
{ SAR_NotExportErr, "Non-exportable error" },
{ SAR_CertRevokedErr, "Certificate revoked error" },
{ SAR_CertNotYetValidErr,"Certificate not yet valid error" },
{ SAR_CerthashExpiredErr,"Certificate hash expirted error" },
{ SAR_CertVerifyErr, "Certificate verification error" },
{ SAR_CertEncodeErr, "Certificate encoding error" },
{ SAR_DecryptPadErr, "Decryption padding error" },
{ SAR_MacLenErr, "MAC length error" },
{ SAR_KeyInfoTypeErr, "Key information type error" },
{ SAR_NotLogin, "Not login" },
};
char *SAF_GetErrorString(int err)
{
int i;
for (i = 0; i < OSSL_NELEM(saf_errstr); i++) {
if (err == saf_errstr[i].error) {
return saf_errstr[i].string;
}
}
return "(undef)";
}

147
crypto/saf/saf_hash.c Normal file
View File

@@ -0,0 +1,147 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/gmsaf.h>
/* 7.3.12 */
int SAF_CreateHashObj(void **phHashObj,
unsigned int uiAlgoType,
unsigned char *pucPublicKey,
unsigned int uiPublicKeyLen,
unsigned char *pucID,
unsigned int ulIDLen)
{
int ret = SAR_UnkownErr;
const EVP_MD *md;
EVP_MD_CTX *ctx = NULL;
if (!(md = EVP_get_digestbysgd(uiAlgorithmType))) {
return SAR_AlgoTypeErr;
}
if (!(ctx = EVP_MD_CTX_new())) {
return 0;
}
if (!EVP_DigestInit(ctx, md)) {
return 0;
}
*phHashObj = ctx;
end:
if (ret != SAR_OK) {
EVP_MD_CTX_free(ctx);
*phHashObj = NULL;
}
return ret;
}
/* 7.3.13 */
int SAF_DestroyHashObj(
void *phHashObj)
{
EVP_MD_CTX_free((EVP_MD_CTX *)phHashObj);
return SAR_OK;
}
/* 7.3.14 */
int SAF_HashUpdate(
void *phHashObj,
const unsigned char *pucInData,
unsigned int uiInDataLen)
{
if (!EVP_DigestUpdate((EVP_MD_CTX *)phHashObj, pucInData, (size_t)uiInDataLne)) {
return SAR_HashErr;
}
return SAR_OK;
}
/* 7.3.15 */
int SAF_HashFinal(void *phHashObj,
unsigned char *pucOutData,
unsigned int *uiOutDataLen)
{
if (!EVP_DigestFinal((EVP_MD_CTX *)phHashObj, pucOutData, uiOutDataLen)) {
return SAR_HashErr;
}
return SAR_OK;
}
/* 7.3.11 */
int SAF_Hash(
unsigned int uiAlgoType,
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucPublicKey,
unsigned int uiPublicKeyLen,
unsigned char *pubID,
unsigned int ulIDLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
const EVP_MD *md;
size_t siz;
if (!(md = EVP_get_digestbysgd(uiAlgoType))) {
return SAR_AlgoTypeErr;
}
siz = (size_t)uiInDataLen;
if (!EVP_Digest(pucInData, siz, pucOutData, puiOutDataLen, md, NULL)) {
return SAR_HashErr;
}
return SAR_OK;
}

112
crypto/saf/saf_keyhandle.c Normal file
View File

@@ -0,0 +1,112 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <limits.h>
#include <openssl/evp.h>
#include <openssl/gmsaf.h>
#include <openssl/gmapi.h>
#include "saf_lcl.h"
/* 7.3.31
* Generate session key returned by `phKeyHandle`
* Encrypt the symmetric key `hSymmKeyObj` with the input public key
* `pucPublicKey`, output the encrypted results to `pucSymmKey`,
*
* how can we encrypt data with public key?
* it this function relies on ther SAF API?
*
* The function don't care the input public key. It should be an exported
* public key. Some extra information should be appened into the output key.
*/
int SAF_GenerateKeyWithEPK(
void *hSymmKeyObj,
unsigned char *pucPublicKey,
unsigned int uiPublicKeyLen,
unsigned char *pucSymmKey,
unsigned int uiSymmKeyLen,
void **phKeyHandle)
{
int pkey_type;
EVP_PKEY *pkey = NULL;
if (!(pkey = d2i_PublicKey(pkey_type, NULL, &p,
(long)uiPublicKeyLen))) {
}
}
/* 7.3.32 */
/* all the inforamtion should be kept in encrypted key
* the encrytped key can be decrypted with the default private key
*/
int SAF_ImportEncedKey(
void *hSymmKeyObj,
unsigned char *pucSymmKey,
unsigned int uiSymmKeyLen,
void **phKeyHandle)
{
return 0;
}
/* 7.3.37 */
int SAF_DestroyKeyHandle(
void *hKeyHandle)
{
SAF_KeyHandle *hkey = (SAF_KeyHandle *)hKeyHandle;
if (!hKeyHandle) {
return SAR_OK;
}
OPENSSL_clear_free(hkey->key, hkey->keylen);
return SAR_OK;
}

137
crypto/saf/saf_lcl.h Normal file
View File

@@ -0,0 +1,137 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <openssl/evp.h>
#include <openssl/cmac.h>
#include <openssl/gmsdf.h>
#include <openssl/gmsaf.h>
typedef struct {
const char *config_path;
ENGINE *engine;
} SAF_APP;
typedef struct {
EVP_ENCODE_CTX *ctx;
int inited;
} SAF_BASE64OBJ;
typedef struct {
void *hAppHandle;
unsigned char *pucContainerName;
unsigned int uiContainerLen;
unsigned char *pucIV;
unsigned int uiIVLen;
unsigned int uiEncOrDec;
unsigned int uiCryptoAlgID;
} SAF_SymmKeyObj;
typedef struct {
unsigned char *key;
size_t keylen;
/* used by `SAF_SymmEncryptUpdate`, `SAF_SymmEncryptFinal`,
* `SAF_SymmDecryptUpdate`, `SAF_SymmDecryptFinal`
*/
EVP_CIPHER_CTX *cipher_ctx;
const EVP_CIPHER *cipher;
CMAC_CTX *cmac_ctx;
} SAF_KEY_HANDLE;
int saf_readfile(
const char *file,
unsigned char **pout,
size_t *len);
int saf_save_ec_keypair(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyBits,
unsigned int uiKeyUsage,
unsigned int uiExportFlag,
ECCrefPublicKey *pucPublicKey,
ECCrefPrivateKey *pucPrivateKey);
int saf_save_rsa_keypair(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyBits,
unsigned int uiKeyUsage,
unsigned int uiExportFlag,
RSArefPublicKey *pucPublicKey,
RSArefPrivateKey *pucPrivateKey);
int saf_get_sdf_session_and_keyindex(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyUsage,
void *phSessionHandle,
unsigned int puiKeyIndex);
int saf_get_sdf_session_and_ecsignkey(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiAlgorithmID, /* SGD_SM2_1 */
void **phSessionhandle,
unsigned int *puiISKIndex);
void saf_release_sdf_session(
void *hSessionHandle);
int saf_get_ec_public_key_from_cert(
unsigned char *pucCertificate,
unsigned int uiCertificateLen,
ECCrefPublicKey *pucPublicKey);

135
crypto/saf/saf_lib.c Normal file
View File

@@ -0,0 +1,135 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <openssl/gmsaf.h>
#include "saf_lcl.h"
//FIXME: use PEM_write_bio_ECPrivateKey in next version
int saf_save_ec_keypair(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyBits,
unsigned int uiKeyUsage,
unsigned int uiExportFlag,
ECCrefPublicKey *pucPublicKey,
ECCrefPrivateKey *pucPrivateKey)
{
return -1;
}
int saf_save_rsa_keypair(void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyBits,
unsigned int uiKeyUsage,
unsigned int uiExportFlag,
RSArefPublicKey *pucPublicKey,
RSArefPrivateKey *pucPrivateKey)
{
return -1;
}
int saf_get_sdf_session_and_keyindex(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyUsage,
void *phSessionHandle,
unsigned int puiKeyIndex)
{
return -1;
}
void saf_release_sdf_session(void *hSessionHandle)
{
}
int saf_get_sdf_session_and_ecsignkey(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiAlgorithmID, /* SGD_SM2_1 */
void **phSessionhandle,
unsigned int *puiISKIndex)
{
return -1;
}
int saf_get_ec_public_key_from_cert(
unsigned char *pucCertificate,
unsigned int uiCertificateLen,
ECCrefPublicKey *pucPublicKey)
{
return -1;
}
static int readfile(const char *file, unsigned char **pout, size_t *len)
{
FILE *fp = fopen(file, "rb");
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *out = malloc(fsize);
fread(out, fsize, 1, f);
fclose(f);
*pout = out;
*len = fsize;
return SAR_OK;
}
static int cert_get_pubkey(
unsigned char *pucCertificate,
unsigned int uiCertificateLen,
unsigned char **pout,
unsigned int *outlen)
{
return 0;
}

147
crypto/saf/saf_mac.c Normal file
View File

@@ -0,0 +1,147 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <openssl/evp.h>
#include <openssl/cmac.h>
#include <openssl/cbcmac.h>
#include <openssl/gmsaf.h>
#include <openssl/gmapi.h>
/* 7.3.45 */
int SAF_MacUpdate(
void *hKeyHandle,
const unsigned char *pucInData,
unsigned int uiInDataLen)
{
int ret = SAR_UnknownErr;
SAF_KEY_HANDLE *hkey = (SAF_KEY_HANDLE *)hKeyHandle;
if (!hKeyHandle || !pucInData) {
SAFerr(SAF_F_SAF_MACUPDATE, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (!hkey->cbcmac_ctx) {
if (!(hkey->cbcmac_ctx = CBCMAC_CTX_new())) {
SAFerr(SAF_F_SAF_MACUPDATE, ERR_R_MALLOC_FAILURE);
goto end;
}
if (!CBCMAC_Init(hkey->cbcmac_ctx, hkey->key, hkey->keylen, hkey->cipher, NULL)) {
SAFerr(SAF_F_SAF_MACUPDATE, SAF_R_CBCMAC_FAILURE);
goto end;
}
}
if (!CBCMAC_Update(hkey->cbcmac_ctx, pucInData, (size_t)uiInDataLen)) {
SAFerr(SAF_F_SAF_MACUPDATE, SAF_R_CBCMAC_FAILURE);
return SAR_UnknownErr;
}
ret = SAR_OK;
end:
if (ret != SAR_OK && hkey->cbcmac_ctx) {
CBCMAC_CTX_free(hkey->cbcmac_ctx);
hkey->cbcmac_ctx = NULL;
}
return ret;
}
/* 7.3.46 */
int SAF_MacFinal(
void *hKeyHandle,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
SAF_KEY_HANDLE *hkey = (SAF_KEY_HANDLE *)hKeyHandle;
size_t siz;
if (!hKeyHandle || !pucOutData || !puiOutDataLen) {
SAFerr(SAF_F_SAF_MACFINAL, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (*puiOutDataLen < EVP_CIPHER_block_size(hkey->cipher)) {
SAFerr(SAF_F_SAF_MACFINAL, SAF_R_BUFFER_TOO_SMALL);
return SAR_IndataLenErr;
}
if (!hkey->cbcmac_ctx) {
SAFerr(SAF_F_SAF_MACFINAL, SAF_R_OPERATION_NOT_INITIALIZED);
return SAR_UnknownErr;
}
siz = EVP_CIPHER_block_size(hkey->cipher);
if (!CBCMAC_Final(hkey->cbcmac_ctx, pucOutData, &siz)) {
SAFerr(SAF_F_SAF_MACFINAL, SAF_R_MAC_FAILURE);
return SAR_UnknownErr;
}
*puiOutDataLen = siz;
return SAR_OK;
}
/* 7.4.44 */
int SAF_Mac(
void *hKeyHandle,
const unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucOutData,
unsigned int *puiOutDataLen)
{
int ret;
if ((ret = SAF_MacUpdate(hKeyHandle, pucInData, uiInDataLen)) != SAR_OK) {
return ret;
}
if ((ret = SAF_MacFinal(hKeyHandle, pucOutData, puiOutDataLen)) != SAR_OK) {
return ret;
}
return SAR_OK;
}

404
crypto/saf/saf_pkcs7.c Normal file
View File

@@ -0,0 +1,404 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <openssl/evp.h>
#include <openssl/gmapi.h>
#include <openssl/gmsaf.h>
#incluce "saf_lcl.h"
/*
In GMAPI we will use private keys handled by ENGINE, the keys in ENGINE
is referenced by ENGINE and key label `key_id`
*/
EVP_PKEY *saf_load_private_key( void *hAppHandle,
unsigned char *containerName, unsigned int containerNameLen,
unsigned int keyUsage)
{
return NULL;
}
int GMAPI_CONTAINER_get_cert_and_key(GMAPI_CONTAINER *container,
int key_usage, X509 **cert, EVP_PKEY **pkey)
{
return 0;
}
/* 7.4.2 */
/* we need AppHandle before doing this
* App + Container + KeyUsage => sign_key
* the private key is referenced by a string label `key_id`
*/
int SAF_Pkcs7_EncodeData(
void *hAppHandle,
unsigned char *pucSignContainerName,
unsigned int uiSignContainerNameLen,
unsigned int uiSignKeyUsage,
unsigned char *pucSignerCertificate,
unsigned int uiSignerCertificateLen,
unsigned int uiDigestAlgorithm,
unsigned char *pucEncCertificate,
unsigned int uiEncCertificateLen,
unsigned char *pucData,
unsigned int uiDataLen,
unsigned char *pucDerP7Data,
unsigned int *puiDerP7DataLen)
{
int ret = SAR_UnknownErr;
PKCS7 *p7 = NULL;
EVP_PKEY *pkey = NULL;
const EVP_MD *md;
p7 = PKCS7_new();
pkey = saf_load_private_key(hAppHandle,
pucSignContainerName, uiSignContainerNameLen
uiSignKeyUsage);
PKCS7_set_type(p7, 0);
return 0;
}
/* 7.4.3 */
int SAF_Pkcs7_DecodeData(
void *hAppHandle)
{
return 0;
}
/* 7.4.4 */
int SAF_Pkcs7_EncodeSignedData(
void *hAppHandle,
unsigned char *pucSignContainerName,
unsigned int uiSignContainerNameLen,
unsigned int uiSignKeyUsage,
unsigned char *pucSignerCertificate,
unsigned int uiSignerCertificateLen,
unsigned int uiDigestAlgorithm,
unsigned char *pucData,
unsigned int uiDataLen,
unsigned char *pucDerP7Data,
unsigned int *puiDerP7DataLen)
{
int flags;
BIO *bio = NULL;
EVP_PKEY *pkey = NULL;
X509 *cert = NULL;
unsigned char *p;
if (!(pkey = saf_load_private_key(hAppHandle, pucSignContainerName,
uiSignContainerNameLen, uiSignKeyUsage))) {
}
/* decode certificate, check no extra input */
p = pucSignerCertificate;
if (!(cert = d2i_X509(NULL, &p, (long)uiSignerCertificateLen))) {
}
if (p - pucSignerCertificate != uiSignerCertificateLen) {
}
/* data bio */
if (!(bio = BIO_new_mem_buf(pucData, (int)uiDataLen))) {
}
/* set digest */
if (!(md = EVP_get_digestbysgd(uiDigestAlgorithm))) {
}
flags = PKCS7_BINARY;
p7 = PKCS7_sign(cert, pkey, NULL, bio, flags);
p = pucDerP7Data;
if (i2d_PKCS7(p7, &p) < 0) {
}
*puiDerP7DataLen = p - pucDerP7Data;
return 0;
}
/* 7.4.5 */
/*
* The content data in PKCS #7 SignedData format is optional, as the
* `SAF_Pkcs7_DecodeSignedData` function has explicit content data input
* with parameter `pucData`, the `SAF_Pkcs7_EncodeSignedData` will not carry
* content data, with the `PKCS7_DETACHED` flag bit set.
*/
int SAF_Pkcs7_DecodeSignedData(
void *hAppHandle,
unsigned char *pucDerP7SignedData,
unsigned int uiDerP7SignedDataLen,
unsigned char *pucSignerCertificate,
unsigned int uiSignerCertificateLen,
unsigned int uiDigestAlgorithm,
unsigned char *pucData,
unsigned int uiDataLen,
unsigned char *pucSign,
unsigned int *puiSignLen)
{
int ret;
PKCS7 *p7 = NULL;
X509 *cert = NULL;
const EVP_MD *md;
BIO *bio = NULL;
STACK_OF(X509) *certs = NULL;
X509_STORE *store = NULL;
int flags = 0;
p = pucDerP7SignedData;
if (!(p7 = d2i_PKCS7(NULL, &p, (long)uiDerP7SignedDataLen))) {
}
if (p - pucDerP7SignedData != uiDerP7SignedDataLen) {
}
p = pucSignerCertificate;
if (!(cert = d2i_X509(NULL, &p, (long)uiSignerCertificateLen))) {
}
if (p - pucSignerCertificate != uiSignerCertificateLen) {
}
if (!(md = EVP_get_digestbysgd(uiDigestAlgorithm))) {
}
if (!PKCS7_set_digest(p7, md)) {
}
if (!PKCS7_verify(p7, cert, store, bio, NULL, flags)) {
}
return 0;
}
/* 7.4.6 */
int SAF_Pkcs7_EncodeEnvelopedData(
void *hAppHandle,
unsigned char *pucData,
unsigned int uiDataLen,
unsigned char *pucEncCertificate,
unsigned int uiEncCertificateLen,
unsigned int uiSymmAlgorithm,
unsigned char *pucDerP7EnvelopedData,
unsigned int *puiDerP7EnvelopedDataLen)
{
int ret = SAR_UnknownErr;
PKCS7 *p7 = NULL;
X509 *cert = NULL;
BIO *bio = NULL;
const EVP_CIPHER *cipher;
int flags;
cipher = EVP_get_cipherbysgd(uiSymmAlgorithm);
bio = BIO_new(BIO_s_mem());
// set data to bio
p = pucEncCertificate;
cert = d2i_X509(NULL, &p, uiEncCertificateLen);
p7 = PKCS7_encrypt(cert, bio, cipher, flags);
end:
PKCS7_free(p7);
return ret;
}
/* 7.4.7 */
/* key is referenced by App.Container.KeyUsage */
int SAF_Pkcs7_DecodeEnvelopedData(
void *hAppHandle,
unsigned char *pucDecContainerName,
unsigned int uiDecContainerNameLen,
unsigned int uiDecKeyUsage,
unsigned char *pucDerP7EnvelopedData,
unsigned int uiDerP7EnvelopedDataLen,
unsigned char *pucData,
unsigned int *puiDataLen)
{
PKCS7 *p7 = NULL;
BIO *bio = NULL;
X509 *cert = NULL;
EVP_PKEY *pkey = NULL;
// get cert and pkey from App.Container.KeyUsage
PKCS7_decrypt(p7, pkey, cert, bio, flags);
return 0;
}
/* 7.4.8 */
/* the `hAppHandle` and key is not required in digest */
int SAF_Pkcs7_EncodeDigestedData(
void *hAppHandle,
unsigned int uiDigestAlgorithm,
unsigned char *pucData,
unsigned int uiDataLen,
unsigned char *pucDerP7DigestedData,
unsigned int *puiDerP7DigestedDataLen)
{
int ret = SAR_UnknownErr;
PKCS7 *p7 = NULL;
BIO *bio = NULL;
const EVP_MD *md;
unsigned char *p;
int len;
if (!hAppHandle || !pucData || !pucDerP7DigestedData || !puiDerP7DigestedDataLen) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_PASSED_NULL_PARAMETER);
return SAR_IndataErr;
}
if (!(md = EVP_get_digestbysgd(uiDigestAlgorithm))) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, SAF_R_INVALID_DIGEST_ALGOR);
return SAR_AlgoTypeErr;
}
if (uiDataLen > INT_MAX) {
return SAR_IndataLenErr;
}
len = (int)uiDataLen;
if (!(p7 = PKCS7_new())) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_MALLOC_FAILURE);
goto end;
}
if (!PKCS7_set_type(p7, NID_pkcs7_digest)) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_PKCS7_LIB);
goto end;
}
/* set digest */
if (!PKCS7_set_digest(p7, md)) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_PKCS7_LIB);
goto end;
}
/* set content */
if (!PKCS7_content_new(p7, NID_pkcs7_data)) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_PKCS7_LIB);
goto end;
}
if (!(bio = PKCS7_dataInit(p7, NULL))) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_PKCS7_LIB);
goto end;
}
if (!BIO_write(bio, pucData, len)) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_GMAPI_LIB);
goto end;
}
if (!BIO_flush(bio)) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_GMAPI_LIB);
goto end;
}
if (!PKCS7_dataFinal(p7, bio)) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_PKCS7_LIB);
goto end;
}
/* check output buffer length */
if ((len = i2d_PKCS7(p7, NULL)) <= 0) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_PKCS7_LIB);
goto end;
}
if (*puiDerP7DigestedDataLen < len) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, SAF_R_BUFFER_TOO_SMALL);
goto end;
}
/* der encoding */
p = pucDerP7DigestedData;
if ((len = i2d_PKCS7(p7, &p)) <= 0) {
SAFerr(SAF_F_SAF_PKCS7_ENCODEDIGESTEDDATA, ERR_R_PKCS7_LIB);
goto end;
}
*puiDerP7DigestedDataLen = (unsigned int)len;
ret = SAR_OK;
end:
PKCS7_free(p7);
return ret;
}
/* 7.4.9 */
/* parse pkcs7 and get data and digest */
int SAF_Pkcs7_DecodeDigestedData(
void *hAppHandle,
unsigned int uiDigestAlgorithm,
unsigned char *pucDerP7DigestedData,
unsigned int uiDerP7DigestedDataLen,
unsigned char *pucData,
unsigned int uiDataLen,
unsigned char *pucDigest,
unsigned int *puiDigestLen)
{
int ret = SAR_UnknownErr;
PKCS7 *p7 = NULL;
unsigned char *p;
long len;
if (!(md = EVP_get_digestbysgd(uiDigestAlgorithm))) {
SAFerr(SAF_F_SAF_PKCS7_DECODEDIGESTEDDATA, SAF_R_INVALID_DIGEST_ALGOR);
return SAR_AlgoTypeErr;
}
p = pucDerP7DigestedData;
len = uiDerP7DigestedDataLen;
if (!(p7 = d2i_PKCS7(NULL, &p, len))) {
goto end;
}
return ret;
}

72
crypto/saf/saf_rand.c Normal file
View File

@@ -0,0 +1,72 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/gmsaf.h>
#include <openssl/gmapi.h>
#include "saf_lcl.h"
/* 7.3.10 */
int SAF_GenRandom(
unsigned int uiRandLen,
unsigned char *pucRand)
{
int len;
if (uiRandLen > 1024 * 1024) {
return SAR_IndataLenErr;
}
len = (int)uiRandLen;
if (!RAND_bytes(pucRand, len)) {
return SAR_GenRandErr;
}
return SAR_OK;
}

246
crypto/saf/saf_rsa.c Normal file
View File

@@ -0,0 +1,246 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <openssl/gmsaf.h>
#include <openssl/gmapi.h>
#include "saf_lcl.h"
/* 7.3.16 */
int SAF_GenRsaKeyPair(void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyBits,
unsigned int uiKeyUsage,
unsigned int uiExportFlag)
{
RSArefPublicKey publicKey;
RSArefPrivateKey privateKey;
if (SDR_OK != SDF_GenerateKeyPair_RSA(
NULL,
uiKeyBits,
&publicKey,
&privateKey)) {
}
if ((ret = saf_save_rsa_keypair(
hAppHandle,
pucContainerName,
uiContainerNameLen,
uiKeyBits,
uiKeyUsage,
uiExportFlag,
&publicKey,
&privateKey))
!= SAR_Ok) {
}
return SAR_NotSupportYetErr;
}
/* 7.3.17 */
int SAF_GetPublicKey(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiKeyUsage,
unsigned char *pucPublicKey,
unsigned int *puiPublicKeyLen)
{
unsigned int uiAlgID;
if (uiAlgID = SGD_RSA) {
if (uiKeyUsage == 1) {
if (SDF_ExportSignPublicKey_RSA(
hSessionHandle,
uiKeyIndex,
(RSArefPublicKey *)pucPublicKey) != SDR_OK) {
}
} else {
if (SDF_ExportEncPublicKey_RSA(
hSessionHandle,
uiKeyIndex,
(RSArefPublicKey *)pucPublicKey) != SDR_OK) {
}
}
*puiPublicKeyLen = (unsigned int)sizeof(RSArefPublicKey);
} else {
if (uiKeyUsage == 1) {
if (SDF_ExportSignPublicKey_ECC(
hSessionHandle,
uiKeyIndex,
(ECCrefPublicKey *)pucPublicKey) != SDR_OK) {
}
} else {
if (SDF_ExportEncPublicKey_ECC(
hSessionHandle,
uiKeyIndex,
(ECCrefPublicKey *)pucPublicKey) != SDR_OK) {
}
}
*puiPublicKeyLen = (unsigned int)sizeof(ECCrefPublicKey);
}
return SAR_NotSupportYetErr;
}
/* 7.3.18 */
/* the `pucInData` is message, not digest */
int SAF_RsaSign(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiHashAlgoType,
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucSignature,
unsigned int *puiSignatureLen)
{
return SAR_NotSupportYetErr;
}
/* 7.3.19 */
int SAF_RsaSignFile(
void *hAppHandle,
unsigned char *pucContainerName,
unsigned int uiContainerNameLen,
unsigned int uiHashAlgoType,
unsigned char *pucFileName,
unsigned char *pucSignature,
unsigned int *puiSignatureLen)
{
int ret;
unsigned char *buf = NULL;
unsigned int buflen;
if ((ret = readfile(pucFileName, &buf, &buflen)) != SAR_OK) {
return ret;
}
if ((ret = SAF_RsaSign(hAppHandle, pucContainerName, uiContainerNameLen,
uiHashAlgoType, buf, buflen, pucSignature, puiSignatureLen)) != SAR_OK) {
OPENSSL_free(buf);
return ret;
}
OPENSSL_free(buf);
return SAR_OK;
}
/* 7.3.20 */
int SAF_RsaVerifySign(
unsigned int uiHashAlgoType,
unsigned char *pucPublicKey,
unsigned int uiPublicKeyLen,
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucSignature,
unsigned int uiSignatureLen)
{
return SAR_NotSupportYetErr;
}
/* 7.3.21 */
int SAF_RsaVerifySignFile(
unsigned int uiHashAlgoType,
unsigned char *pucPublicKey,
unsigned int uiPublicKeyLen,
unsigned char *pucFileName,
unsigned char *pucSignature,
unsigned int uiSignatureLen)
{
int ret;
unsigned char *buf = NULL;
unsigned int buflen;
if ((ret = readfile(pucFileName, &buf, &buflen)) != SAR_OK) {
return ret;
}
if ((ret = SAF_RsaVerifySign(uiHashAlgoType, pucPublicKey, uiPublicKeyLen,
buf, buflen, pucSignature, puiSignatureLen)) != SAR_OK) {
OPENSSL_free(buf);
return ret;
}
OPENSSL_free(buf);
return SAR_OK;
}
/* 7.3.22 */
int SAF_VerifySignByCert(
unsigned int uiHashAlgoType,
unsigned char *pucCertificate,
unsigned int uiCertificateLen,
unsigned char *pucInData,
unsigned int uiInDataLen,
unsigned char *pucSignature,
unsigned int uiSignatureLen)
{
int ret;
unsigned char *buf = NULL;
unsigned int buflen;
if ((ret = cert_get_pubkey(pucCertificate, uiCertificateLen, &buf, &buflen)) != SAR_OK) {
return ret;
}
if ((ret = SAF_RsaVerifySign(uiHashAlgoType, pucPublicKey, uiPublicKeyLen,
buf, buflen, pucSignature, puiSignatureLen)) != SAR_OK) {
OPENSSL_free(buf);
return ret;
}
OPENSSL_free(buf);
return SAR_OK;
}

255
crypto/saf/saf_sm2.c Normal file
View File

@@ -0,0 +1,255 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <openssl/evp.h>
#include <openssl/gmapi.h>
#include <openssl/gmsaf.h>
#include "saf_lcl.h"
/* 7.4.10 */
int SAF_SM2_EncodeSignedAndEnvelopedData(
void *hAppHandle,
unsigned char *pucSignContainerName,
unsigned int uiSignContainerNameLen,
unsigned int uiSignKeyUsage,
unsigned char *pucSignerCertificate,
unsigned int uiSignerCertificateLen,
unsigned int uiDigestAlgorithm,
unsigned char *pucEncCertificate,
unsigned int uiEncCertificateLen,
unsigned int uiSymmAlgorithm,
unsigned char *pucData,
unsigned int uiDataLen,
unsigned char *pucDerSignedAndEnvelopedData,
unsigned int *puiDerSignedAndEnvelopedDataLen)
{
int ret = SAR_UnknownErr;
PKCS7 *p7 = NULL;
EVP_PKEY *pkey = NULL;
const EVP_MD *md;
p7 = PKCS7_new();
pkey = saf_load_private_key(hAppHandle,
pucSignContainerName, uiSignContainerNameLen
uiSignKeyUsage);
PKCS7_set_type(p7, 0);
return 0;
}
/* 7.4.11 */
int SAF_SM2_DecodeSignedAndEnvelopedData(
void *hAppHandle,
unsigned char *pucDerContainerName,
unsigned int uiDerContainerNameLen,
unsigned int uiDecKeyUsage,
unsigned char *pucDerSignedAndEnvelopedData,
unsigned int uiDerSignedAndEnvelopedDataLen,
unsigned char *pucData,
unsigned int *puiDataLen,
unsigned char *pucSignerCertificate,
unsigned int *puiSignerCertificateLen,
unsigned int *puiDigestAlgorithms)
{
return 0;
}
/* 7.4.12 */
int SAF_SM2_EncodeSignedData(
void *hAppHandle,
unsigned char *pucSignContainerName,
unsigned int uiSignContainerNameLen,
unsigned int uiSignKeyUsage,
unsigned char *pucSignerCertificate,
unsigned int uiSignerCertificateLen,
unsigned int uiDigestAlgorithm,
unsigned char *pucData,
unsigned int uiDataLen,
unsigned char *pucDerSignedData,
unsigned int *puiDerSignedDataLen)
{
int flags;
BIO *bio = NULL;
EVP_PKEY *pkey = NULL;
X509 *cert = NULL;
unsigned char *p;
if (!(pkey = saf_load_private_key(hAppHandle, pucSignContainerName,
uiSignContainerNameLen, uiSignKeyUsage))) {
}
/* decode certificate, check no extra input */
p = pucSignerCertificate;
if (!(cert = d2i_X509(NULL, &p, (long)uiSignerCertificateLen))) {
}
if (p - pucSignerCertificate != uiSignerCertificateLen) {
}
/* data bio */
if (!(bio = BIO_new_mem_buf(pucData, (int)uiDataLen))) {
}
/* set digest */
if (!(md = EVP_get_digestbysgd(uiDigestAlgorithm))) {
}
flags = PKCS7_BINARY;
p7 = PKCS7_sign(cert, pkey, NULL, bio, flags);
p = pucDerP7Data;
if (i2d_PKCS7(p7, &p) < 0) {
}
*puiDerP7DataLen = p - pucDerP7Data;
return 0;
}
/* 7.4.13 */
int SAF_SM2_DecodeSignedData(
void *hAppHandle,
unsigned char *pucDerSignedData,
unsigned int uiDerSignedDataLen,
unsigned char *pucSignerCertificate,
unsigned int uiSignerCertificateLen,
unsigned int uiDigestAlgorithm,
unsigned char *pucData,
unsigned int uiDataLen,
unsigned char *pucSign,
unsigned int *puiSignLen)
{
int ret;
PKCS7 *p7 = NULL;
X509 *cert = NULL;
const EVP_MD *md;
BIO *bio = NULL;
STACK_OF(X509) *certs = NULL;
X509_STORE *store = NULL;
int flags = 0;
p = pucDerP7SignedData;
if (!(p7 = d2i_PKCS7(NULL, &p, (long)uiDerP7SignedDataLen))) {
}
if (p - pucDerP7SignedData != uiDerP7SignedDataLen) {
}
p = pucSignerCertificate;
if (!(cert = d2i_X509(NULL, &p, (long)uiSignerCertificateLen))) {
}
if (p - pucSignerCertificate != uiSignerCertificateLen) {
}
if (!(md = EVP_get_digestbysgd(uiDigestAlgorithm))) {
}
if (!PKCS7_set_digest(p7, md)) {
}
if (!PKCS7_verify(p7, cert, store, bio, NULL, flags)) {
}
return 0;
}
/* 7.4.14 */
int SAF_SM2_EncodeEnvelopedData(
void *hAppHandle,
unsigned char *pucData,
unsigned int uiDataLen,
unsigned char *pucEncCertificate,
unsigned int uiEncCertificateLen,
unsigned int uiSymmAlgorithm,
unsigned char *pucDerEnvelopedData,
unsigned int *puiDerEnvelopedDataLen)
{
int ret = SAR_UnknownErr;
PKCS7 *p7 = NULL;
X509 *cert = NULL;
BIO *bio = NULL;
const EVP_CIPHER *cipher;
int flags;
cipher = EVP_get_cipherbysgd(uiSymmAlgorithm);
bio = BIO_new(BIO_s_mem());
// set data to bio
p = pucEncCertificate;
cert = d2i_X509(NULL, &p, uiEncCertificateLen);
p7 = PKCS7_encrypt(cert, bio, cipher, flags);
end:
PKCS7_free(p7);
return ret;
}
/* 7.4.15 */
int SAF_SM2_DecodeEnvelopedData(
void *hAppHandle,
unsigned char *pucDecContainerName,
unsigned int uiDecContainerNameLen,
unsigned int uiDecKeyUsage,
unsigned char *pucDerEnvelopedData,
unsigned int uiDerEnvelopedDataLen,
unsigned char *pucData,
unsigned int *puiDataLen)
{
PKCS7 *p7 = NULL;
BIO *bio = NULL;
X509 *cert = NULL;
EVP_PKEY *pkey = NULL;
// get cert and pkey from App.Container.KeyUsage
PKCS7_decrypt(p7, pkey, cert, bio, flags);
return 0;
}

144
crypto/saf/saf_symmkeyobj.c Normal file
View File

@@ -0,0 +1,144 @@
/* ====================================================================
* Copyright (c) 2016 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES
* LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
#include <limits.h>
#include <openssl/evp.h>
#include <openssl/gmsaf.h>
#include <openssl/gmapi.h>
#include "saf_lcl.h"
/* 7.3.30
* All symmetric keys in GMAPI are session objects.
* The `SymmKeyObj` is a EVP_CIPHER_CTX
*/
int SAF_CreateSymmKeyObj(
void *hAppHandle,
void **phSymmKeyObj,
unsigned char *pucContainerName,
unsigned int uiContainerLen,
unsigned char *pucIV,
unsigned int uiIVLen,
unsigned int uiEncOrDec,
unsigned int uiCryptoAlgID)
{
int ret = SAR_UnknownErr;
SAF_SymmKeyObj *obj = NULL;
/* check arguments */
if (!hAppHandle || !phSymmKeyObj || !pucContainerName || !pucIV) {
SAFerr(SAF_F_SAF_CREATESYMMKEYOBJ,
ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (uiContainerLen > INT_MAX) {
SAFerr(SAF_F_SAF_CREATESYMMKEYOBJ,
SAF_R_INVALID_INPUT_LENGTH);
return -1;
}
if (uiIVLen > EVP_MAX_IV_LENGTH) {
SAFerr(SAF_F_SAF_CREATESYMMKEYOBJ,
SAF_R_INVALID_INPUT_LENGTH);
return -1;
}
/* init object */
if (!(obj = OPENSSL_zalloc(sizeof(*obj)))) {
SAFerr(SAF_F_SAF_CREATESYMMKEYOBJ,
ERR_R_MALLOC_FAILURE);
goto end;
}
obj->hAppHandle = hAppHandle;
if (!(obj->pucContainerName = OPENSSL_memdup(pucContainerName,
(size_t)uiContainerLen))) {
SAFerr(SAF_F_SAF_CREATESYMMKEYOBJ,
ERR_R_MALLOC_FAILURE);
goto end;
}
if (!(obj->pucIV = OPENSSL_memdup(pucIV, (size_t)uiIVLen))) {
SAFerr(SAF_F_SAF_CREATESYMMKEYOBJ,
ERR_R_MALLOC_FAILURE);
goto end;
}
obj->uiEncOrDec = uiEncOrDec;
if (!EVP_get_cipherbysgd(uiCryptoAlgID)) {
SAFerr(SAF_F_SAF_CREATESYMMKEYOBJ,
SAF_R_INVALID_ALGOR);
goto end;
}
obj->uiCryptoAlgID = uiCryptoAlgID;
/* set output */
*phSymmKeyObj = obj;
obj = NULL;
ret = SAR_OK;
end:
(void)SAF_DestroySymmAlgoObj(obj);
return ret;
}
/* 7.3.36 */
int SAF_DestroySymmAlgoObj(
void *hSymmKeyObj)
{
SAF_SymmKeyObj *obj = (SAF_SymmKeyObj *)hSymmKeyObj;
if (!hSymmKeyObj) {
return SAR_OK;
}
OPENSSL_free(obj->pucContainerName);
OPENSSL_free(obj->pucIV);
memset(obj, 0, sizeof(*obj));
return SAR_OK;
}