/************************************************************************** * VERIFY SIGNATURE **************************************************************************/ int lib_verify (uchar* data_buf, uint32 data_len, uchar* sig_buf, uint32 sig_len) { if (RSA_KEY_LEN != sig_len) { SMSG(true,"signature length is wrong (%d)\n",sig_len); goto _err; } SMSG(true,"[%s] 0x%x,0x%x,0x%x,0x%x\n",MOD,data_buf[0],data_buf[1],data_buf[2],data_buf[3]); /* hash the plain text */ sha1(data_buf, data_len, sha1sum); /* verify this signature */ SMSG(true,"[%s] verify signature",MOD); if( rsa_verify( &rsa, HASH_LEN, sha1sum, sig_buf ) != 0 ) { SMSG(true, " ... failed\n" ); goto _err; } SMSG(true," ... pass\n"); return 0; _err: return -1; }
static ssh_key *rsa2_new_priv(const ssh_keyalg *self, ptrlen pub, ptrlen priv) { BinarySource src[1]; ssh_key *sshk; RSAKey *rsa; sshk = rsa2_new_pub(self, pub); if (!sshk) return NULL; rsa = container_of(sshk, RSAKey, sshk); BinarySource_BARE_INIT_PL(src, priv); rsa->private_exponent = get_mp_ssh2(src); rsa->p = get_mp_ssh2(src); rsa->q = get_mp_ssh2(src); rsa->iqmp = get_mp_ssh2(src); if (get_err(src) || !rsa_verify(rsa)) { rsa2_freekey(&rsa->sshk); return NULL; } return &rsa->sshk; }
/** \ingroup Core_Signature \brief Checks a signature \param hash Signature Hash to be checked \param length Signature Length \param sig The Signature to be checked \param signer The signer's public key \return 1 if good; else 0 */ unsigned pgp_check_sig(const uint8_t *hash, unsigned length, const pgp_sig_t * sig, const pgp_pubkey_t * signer) { unsigned ret; if (pgp_get_debug_level(__FILE__)) { hexdump(stdout, "hash", hash, length); } ret = 0; switch (sig->info.key_alg) { case PGP_PKA_DSA: ret = pgp_dsa_verify(hash, length, &sig->info.sig.dsa, &signer->key.dsa); break; case PGP_PKA_RSA: ret = rsa_verify(sig->info.hash_alg, hash, length, &sig->info.sig.rsa, &signer->key.rsa); break; default: (void) fprintf(stderr, "pgp_check_sig: unusual alg\n"); ret = 0; } return ret; }
void check_rw_signature(void) { struct sha256_ctx ctx; int good, res; uint8_t *hash; uint32_t *rsa_workbuf; /* Only the Read-Only firmware needs to do the signature check */ if (system_get_image_copy() != SYSTEM_IMAGE_RO) return; /* Check if we have a RW firmware flashed */ if (*rw_rst == 0xffffffff) return; CPRINTS("Verifying RW image..."); /* Large buffer for RSA computation : could be re-use afterwards... */ res = shared_mem_acquire(3 * RSANUMBYTES, (char **)&rsa_workbuf); if (res) { CPRINTS("No memory for RW verification"); return; } /* SHA-256 Hash of the RW firmware */ /* TODO(crosbug.com/p/44803): Do we have to hash the whole region? */ SHA256_init(&ctx); SHA256_update(&ctx, (void *)CONFIG_PROGRAM_MEMORY_BASE + CONFIG_RW_MEM_OFF, CONFIG_RW_SIZE - CONFIG_RW_SIG_SIZE); hash = SHA256_final(&ctx); good = rsa_verify((const struct rsa_public_key *)CONFIG_RO_PUBKEY_ADDR, (const uint8_t *)CONFIG_RW_SIG_ADDR, hash, rsa_workbuf); if (good) { CPRINTS("RW image verified"); /* Jump to the RW firmware */ system_run_image_copy(SYSTEM_IMAGE_RW); } else { CPRINTS("RSA verify FAILED"); pd_log_event(PD_EVENT_ACC_RW_FAIL, 0, 0, NULL); /* RW firmware is invalid : do not jump there */ if (system_is_locked()) system_disable_jump(); } shared_mem_release(rsa_workbuf); }
static int check_rw_valid(void) { int good; /* Check if we have a RW firmware flashed */ if (*rw_rst == 0xffffffff) return 0; good = rsa_verify(&pkey, (void *)rw_sig, (void *)rw_hash, rsa_workbuf); if (!good) { debug_printf("RSA verify FAILED\n"); return 0; } return 1; }
static int check_rw_valid(void *rw_hash) { int good; /* Check if we have a RW firmware flashed */ if (*rw_rst == 0xffffffff) return 0; good = rsa_verify(&pkey, (void *)rw_sig, rw_hash, rsa_workbuf); if (!good) { debug_printf("RSA FAILED\n"); pd_log_event(PD_EVENT_ACC_RW_FAIL, 0, 0, NULL); return 0; } return 1; }
static void *rsa2_createkey(unsigned char *pub_blob, int pub_len, unsigned char *priv_blob, int priv_len) { struct RSAKey *rsa; char *pb = (char *) priv_blob; rsa = rsa2_newkey((char *) pub_blob, pub_len); rsa->private_exponent = getmp(&pb, &priv_len); rsa->p = getmp(&pb, &priv_len); rsa->q = getmp(&pb, &priv_len); rsa->iqmp = getmp(&pb, &priv_len); if (!rsa_verify(rsa)) { rsa2_freekey(rsa); return NULL; } return rsa; }
static void RSATest(void) { char modulus_str[] = "ce812d6f1979ed7839b895d4b4b034319a630213b4b4528a0100f6ef961ffd050c775e9e9ebc9ca09d422c948d63698acf3f7c3615eb2cceac2c46bdfc8016c1988803ebdd5177ade1195c5caa6630ab2c8708e9cd430aedba92b26ba52e18e4e1b6c4f429dfa53c20c7b756f9622beb40c00e481e1dcdf0afa5e83ca7e4e443"; char signature_str[] = "c70bf6a79679af36ca72b7f6a9ce3b7a669860e22dffbcd6fe3075fab07e0ba6eb68f620653ba17144c431d9fa527f40ba5c83cf6b4154ae4ff9e604a2b74d8f4fb2f57a9a190ce3916e6176dbfb045485ad05109cc6ae7423900e12ccdc6dbd76e6e094e94543609c0427527ca7fa5fe5928f86053e05c419cd52cea7573596"; char digest_str[] = "026946989674B77821CE9EBCB0F66445ACC6A154"; BI *signature, *pub_exp, *modulous, *res; printk("signature: %s\n", signature_str); printk("original checksum: %s\n", digest_str); // Note: public exponent is always 65537 signature = InPutFromStr(signature_str, HEX); pub_exp = move_p(65537); modulous = InPutFromStr(modulus_str, HEX); res = init_BI(); rsa_verify(signature, pub_exp, modulous, res); printk("recovered checksum:"); dump_bi(res); free_BI(signature); free_BI(pub_exp); free_BI(modulous); free_BI(res); /* BI* signature = move_p(65537); BI* pub_exp = move_p(3); BI* res = NULL; printk("--------------start mod--------------\n"); res = Mod(signature, pub_exp); printk("--------------stop mode--------------\n"); free_BI(signature); free_BI(pub_exp); free_BI(res); */ }
int rsa_verify_sig(char *sig, int sig_size, u8 *sha1) { MPI public_key[2]; MPI hash; MPI data; int nread; int nframe; if (!rsa_key) { return -EINVAL; } /* initialize our keys */ nread = rsa_key->n_size; public_key[0] = mpi_read_from_buffer((byte *)rsa_key->n, &nread, 0); if (!public_key[0]) { return -EINVAL; } nread = rsa_key->e_size; public_key[1] = mpi_read_from_buffer((byte *)rsa_key->e, &nread, 0); if (!public_key[1]) { return -EINVAL; } /* set up the MPI for the sig */ data = mpi_read_from_buffer(sig, &sig_size, 0); if (!data) { return -EINVAL; } /* set up the MPI for the result */ nframe = mpi_get_nbits(public_key[0]); hash = do_encode_md(sha1, nframe); /* verify the sig */ return rsa_verify(hash, &data, public_key); }
static ssh_key *rsa2_new_priv_openssh(const ssh_keyalg *self, BinarySource *src) { RSAKey *rsa; rsa = snew(RSAKey); rsa->sshk.vt = &ssh_rsa; rsa->comment = NULL; rsa->modulus = get_mp_ssh2(src); rsa->exponent = get_mp_ssh2(src); rsa->private_exponent = get_mp_ssh2(src); rsa->iqmp = get_mp_ssh2(src); rsa->p = get_mp_ssh2(src); rsa->q = get_mp_ssh2(src); if (get_err(src) || !rsa_verify(rsa)) { rsa2_freekey(&rsa->sshk); return NULL; } return &rsa->sshk; }
int verifyMsg(struct Msg *msg, char *privKeyFile, char *pubKeyFile) { //get key char *encKey = msg->pke; char *key = rsa_decrypt(encKey, privKeyFile); //decrypt the message char *enc = msg->enc; char *text = des_decrypt( key, enc, msg->encLen); //divide message into x and signiture int xLen = msg->xLen; int sigLen = msg->sigLen; char x[xLen+1]; char sig[sigLen+1]; memcpy( x, text, xLen ); x[xLen] = '\0'; text = text+xLen; memcpy( sig, text, sigLen ); sig[sigLen] ='\0'; //verify signiture int result = rsa_verify(x, sig, pubKeyFile, sigLen); return result; }
static int repo_archive_extract_file(int fd, const char *file, const char *dest, const char *repokey, int dest_fd) { struct archive *a = NULL; struct archive_entry *ae = NULL; unsigned char *sig = NULL; int siglen = 0, ret, rc = EPKG_OK; a = archive_read_new(); archive_read_support_filter_all(a); archive_read_support_format_tar(a); /* Seek to the begin of file */ (void)lseek(fd, 0, SEEK_SET); archive_read_open_fd(a, fd, 4096); while (archive_read_next_header(a, &ae) == ARCHIVE_OK) { if (strcmp(archive_entry_pathname(ae), file) == 0) { if (dest_fd == -1) { archive_entry_set_pathname(ae, dest); /* * The repo should be owned by root and not writable */ archive_entry_set_uid(ae, 0); archive_entry_set_gid(ae, 0); archive_entry_set_perm(ae, 0644); if (archive_read_extract(a, ae, EXTRACT_ARCHIVE_FLAGS) != 0) { pkg_emit_errno("archive_read_extract", "extract error"); rc = EPKG_FATAL; goto cleanup; } } else { if (archive_read_data_into_fd(a, dest_fd) != 0) { pkg_emit_errno("archive_read_extract", "extract error"); rc = EPKG_FATAL; goto cleanup; } (void)lseek(dest_fd, 0, SEEK_SET); } } if (strcmp(archive_entry_pathname(ae), "signature") == 0) { siglen = archive_entry_size(ae); sig = malloc(siglen); archive_read_data(a, sig, siglen); } } if (repokey != NULL) { if (sig != NULL) { ret = rsa_verify(dest, repokey, sig, siglen - 1, dest_fd); if (ret != EPKG_OK) { pkg_emit_error("Invalid signature, " "removing repository."); if (dest != NULL) unlink(dest); free(sig); rc = EPKG_FATAL; goto cleanup; } free(sig); } else { pkg_emit_error("No signature found in the repository. " "Can not validate against %s key.", repokey); rc = EPKG_FATAL; if (dest != NULL) unlink(dest); goto cleanup; } } cleanup: if (a != NULL) archive_read_free(a); return rc; }
int digsig_rsa_bsign_verify(unsigned char *hash_format, int length, unsigned char *signed_hash) { int rc = 0, cmp; MPI hash, data; unsigned nread = DIGSIG_ELF_SIG_SIZE; int nframe; unsigned char sig_class; unsigned char sig_timestamp[SIZEOF_UNSIGNED_INT]; int i; SIGCTX *ctx = NULL; unsigned char *new_sig; new_sig = kmalloc(gDigestLength[HASH_SHA1], DIGSIG_SAFE_ALLOC); if (!new_sig) { DSM_ERROR ("kmalloc failed in %s for new_sig\n", __FUNCTION__); return -ENOMEM; } /* Get MPI of signed data from .sig file/section */ nread = DIGSIG_ELF_SIG_SIZE; data = mpi_read_from_buffer(signed_hash + DIGSIG_RSA_DATA_OFFSET, &nread, 0); if (!data) { kfree(new_sig); return -EINVAL; } /* Get MPI for hash */ /* bsign modif - file hash - gpg modif */ /* bsign modif: add bsign greet at beginning */ /* gpg modif: add class and timestamp at end */ ctx = kmalloc(sizeof(SIGCTX), GFP_KERNEL); if (!ctx) { DSM_ERROR("Cannot allocate ctx\n"); mpi_free (data); kfree (new_sig); return -ENOMEM; } ctx->tvmem = kmalloc(TVMEMSIZE, GFP_KERNEL); if (!ctx->tvmem) { kfree (ctx); mpi_free(data); kfree (new_sig); DSM_ERROR("Cannot allocate plaintext buffer\n"); return -ENOMEM; } digsig_sha1_init(ctx); sig_class = signed_hash[DIGSIG_RSA_CLASS_OFFSET]; sig_class &= 0xff; for (i = 0; i < SIZEOF_UNSIGNED_INT; i++) { sig_timestamp[i] = signed_hash[DIGSIG_RSA_TIMESTAMP_OFFSET + i] & 0xff; } digsig_sha1_update(ctx, DIGSIG_BSIGN_STRING, DIGSIG_BSIGN_GREET_SIZE); digsig_sha1_update(ctx, hash_format, SHA1_DIGEST_LENGTH); digsig_sha1_update(ctx, &sig_class, 1); digsig_sha1_update(ctx, sig_timestamp, SIZEOF_UNSIGNED_INT); if ((rc = digsig_sha1_final(ctx, new_sig)) < 0) { DSM_ERROR ("internal_rsa_verify_final Cannot finalize hash algorithm\n"); mpi_free(data); kfree(ctx->tvmem); kfree(ctx); return rc; } nframe = mpi_get_nbits(digsig_public_key[0]); hash = do_encode_md(new_sig, nframe); if (hash == MPI_NULL) { DSM_PRINT(DEBUG_SIGN, "mpi creation failed\\n"); } /* Do RSA verification */ cmp = rsa_verify(hash, &data, digsig_public_key); rc = cmp ? -EPERM : 0; mpi_free(hash); mpi_free(data); kfree(ctx->tvmem); kfree(ctx); kfree (new_sig); return rc; }
std::string rsa_verify_file(const char* file){ std::ifstream in(file,std::ios::in|std::ios::binary); in.seekg(4,std::ios::beg); unsigned char* encrypted=new unsigned char[RSA_KEY_BYTES]; in.read((char*)encrypted,RSA_KEY_BYTES); unsigned int hashlen=102400; in.seekg(0,std::ios::end); unsigned int totallen=int(in.tellg())-260; if(totallen<hashlen){ hashlen=totallen; } in.seekg(256+4,std::ios_base::beg); unsigned char* hashmake=new unsigned char[hashlen]; in.read((char*)hashmake,hashlen); MD5 md5checksumB(hashmake,hashlen); unsigned char* hexx=new unsigned char[33]; hexx=(unsigned char*)md5checksumB.hex_digest(); in.close(); unsigned char* resulth; unsigned char public_exponent[RSA_KEY_BYTES]; //[]={'0xFF','0xFF','0x01'}; for(int i=0; i<(RSA_KEY_BYTES-3); i++){public_exponent[i]=0;} public_exponent[RSA_KEY_BYTES-3]=0x01; //65536 public_exponent[RSA_KEY_BYTES-2]=0x00; //0 public_exponent[RSA_KEY_BYTES-1]=0x01; //1 int size_s=rsa_verify(&resulth,encrypted,public_exponent,user_public_modulus,RSA_KEY_BYTES); if(size_s!=32){ std::ostringstream tos; tos << size_s; return "invalid key"; } for(int i=0; i<32; i++){ if(hexx[i]!=resulth[i]){ std::ostringstream t; t << i; return "invalid key"; } } delete[] encrypted; delete[] hashmake; delete[] hexx; return ""; }
/************************************************************************** * SIGNING **************************************************************************/ int lib_sign(uchar* data_buf, uint32 data_len, uchar* sig_buf, uint32 sig_len) { #if 0 int i = 0; if (RSA_KEY_LEN != sig_len) { SMSG(true,"signature length is wrong (%d)\n",sig_len); goto _err; } /* hash the plain text */ sha1(data_buf, data_len, sha1sum ); /* 2011.09.27. Add OpenSSL compatibility support OpenSSL's command : openssl rsautl -sign -in xxxxx -inkey xxx.pem -out signature RSA padding type : SIG_RSA_SHA1 original implementation for W1126 and W1132 MP release This padding rule can't be compatible with OpenSSL The cipher results are not the same RSA padding type : SIG_RSA_RAW This padding rule can be compatible with OpenSSL The cipher results are the same */ /* encrypt the hash value (sign) */ SMSG(true,"[%s] RSA padding : RAW \n",MOD); if( rsa_sign( &rsa, HASH_LEN, sha1sum, sig_buf ) != 0 ) { SMSG(true, "failed\n" ); goto _err; } SMSG(true,"[%s] sign image ... pass\n\n",MOD); /* output signature */ SMSG(true,"[%s] output signature: \n",MOD); SMSG(true," ------------------------------------\n"); for(i=0;i<RSA_KEY_LEN;i++) { if(i==RSA_KEY_LEN-1) { if(sig_buf[i]<0x10) { SMSG(true,"0x0%x",sig_buf[i]); } else { SMSG(true,"0x%x",sig_buf[i]); } } else { if(sig_buf[i]<0x10) { SMSG(true,"0x0%x,",sig_buf[i]); } else { SMSG(true,"0x%x,",sig_buf[i]); } } } SMSG(true,"\n"); /* self testing : verify this signature */ SMSG(true,"\n[%s] verify signature",MOD); if( rsa_verify( &rsa, HASH_LEN, sha1sum, sig_buf ) != 0 ) { SMSG(true, "failed\n" ); goto _err; } SMSG(true,"... pass\n"); #endif return 0; #if 0 _err: return -1; #endif }
int pkg_update(const char *name, const char *packagesite, bool force) { char url[MAXPATHLEN]; struct archive *a = NULL; struct archive_entry *ae = NULL; char repofile[MAXPATHLEN]; char repofile_unchecked[MAXPATHLEN]; char tmp[MAXPATHLEN]; const char *dbdir = NULL; const char *repokey; unsigned char *sig = NULL; int siglen = 0; int fd, rc = EPKG_FATAL, ret; struct stat st; time_t t = 0; sqlite3 *sqlite; char *archreq = NULL; const char *myarch; int64_t res; const char *tmpdir; snprintf(url, MAXPATHLEN, "%s/repo.txz", packagesite); tmpdir = getenv("TMPDIR"); if (tmpdir == NULL) tmpdir = "/tmp"; strlcpy(tmp, tmpdir, sizeof(tmp)); strlcat(tmp, "/repo.txz.XXXXXX", sizeof(tmp)); fd = mkstemp(tmp); if (fd == -1) { pkg_emit_error("Could not create temporary file %s, " "aborting update.\n", tmp); return (EPKG_FATAL); } if (pkg_config_string(PKG_CONFIG_DBDIR, &dbdir) != EPKG_OK) { pkg_emit_error("Cant get dbdir config entry"); return (EPKG_FATAL); } snprintf(repofile, sizeof(repofile), "%s/%s.sqlite", dbdir, name); if (force) t = 0; /* Always fetch */ else { if (stat(repofile, &st) != -1) { t = st.st_mtime; /* add 1 minute to the timestamp because * repo.sqlite is always newer than repo.txz, * 1 minute should be enough. */ t += 60; } } rc = pkg_fetch_file_to_fd(url, fd, t); close(fd); if (rc != EPKG_OK) { goto cleanup; } if (eaccess(repofile, W_OK) == -1) { pkg_emit_error("Insufficient privilege to update %s\n", repofile); rc = EPKG_ENOACCESS; goto cleanup; } a = archive_read_new(); archive_read_support_compression_all(a); archive_read_support_format_tar(a); archive_read_open_filename(a, tmp, 4096); while (archive_read_next_header(a, &ae) == ARCHIVE_OK) { if (strcmp(archive_entry_pathname(ae), "repo.sqlite") == 0) { snprintf(repofile_unchecked, sizeof(repofile_unchecked), "%s.unchecked", repofile); archive_entry_set_pathname(ae, repofile_unchecked); /* * The repo should be owned by root and not writable */ archive_entry_set_uid(ae, 0); archive_entry_set_gid(ae, 0); archive_entry_set_perm(ae, 0644); archive_read_extract(a, ae, EXTRACT_ARCHIVE_FLAGS); } if (strcmp(archive_entry_pathname(ae), "signature") == 0) { siglen = archive_entry_size(ae); sig = malloc(siglen); archive_read_data(a, sig, siglen); } } if (pkg_config_string(PKG_CONFIG_REPOKEY, &repokey) != EPKG_OK) { free(sig); return (EPKG_FATAL); } if (repokey != NULL) { if (sig != NULL) { ret = rsa_verify(repofile_unchecked, repokey, sig, siglen - 1); if (ret != EPKG_OK) { pkg_emit_error("Invalid signature, " "removing repository.\n"); unlink(repofile_unchecked); free(sig); rc = EPKG_FATAL; goto cleanup; } free(sig); } else { pkg_emit_error("No signature found in the repository. " "Can not validate against %s key.", repokey); rc = EPKG_FATAL; unlink(repofile_unchecked); goto cleanup; } } /* check is the repository is for valid architecture */ sqlite3_initialize(); if (sqlite3_open(repofile_unchecked, &sqlite) != SQLITE_OK) { unlink(repofile_unchecked); pkg_emit_error("Corrupted repository"); rc = EPKG_FATAL; goto cleanup; } pkg_config_string(PKG_CONFIG_ABI, &myarch); archreq = sqlite3_mprintf("select count(arch) from packages " "where arch not GLOB '%q'", myarch); if (get_pragma(sqlite, archreq, &res) != EPKG_OK) { sqlite3_free(archreq); pkg_emit_error("Unable to query repository"); rc = EPKG_FATAL; sqlite3_close(sqlite); goto cleanup; } if (res > 0) { pkg_emit_error("At least one of the packages provided by" "the repository is not compatible with your abi: %s", myarch); rc = EPKG_FATAL; sqlite3_close(sqlite); goto cleanup; } sqlite3_close(sqlite); sqlite3_shutdown(); if (rename(repofile_unchecked, repofile) != 0) { pkg_emit_errno("rename", ""); rc = EPKG_FATAL; goto cleanup; } if ((rc = remote_add_indexes(name)) != EPKG_OK) goto cleanup; rc = EPKG_OK; cleanup: if (a != NULL) archive_read_finish(a); (void)unlink(tmp); return (rc); }
int rsa_dev_do_rsa_verify(RSA_VERIFY* rsa) { BI* signature = NULL; BI* pub_exp = NULL; BI* mod = NULL; BI* dgst = init_BI(); int ret = -EFAULT; if (!rsa) { printk("[MCP][RSA] WARNING, do rsa verify failed, invalid argument\n"); goto end_proc; } if (rsa->dgst==NULL) { printk("[MCP][RSA] WARNING, do rsa verify failed, dgst should not be zero\n"); return -EFAULT; } if (rsa->signature) { signature = init_BI(); if (copy_from_user(signature, (RSA_VERIFY __user *) rsa->signature, sizeof(BI))) { printk("[MCP][RSA] WARNING, do rsa verify failed, copy signature failed\n"); goto end_proc; } } else { printk("[MCP][RSA] WARNING, do rsa verify failed, signature should not be null\n"); goto end_proc; } if (rsa->pub_exp) { pub_exp = init_BI(); if (copy_from_user(pub_exp, (BI __user *) rsa->pub_exp, sizeof(BI))) { printk("[MCP][RSA] WARNING, do rsa verify failed, copy signature failed\n"); goto end_proc; } } else { pub_exp = move_p(65537); // default public exp } if (rsa->mod) { mod = init_BI(); if (copy_from_user(mod, (BI __user *) rsa->mod, sizeof(BI))) { printk("[MCP][RSA] WARNING, do rsa verify failed, copy signature failed\n"); goto end_proc; } } else { mod = InPutFromStr(DEF_RSA_MOD, DEF_RSA_MOD_FMT); } ret = rsa_verify(signature, pub_exp, mod, dgst); if (copy_to_user((BI __user *) rsa->dgst, dgst, sizeof(BI))) { printk("[MCP][RSA] WARNING, do rsa verify failed, copy dgst to user failed\n"); ret = -EFAULT; } end_proc: if (signature) free_BI(signature); if (pub_exp) free_BI(pub_exp); if (mod) free_BI(mod); if (dgst) free_BI(dgst); return ret; }
static int loadrsakey_main(FILE * fp, struct RSAKey *key, int pub_only, char **commentptr, char *passphrase, const char **error) { unsigned char buf[16384]; unsigned char keybuf[16]; int len; int i, j, ciphertype; int ret = 0; struct MD5Context md5c; char *comment; *error = NULL; /* Slurp the whole file (minus the header) into a buffer. */ len = fread(buf, 1, sizeof(buf), fp); fclose(fp); if (len < 0 || len == sizeof(buf)) { *error = "error reading file"; goto end; /* file too big or not read */ } i = 0; *error = "file format error"; /* * A zero byte. (The signature includes a terminating NUL.) */ if (len - i < 1 || buf[i] != 0) goto end; i++; /* One byte giving encryption type, and one reserved uint32. */ if (len - i < 1) goto end; ciphertype = buf[i]; if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES) goto end; i++; if (len - i < 4) goto end; /* reserved field not present */ if (buf[i] != 0 || buf[i + 1] != 0 || buf[i + 2] != 0 || buf[i + 3] != 0) goto end; /* reserved field nonzero, panic! */ i += 4; /* Now the serious stuff. An ordinary SSH-1 public key. */ j = makekey(buf + i, len - i, key, NULL, 1); if (j < 0) goto end; /* overran */ i += j; /* Next, the comment field. */ j = toint(GET_32BIT(buf + i)); i += 4; if (j < 0 || len - i < j) goto end; comment = snewn(j + 1, char); if (comment) { memcpy(comment, buf + i, j); comment[j] = '\0'; } i += j; if (commentptr) *commentptr = dupstr(comment); if (key) key->comment = comment; else sfree(comment); if (pub_only) { ret = 1; goto end; } if (!key) { ret = ciphertype != 0; *error = NULL; goto end; } /* * Decrypt remainder of buffer. */ if (ciphertype) { MD5Init(&md5c); MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase)); MD5Final(keybuf, &md5c); des3_decrypt_pubkey(keybuf, buf + i, (len - i + 7) & ~7); smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */ } /* * We are now in the secret part of the key. The first four * bytes should be of the form a, b, a, b. */ if (len - i < 4) goto end; if (buf[i] != buf[i + 2] || buf[i + 1] != buf[i + 3]) { *error = "wrong passphrase"; ret = -1; goto end; } i += 4; /* * After that, we have one further bignum which is our * decryption exponent, and then the three auxiliary values * (iqmp, q, p). */ j = makeprivate(buf + i, len - i, key); if (j < 0) goto end; i += j; j = ssh1_read_bignum(buf + i, len - i, &key->iqmp); if (j < 0) goto end; i += j; j = ssh1_read_bignum(buf + i, len - i, &key->q); if (j < 0) goto end; i += j; j = ssh1_read_bignum(buf + i, len - i, &key->p); if (j < 0) goto end; i += j; if (!rsa_verify(key)) { *error = "rsa_verify failed"; freersakey(key); ret = 0; } else ret = 1; end: smemclr(buf, sizeof(buf)); /* burn the evidence */ return ret; }
int main(){ LCLIB_CTX lclib_ctx; unsigned char data1[13]; unsigned char *data=NULL; unsigned long int datLen=13; //unsigned char s1[BSIZE/8]; //unsigned char s2[BSIZE/8]; //unsigned long int l1=BSIZE/8; //unsigned long int l2=BSIZE/8; int i; unsigned char *N,*d,*e; struct timeval tvs,tve,tvd; struct timezone tz; /* r=open("/dev/urandom",O_RDONLY); i=read(r,s1,BSIZE/8); i=read(r,s2,BSIZE/8); */ memcpy(data1,"abcdef0123456",13); printf("clear text\n"); for(i=0;i<13;i++) printf("%x",data1[i]); printf("\n\n"); rsa_init(&lclib_ctx,BSIZE); data=rsa_alloc(&lclib_ctx,data1,13); if(data==NULL){ printf("unable to alloc\n"); exit(0); } gettimeofday(&tvs,&tz); printf("calculating %d bit rsa key pair\n",BSIZE); //i=rsa_genkeys(&lclib_ctx,s1,l1,s2,l2); i=rsa_genkeys_internal(&lclib_ctx); gettimeofday(&tve,&tz); i=rsa_encrypt(&lclib_ctx,data,&datLen); printf("->%d\n",i); printf("encrypted data\n"); for(i=0;i<BSIZE/8;i++) printf("%x",data[i]); printf("\n\n"); i=rsa_decrypt(&lclib_ctx,data,&datLen); printf("->%d\n",i); printf("decrypted / clear text\n"); for(i=0;i<(int)datLen;i++) printf("%x",data[i]); printf("\n"); tvd.tv_sec=tve.tv_sec - tvs.tv_sec; printf("time taken to generate a %d bit key was %ld \ seconds\n",BSIZE,tvd.tv_sec); printf("bnBits=%u\n",bnBits(&lclib_ctx.rsa_ctx.e)); rsa_extractkeys(&lclib_ctx,&N,&d,&e); printf("N=\n"); for(i=0;i<(int)lclib_ctx.rsa_ctx.bits/8;i++) printf("%x",N[i]); printf("\n"); printf("d=\n"); for(i=0;i<(int)lclib_ctx.rsa_ctx.bits/8;i++) printf("%x",d[i]); printf("\n"); printf("e=\n"); for(i=0;i<(int)lclib_ctx.rsa_ctx.bits/8;i++) printf("%x",e[i]); printf("\n"); rsa_setkeys(&lclib_ctx,N,d,e); /* rsa_encrypt(&lclib_ctx,data,&datLen); printf("encrypted data\n"); for(i=0;i<BSIZE/8;i++) printf("%x",data[i]); printf("\n\n"); rsa_decrypt(&lclib_ctx,data,&datLen); printf("decrypted / clear text\n"); for(i=0;i<(int)datLen;i++) printf("%x",data[i]); printf("\n"); */ rsa_sign(&lclib_ctx,data,&datLen); printf("\nsigned data\n"); for(i=0;i<BSIZE/8;i++) printf("%x",data[i]); printf("\n\n"); rsa_verify(&lclib_ctx,data,&datLen); printf("clear text\n"); for(i=0;i<(int)datLen;i++) printf("%x",data[i]); printf("\n"); rsa_freekeys(&lclib_ctx,&N,&d,&e); lclib_end(&lclib_ctx); rsa_free(data); return 0; }