/* * Do an RSA operation to sign the message digest */ int rsa_pkcs1_sign( rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, int hash_id, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { switch( ctx->padding ) { case RSA_PKCS_V15: return rsa_rsassa_pkcs1_v15_sign( ctx, mode, hash_id, hashlen, hash, sig ); #if defined(POLARSSL_PKCS1_V21) case RSA_PKCS_V21: return rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, hash_id, hashlen, hash, sig ); #endif default: return( POLARSSL_ERR_RSA_INVALID_PADDING ); } }
int Crypto::SignRsa2048Sha256(const u8 modulus[kRsa2048Size], const u8 private_exponent[kRsa2048Size], const u8 hash[kSha256HashLen], u8 signature[kRsa2048Size]) { int ret; rsa_context ctx; rsa_init(&ctx, RSA_PKCS_V15, 0); ctx.len = kRsa2048Size; mpi_read_binary(&ctx.D, private_exponent, ctx.len); mpi_read_binary(&ctx.N, modulus, ctx.len); ret = rsa_rsassa_pkcs1_v15_sign(&ctx, RSA_PRIVATE, SIG_RSA_SHA256, kSha256HashLen, hash, signature); rsa_free(&ctx); return ret; }
int EsSign::RsaSign(EsSignType type, const u8* hash, const u8* modulus, const u8* priv_exp, u8* signature) { int ret; rsa_context rsa; int hash_id = 0; int hash_len = 0; rsa_init(&rsa, RSA_PKCS_V15, hash_id); if (hash == NULL || modulus == NULL || priv_exp == NULL || signature == NULL) return 1; switch (type) { case(ES_SIGN_RSA4096_SHA1) : case(ES_SIGN_RSA4096_SHA256) : { rsa.len = Crypto::kRsa4096Size; hash_id = (type == ES_SIGN_RSA4096_SHA1) ? SIG_RSA_SHA1 : SIG_RSA_SHA256; hash_len = (type == ES_SIGN_RSA4096_SHA1) ? Crypto::kSha1HashLen : Crypto::kSha256HashLen; memset(signature, 0, sizeof(kRsa4096SignLen)); break; } case(ES_SIGN_RSA2048_SHA1) : case(ES_SIGN_RSA2048_SHA256) : { rsa.len = Crypto::kRsa2048Size; hash_id = (type == ES_SIGN_RSA2048_SHA1) ? SIG_RSA_SHA1 : SIG_RSA_SHA256; hash_len = (type == ES_SIGN_RSA2048_SHA1) ? Crypto::kSha1HashLen : Crypto::kSha256HashLen; memset(signature, 0, sizeof(kRsa2048SignLen)); break; } default: return 1; } mpi_read_binary(&rsa.D, priv_exp, rsa.len); mpi_read_binary(&rsa.N, modulus, rsa.len); // set signature id *((u32*)(signature)) = be_word(type); ret = rsa_rsassa_pkcs1_v15_sign(&rsa, RSA_PRIVATE, hash_id, hash_len, hash, (signature + 4)); rsa_free(&rsa); return ret; }
int RsaSignVerify(void *data, u64 len, u8 *sign, u8 *mod, u8 *priv_exp, u32 sig_type, u8 rsa_mode) { int rsa_result = 0; rsa_context ctx; u8 hash[HASH_MAX_LEN]; if(!RsaKeyInit(&ctx, mod, priv_exp, (u8*)RSA_PUB_EXP, GetRsaType(sig_type))) return -1; if(!CalcHashForSign(data, len, hash, sig_type)) return -1; if(rsa_mode == CTR_RSA_VERIFY) rsa_result = rsa_pkcs1_verify(&ctx, RSA_PUBLIC, GetRsaHashType(sig_type), 0, hash, sign); else // CTR_RSA_SIGN rsa_result = rsa_rsassa_pkcs1_v15_sign(&ctx, RSA_PRIVATE, GetRsaHashType(sig_type), 0, hash, sign); rsa_free(&ctx); return rsa_result; }