int UtlCryptoKeyRsa::importFromFile(const char* pFilename) { // Make sure we don't leave any previous keys hanging around clearKey(); FILE *pFile = fopen(pFilename, "rt"); if (!pFile) return -1; // First try to read a public key mpRsa = PEM_read_RSA_PUBKEY(pFile, 0, 0, 0); if (mpRsa) setKeyType(KEY_PUBLIC); else { // If that failed, try to read a private key fseek(pFile, 0, SEEK_SET); mpRsa = PEM_read_RSAPrivateKey(pFile, 0, 0, 0); if (mpRsa) setKeyType(KEY_PRIVATE); } fclose(pFile); if (isValid()) return setLastError(0); else return -1; }
static gint lua_rsa_pubkey_load (lua_State *L) { RSA *rsa = NULL, **prsa; const gchar *filename; FILE *f; filename = luaL_checkstring (L, 1); if (filename != NULL) { f = fopen (filename, "r"); if (f == NULL) { msg_err ("cannot open pubkey from file: %s, %s", filename, strerror (errno)); lua_pushnil (L); } else { if (!PEM_read_RSA_PUBKEY (f, &rsa, NULL, NULL)) { msg_err ("cannot open pubkey from file: %s, %s", filename, ERR_error_string (ERR_get_error (), NULL)); lua_pushnil (L); } else { prsa = lua_newuserdata (L, sizeof (RSA *)); rspamd_lua_setclass (L, "rspamd{rsa_pubkey}", -1); *prsa = rsa; } fclose (f); } } else { lua_pushnil (L); } return 1; }
/* * rsa public decrypt */ char* rsa_decrypt_public(unsigned char *enc,int enc_len,char* private_key_str,int p_len,int *dec_len) { RSA* rsa; int rsa_len; char *p_de; #if 1 // private_key = rsa_key_seliaze(private_key_str); BIO* p_bio = BIO_new_mem_buf(private_key_str, -1); rsa = PEM_read_bio_RSAPublicKey(p_bio, NULL, 0, NULL); // if ( rsa == NULL ) { printf("RSA is NULL\n"); return NULL; } #else FILE* file=fopen("/tmp/r.key","r"); rsa=PEM_read_RSA_PUBKEY(file,NULL,NULL,NULL); #endif rsa_len=RSA_size(rsa); p_de=(unsigned char *)calloc(rsa_len+1,1); printf("rsa length = %d\n",rsa_len); int rc=0; rc = RSA_public_decrypt(rsa_len,(unsigned char *)enc,(unsigned char*)p_de,rsa,RSA_PKCS1_PADDING); //RSA_public_decrypt RSA_private_decrypt if ( rc<=0 ) { int e=ERR_get_error(); printf("error code is:%s\n",ERR_error_string(e,NULL)); return NULL; } RSA_free(rsa); printf("plain = %s\n",p_de); *dec_len = rc; return p_de; }
char *my_encrypt(char *str,const char *path_key){ char *p_en; RSA *p_rsa; FILE *file; int flen,rsa_len; if((file=fopen(path_key,"r"))==NULL){ perror("open key file error"); return NULL; } if((p_rsa=PEM_read_RSA_PUBKEY(file,NULL,NULL,NULL))==NULL){ //if((p_rsa=PEM_read_RSAPublicKey(file,NULL,NULL,NULL))==NULL){ 换成这句死活通不过,无论是否将公钥分离源文件 ERR_print_errors_fp(stdout); return NULL; } flen=strlen(str); rsa_len=RSA_size(p_rsa); p_en=(char *)malloc(rsa_len+1); memset(p_en,0,rsa_len+1); if(RSA_public_encrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_en,p_rsa,RSA_NO_PADDING)<0){ return NULL; } RSA_free(p_rsa); printf("length = %d\n",rsa_len+1); fclose(file); return p_en; }
svRSAKey::svRSAKey(const string &pem) : svObject("svRSAKey"), type(svRSA_TYPE_NULL), key(NULL), mtime(0) { struct stat key_stat; if (stat(pem.c_str(), &key_stat) == -1) throw svExRSAKeyStat(pem, strerror(errno)); mtime = key_stat.st_mtime; FILE *h_key = fopen(pem.c_str(), "r"); if (!h_key) throw svExRSAKeyOpen(pem, strerror(errno)); if ((key = PEM_read_RSA_PUBKEY(h_key, NULL, NULL, NULL))) type = svRSA_TYPE_PUBLIC; else { rewind(h_key); if ((key = PEM_read_RSAPrivateKey(h_key, NULL, NULL, NULL))) type = svRSA_TYPE_PRIVATE; else { ERR_load_crypto_strings(); svError("%s: %s: %s", name.c_str(), pem.c_str(), ERR_error_string(ERR_get_error(), NULL)); } } fclose(h_key); if (type == svRSA_TYPE_NULL) throw svExRSAKeyInvalid(pem); name = pem; }
int rsautl_verify(const char *pubKey, const char *inFile, const char *inSig) { int ret = SourceSec_PubKeyNotFound; FILE *fpPubKey = fopen(pubKey, "rt"); if(!fpPubKey) return ret; // Set file as public key source (must be in PEM format) RSA *rsa_pub = PEM_read_RSA_PUBKEY(fpPubKey, NULL, NULL, NULL); // Try to open signature file FILE *fpSigFile = fopen(inSig, "rb"); if(!fpSigFile) { fclose(fpPubKey); return SourceSec_SigNotFound; } // Calculate hash of input file unsigned char hash[SHA256_DIGEST_LENGTH]; calc_sha256(inFile, hash); // Get size of signature file fseek(fpSigFile, 0L, SEEK_END); size_t lenSig = ftell(fpSigFile); fseek(fpSigFile, 0L, SEEK_SET); // Signature size is suspiciously high, cancel process if(lenSig > 1024) { fclose(fpPubKey); fclose(fpSigFile); return SourceSec_SigTooBig; } // Read content into memory unsigned char *signature = (unsigned char*)malloc(lenSig); size_t rv = fread(signature, sizeof(unsigned char), lenSig, fpSigFile); // Check if full content was loaded if(rv != lenSig) { fclose(fpPubKey); fclose(fpSigFile); return SourceSec_SigIncomplete; } // Verify signature integrity ret = RSA_verify(NID_sha256, hash, SHA256_DIGEST_LENGTH, (const unsigned char*)signature, lenSig, rsa_pub); // Free resources fclose(fpPubKey); fclose(fpSigFile); free(signature); return ret; }
int encryptf(FILE * fp,char * pub_key,char * encry_path) { //read file to str pointer char * plain; int fsize; fseek(fp,0,SEEK_END); fsize=ftell(fp); fseek(fp,0,SEEK_SET); plain=(char *)malloc(fsize * sizeof(char)); fread(plain,sizeof(char),fsize,fp); // printf("file size is:\n%d\n",fsize); // printf("Source is:\n%s\n",plain); // printf("strlen is: \n%d\n",strlen(plain)); fclose(fp); // used to store encrypted file char encrypted[1024]; // ------------------------------------------------------- // use public key to encrypt plain text // ------------------------------------------------------- // open public key file FILE* pub_fp=fopen(pub_key,"r"); if(pub_fp==NULL){ printf("failed to open pub_key file %s!\n", pub_key); return -1; } // read public key from file RSA* rsa1=PEM_read_RSA_PUBKEY(pub_fp, NULL, NULL, NULL); if(rsa1==NULL){ printf("unable to read public key!\n"); return -1; } if(strlen(plain)>=RSA_size(rsa1)-41){ printf("failed to encrypt\n"); return -1; } fclose(pub_fp); // use public key to encrypt encrylen=RSA_public_encrypt(strlen(plain), (const unsigned char*)plain, (unsigned char*)encrypted, rsa1, RSA_PKCS1_PADDING); if(encrylen==-1 ){ printf("failed to encrypt\n"); return -1; } // printf("in encryptf func, encrylen is:\n%d\n",encrylen); // output encrypted data to original file FILE* ffp=fopen(encry_path,"w"); if(ffp){ fwrite(encrypted,encrylen,1,ffp); fclose(ffp); } }
static bool VerifyBuffer(const unsigned char* buffer, const unsigned int bufferLen, const unsigned char* signatureEncoded, const unsigned int signatureEncodedLen, const CStdString& appsPublicKeyFile) { unsigned char hash[SHA_DIGEST_LENGTH]; SHA_CTX context; FILE *fkey = NULL; RSA *rsa = NULL; bool bSuccedded = false; unsigned char* signature = NULL; int signatureLen = 0; SHA1_Init(&context); SHA1_Update(&context, buffer, bufferLen); SHA1_Final(hash, &context); #ifdef DEBUG dump_sha1(hash); #endif do { signatureLen = unbase64((unsigned char*)signatureEncoded, signatureEncodedLen, &signature); if(!signatureLen) { CLog::Log(LOGERROR, "CAppSecurity::%s - failed to decode signature [%s]", __func__, signatureEncoded); break; } fkey = fopen(_P(appsPublicKeyFile), "r"); if (!fkey) { CLog::Log(LOGERROR, "CAppSecurity::%s - failed to open publickey file [%s]", __func__, appsPublicKeyFile.c_str()); break; } PEM_read_RSA_PUBKEY(fkey, &rsa, NULL, NULL); if (!rsa) { CLog::Log(LOGERROR, "CAppSecurity::%s - failed to load rsa key from file [%s]", __func__, appsPublicKeyFile.c_str()); break; } bSuccedded = RSA_verify(NID_sha1, hash, SHA_DIGEST_LENGTH, signature, signatureLen, rsa); } while(false); if (rsa) RSA_free(rsa); if (fkey) fclose(fkey); if (signature) free(signature); return bSuccedded; }
RSAipher* RSAipher::Create( FILE* pFile, bool bPublic) { if(!pFile) return NULL; RSA* pKey = bPublic ? PEM_read_RSA_PUBKEY( pFile, NULL, NULL, NULL) : PEM_read_RSAPrivateKey( pFile, NULL, NULL, NULL); if(!pKey) { assert(false); return NULL; } return new RSAipher( pKey, bPublic); }
int main() { const unsigned char text[] = "hello world"; unsigned char crypt_text[1024]; unsigned char decrypt_text[1024 - 11]; RSA *public_key = NULL; RSA *private_key = NULL; public_key = RSA_new(); private_key = RSA_new(); FILE *fpub = fopen("public_key", "r"); FILE *fpriv = fopen("private_key", "r"); printf("text: %s\n", text); RSA *ret = PEM_read_RSA_PUBKEY(fpub, &public_key, NULL, NULL); printf("pubkey ret: %d\n", ret); ret = PEM_read_RSAPrivateKey(fpriv, &private_key, NULL, NULL); printf("prikey ret: %d\n", ret); //私钥加密,公钥解密 int num = RSA_private_encrypt(sizeof(text) - 1, text, crypt_text, private_key, RSA_PKCS1_PADDING); printf("num: %d\n", num); for (int i = 0; i < num; i++) { printf("\\x%02x", crypt_text[i]); } printf("\ndecrypt\n"); int decrypt_len = RSA_public_decrypt(num, crypt_text, decrypt_text, public_key, RSA_PKCS1_PADDING); if (decrypt_len < 0) printf("error: %lu\n", ERR_get_error()); printf("decrypt_len: %d\n", decrypt_len); printf("decrypt text: %s\n", decrypt_text); //公钥加密,私钥解密 num = RSA_public_encrypt(sizeof(text) - 1, text, crypt_text, public_key, RSA_PKCS1_PADDING); printf("num: %d\n", num); for (int i = 0; i < num; i++) { printf("\\x%02x", crypt_text[i]); } printf("\ndecrypt\n"); decrypt_len = RSA_private_decrypt(RSA_size(private_key), crypt_text, decrypt_text, private_key, RSA_PKCS1_PADDING); if (decrypt_len < 0) printf("error: %lu\n", ERR_get_error()); printf("decrypt_len: %d\n", decrypt_len); printf("decrypt text: %s\n", decrypt_text); return 0; }
bool CRsaEncDec::ReadPublickey(const std::string& keyfile, bool readfile) { if (m_publicKey != NULL) { RSA_free(m_publicKey); m_publicKey = NULL; } if (NULL == (m_publicKey = RSA_new())) return false; if (readfile) { FILE* hPubKeyFile = fopen(keyfile.c_str(), "rb"); if( hPubKeyFile == NULL ) { LOG.err_log("打开公钥文件失败:%s, [%s:%d]", keyfile.c_str(), __FILE__, __LINE__); return false; } RSA* res = PEM_read_RSA_PUBKEY(hPubKeyFile, &m_publicKey, 0, 0); fclose(hPubKeyFile); hPubKeyFile = NULL; if (!res) { LOG.err_log("读取公钥失败![%s:%d]", __FILE__, __LINE__); return false; } } else { BIGNUM *bnn = BN_new(); BIGNUM *bne = BN_new(); BIGNUM *bnd = BN_new(); BN_hex2bn(&bnn, MODULUS); BN_set_word(bne, PUBLIC_EXPONENT); BN_hex2bn(&bnd, PRIVATE_EXPONENT); m_publicKey->n = bnn; m_publicKey->e = bne; m_publicKey->d = bnd; return true; } return true; }
RSA* getRsaFp2( const char* rsapubKeyPath ) { FILE* fp; fp = fopen( rsapubKeyPath, "r" ); if ( fp == 0 ) { fprintf( stderr, "Couldn't open RSA pub key: '%s'. %s\n", rsapubKeyPath, strerror(errno) ); exit(1); } RSA *rsa = 0; rsa = RSA_new(); rsa = PEM_read_RSA_PUBKEY(fp, 0, pass_cb, (char*)rsapubKeyPath); fclose( fp ); return rsa; }
RSA* SecurityKey::getPublicRSA() const { RSA *rsa = RSA_new(); FILE * rsa_pkey_file = fopen(file.getPath().c_str(), "r"); if (!rsa_pkey_file) { IBRCOMMON_LOGGER_ex(critical) << "Failed to open " << file.getPath() << IBRCOMMON_LOGGER_ENDL; throw ibrcommon::Exception("Failed to open " + file.getPath()); } if (!PEM_read_RSA_PUBKEY(rsa_pkey_file, &rsa, NULL, NULL)) { IBRCOMMON_LOGGER_ex(critical) << "Error loading RSA public key file: " << file.getPath() << IBRCOMMON_LOGGER_ENDL; ERR_print_errors_fp(stderr); throw ibrcommon::Exception("Error loading RSA public key file: " + file.getPath()); } fclose(rsa_pkey_file); return rsa; }
RSA *readkey(char *location,int keytype){ FILE *infile; infile = fopen(location, "r"); if (keytype==PUBKEY){ RSA *key=PEM_read_RSA_PUBKEY(infile,NULL,NULL,NULL); return key;} else if (keytype==PRIKEY){ RSA *key= PEM_read_RSAPrivateKey(infile,NULL,NULL,NULL); return key;} }
int main() { struct config conf; memset(&conf, 0, sizeof(conf)); // Lookup IP of target struct hostent *he = gethostbyname("128.138.200.81"); memset(&conf.sin, 0, sizeof(conf.sin)); conf.sin.sin_family = he->h_addrtype; conf.sin.sin_port = htons(443); conf.sin.sin_addr = *(((struct in_addr **)he->h_addr_list)[0]); // Dummy values memset(conf.prev_block_hash, 0xAA, 32); memset(conf.merkle_root, 0xBB, 32); memset(conf.difficulty, 0x00, 32); conf.difficulty[0] = 0x00; conf.difficulty[1] = 0x00; conf.difficulty[2] = 0x07; // Load RSA key FILE *fp = fopen("./pubkey.pem", "rb"); // Apparently, PEM_read_PUBKEY() doens't read PEM(?!?) PEM_read_RSA_PUBKEY(fp, &conf.public_key, NULL, NULL); fclose(fp); if (conf.public_key == NULL) { printf("Error couldn't read public key\n"); return -1; } // Open /dev/urandom conf.rand = fopen("/dev/urandom", "rb"); conf.base = event_base_new(); struct timeval one_sec = {1,0}; struct event *status_ev = event_new(conf.base, -1, EV_PERSIST, print_status, &conf); event_add(status_ev, &one_sec); fetcher(&conf, 1000); event_base_dispatch(conf.base); return 0; }
static int load_rsa_keys(int is_encrypt, BIGNUM **e, BIGNUM **n) { OpenSSL_add_all_algorithms(); FILE* fp = is_encrypt ? fopen("./keys/public.pem","r") : fopen("./keys/private.pem","r"); if (fp == NULL) { return 1; } RSA *rsa = is_encrypt ? PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL) : PEM_read_RSAPrivateKey(fp, NULL, password_cb, "12345"); fclose(fp); if (rsa == NULL) { return 2; } *n = rsa->n; *e = is_encrypt ? rsa->e : rsa->d; return 0; }
int COsslKey::LoadPublicKey( const sqbind::stdString &sFile ) {_STT(); Destroy(); m_pkey = EVP_PKEY_new(); if ( !m_pkey ) { oexERROR( 0, oexT( "EVP_PKEY_new() failed" ) ); Destroy(); return 0; } // end if oex::CStr8 name = oexStrToMb( oex::CStr( sFile.c_str(), sFile.length() ) ); FILE *fp = fopen( name.Ptr(), "r" ); if ( !fp ) { oexERROR( oexGetLastError(), oexMks( oexT( "fopen( '" ), oexMbToStr( name ), oexT( "' ) failed" ) ) ); Destroy(); return 0; } // end if RSA *rsa = PEM_read_RSAPublicKey( fp, oexNULL, oexNULL, (void*)getPasswordPtr() ); if ( !rsa ) rsa = PEM_read_RSA_PUBKEY( fp, oexNULL, oexNULL, (void*)getPasswordPtr() ); if ( !rsa ) { oexERROR( 0, oexT( "PEM_read_RSAPublicKey() failed" ) ); fclose( fp ); Destroy(); return 0; } // end if fclose( fp ); // Assign key if ( !EVP_PKEY_assign_RSA( m_pkey, rsa ) ) { oexERROR( 0, oexT( "EVP_PKEY_assign_RSA() failed" ) ); Destroy(); return 0; } // end if rsa = oexNULL; return 1; }
RSA* rsa_read_public_key_from_PEM(const std::string& path) { // std::cout << "(i) " << __func__ << ": trying to open " << path << std::endl; FILE* pem_file = fopen(path.c_str(), "rb"); if(pem_file == nullptr || pem_file == 0) { std::cout << "(e) "<< __func__ << ": could not open file: " << path << std::endl; return nullptr; } RSA* rsa = PEM_read_RSA_PUBKEY(pem_file, NULL, NULL, NULL); fclose(pem_file); if(rsa == nullptr || rsa == 0) { std::cout << "(e) "<< __func__ << ": null key." << std::endl; return nullptr; } return rsa; }
int rsa_pub_encrypt(char ** str_out, char *str_in, size_t str_in_sz, char *key_file) { RSA * pub_key = NULL; FILE * pub_key_file; OpenSSL_add_all_algorithms(); OpenSSL_add_all_ciphers(); ERR_load_crypto_strings(); pub_key_file = fopen(key_file, "rb"); if (pub_key_file == NULL) { std::cerr << "Keyfile read failed" << std::endl; return -1; } pub_key = PEM_read_RSA_PUBKEY(pub_key_file, NULL, NULL, NULL); fclose(pub_key_file); if (!pub_key) { std::cerr << ERR_error_string(ERR_get_error(), NULL) << std::endl; return -1; } int key_size = RSA_size(pub_key); unsigned char *ustr_out = (unsigned char *)malloc(key_size); // std::cout << "key_size: " << key_size << std::endl; // std::cout << "str_in_sz: " << str_in_sz << std::endl; int len = RSA_public_encrypt(str_in_sz, (unsigned char *)&str_in[0], ustr_out, pub_key, RSA_PKCS1_PADDING); if (len == -1) { std::cerr << "RSA_public_encrypt error (rsa_pub_encrypt)." << std::endl; std::cerr << ERR_error_string(ERR_get_error(), NULL) << std::endl; return -1; } *str_out = (char *)ustr_out; return len; }
char *public_decrypt(char *str, char *path_key) { char *p_de; RSA *p_rsa; FILE *file; int rsa_len; if ((file = fopen(path_key, "r")) == NULL) { perror("open key file error"); return NULL; } if ((p_rsa = PEM_read_RSA_PUBKEY(file, NULL, NULL, NULL)) == NULL) { ERR_print_errors_fp(stdout); return NULL; } rsa_len = RSA_size(p_rsa); p_de = (char *) malloc(rsa_len); bzero(p_de, rsa_len); assert(RSA_public_decrypt(rsa_len, (unsigned char *) str, (unsigned char*) p_de, p_rsa, RSA_NO_PADDING) != -1); RSA_free(p_rsa); fclose(file); return p_de; }
static RSA * load_rsa_public_key(const char *rsa_key_path) { FILE *fp; RSA *rsa = NULL; char errbuf[1024]; if ((fp = fopen(rsa_key_path, "rb")) == 0) { pkg_emit_errno("fopen", rsa_key_path); return (NULL); } if (!PEM_read_RSA_PUBKEY( fp, &rsa, NULL, NULL )) { pkg_emit_error("error reading public key(%s): %s", rsa_key_path, ERR_error_string(ERR_get_error(), errbuf)); fclose(fp); return (NULL); } fclose(fp); return (rsa); }
int openssl_read_pem_pubkey(const char *f, __ops_pubkey_t *key, const char *type, int verbose) { FILE *fp; DSA *dsa; RSA *rsa; int ok; OpenSSL_add_all_algorithms(); if ((fp = fopen(f, "r")) == NULL) { if (verbose) { (void) fprintf(stderr, "can't open '%s'\n", f); } return 0; } ok = 1; if (strcmp(type, "ssh-rsa") == 0) { rsa = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL); if(!rsa) rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL); key->key.rsa.e = rsa->e; key->key.rsa.n = rsa->n; } else if (strcmp(type, "ssh-dss") == 0) { if ((dsa = PEM_read_DSA_PUBKEY(fp, NULL, NULL, NULL)) == NULL) { ok = 0; } else { key->key.dsa.y = dsa->pub_key; } } else { ok = 0; } (void) fclose(fp); return ok; }
int serverReadKey(Server * server, char * key) { FILE * f; if ((f = fopen(key, "r")) == NULL) { fprintf(stderr, "Can't open file %s!\n", key); return 1; } server->rsa = RSA_new(); if (server->rsa == NULL) return 1; if(PEM_read_RSA_PUBKEY(f, &server->rsa, (pem_password_cb *) password_callback, NULL) == 0) { ERR_print_errors_fp(stderr); return 1; } char * tmpstr; tmpstr = BN_bn2dec(server->rsa->n); printf("Модуль: %s\n", tmpstr); OPENSSL_free(tmpstr); tmpstr = BN_bn2dec(server->rsa->e); printf("Публичная экспонента: %s\n", tmpstr); OPENSSL_free(tmpstr); printf("&p = %x\n", server->rsa->p); if (server->rsa->p){ tmpstr = BN_bn2dec(server->rsa->p); printf("p = %s\n", tmpstr); OPENSSL_free(tmpstr); } return 0; }
char * encrypt(char * p_src,char * pub_key) { char * p_ecypt; int rsa_len; // open public key file FILE * pub_fp=fopen(pub_key,"r"); if(pub_fp==NULL){ printf("failed to open pub_key file %s!\n",pub_key); return NULL; } // read public key from public key file RSA *rsa1=PEM_read_RSA_PUBKEY(pub_fp,NULL,NULL,NULL); if(rsa1==NULL){ printf("failed to read public key!\n"); return NULL; } rsa_len=RSA_size(rsa1); p_ecypt=(char *)malloc(rsa_len+1); memset(p_ecypt,0,rsa_len+1); if(strlen(p_src)>=RSA_size(rsa1)-41){ printf("failed to encrypt\n"); return NULL; } fclose(pub_fp); // encrypt by using public key encrylen=RSA_public_encrypt(strlen(p_src),(const unsigned char*)p_src,(unsigned char*)p_ecypt,rsa1,RSA_PKCS1_PADDING); if(encrylen==-1){ printf("failed to encrypt\n"); return NULL; } return p_ecypt; }
//create the RSA pointers for encryption/decryption void Crypter::CreateRSA(char * fileName, int publicNum){ FILE * fp = fopen(fileName,"rb"); if(fp == NULL) { printf("Unable to open file %s \n",fileName); return; } RSA *rsaKey = RSA_new() ; if(publicNum) { rsaKey = PEM_read_RSA_PUBKEY(fp, &rsaKey,NULL, NULL); mPublicRSA = rsaKey; } else { rsaKey = PEM_read_RSAPrivateKey(fp, &rsaKey, NULL, NULL); mPrivateRSA = rsaKey; } }
char *js_public_encrypt(const char *plain_text, const char *public_key_path) { RSA *rsa_publicKey = NULL; FILE *fp_publicKey; int rsa_public_len; if ((fp_publicKey = fopen(public_key_path, "r")) == NULL) { printf("Could not open %s\n", public_key_path); return '\0'; } if ((rsa_publicKey = PEM_read_RSA_PUBKEY(fp_publicKey, NULL, NULL, NULL)) == NULL) { fclose(fp_publicKey); printf("Error loading RSA Public Key File."); return '\0'; } fclose(fp_publicKey); rsa_public_len = RSA_size(rsa_publicKey); printf("RSA public length: %d\n", rsa_public_len); // 11 bytes is overhead required for encryption int chunk_length = rsa_public_len - 11; // plain text length int plain_char_len = (int)strlen(plain_text); // calculate the number of chunks int num_of_chunks = (int)(strlen(plain_text) / chunk_length) + 1; int total_cipher_length = 0; // the output size is (total number of chunks) x (the key length) int encrypted_size = (num_of_chunks * rsa_public_len); unsigned char *cipher_data = malloc(encrypted_size + 1); char *err = NULL; for (int i = 0; i < plain_char_len; i += chunk_length) { // get the remaining character count from the plain text int remaining_char_count = plain_char_len - i; // this len is the number of characters to encrypt, thus take the minimum between the chunk count & the remaining characters // this must less than rsa_public_len - 11 int len = JSMIN(remaining_char_count, chunk_length); unsigned char *plain_chunk = malloc(len + 1); // take out chunk of plain text memcpy(&plain_chunk[0], &plain_text[i], len); printf("Plain chunk: %s\n", plain_chunk); unsigned char *result_chunk = malloc(rsa_public_len + 1); int result_length = RSA_public_encrypt(len, plain_chunk, result_chunk, rsa_publicKey, RSA_PKCS1_PADDING); printf("Plain char len: %d\n", i); printf("Encrypted Result chunk: %s\nEncrypted Chunk length: %d\n", result_chunk, result_length); free(plain_chunk); if (result_length == -1) { ERR_load_CRYPTO_strings(); fprintf(stderr, "Error %s\n", ERR_error_string(ERR_get_error(), err)); fprintf(stderr, "Error %s\n", err); } memcpy(&cipher_data[total_cipher_length], &result_chunk[0], result_length); total_cipher_length += result_length; free(result_chunk); } printf("Total cipher length: %d\n", total_cipher_length); RSA_free(rsa_publicKey); size_t total_len = 0; char *encrypted = base64_encode(cipher_data, encrypted_size, &total_len); printf("Final result: %s\n Final result length: %zu\n", encrypted, total_len); free(cipher_data); return encrypted; }
char *js_public_decrypt(const char *cipher_text, const char *public_key_path) { RSA *rsa_publicKey = NULL; FILE *fp_publicKey; int rsa_public_len; if ((fp_publicKey = fopen(public_key_path, "r")) == NULL) { printf("Could not open %s\n", public_key_path); return '\0'; } if ((rsa_publicKey = PEM_read_RSA_PUBKEY(fp_publicKey, NULL, NULL, NULL)) == NULL) { fclose(fp_publicKey); printf("Error loading RSA Public Key File."); return '\0'; } fclose(fp_publicKey); printf("Cipher text: %s\n", cipher_text); rsa_public_len = RSA_size(rsa_publicKey); printf("RSA public length: %d\n", rsa_public_len); size_t crypt_len = 0; unsigned char *crypt = base64_decode(cipher_text, strlen(cipher_text), &crypt_len); printf("Decoded cipher: %s\nCrypt length: %ld\n", crypt, crypt_len); // If no static, it will cause "address of stack memory associated with local variable ...", which mean the variable will released from memory after the end of this function char *plain_char = malloc(crypt_len); // initialize strcpy(plain_char, ""); char *err = NULL; for (int i = 0; i < crypt_len; i += rsa_public_len) { unsigned char *crypt_chunk = malloc(rsa_public_len + 1); memcpy(&crypt_chunk[0], &crypt[i], rsa_public_len); printf("Crypt chunk: %s\n", crypt_chunk); unsigned char *result_chunk = malloc(crypt_len + 1); int result_length = RSA_public_decrypt(rsa_public_len, crypt_chunk, result_chunk, rsa_publicKey, RSA_PKCS1_PADDING); // chunk length should be the size of publickey (in bytes) minus 11 (overhead during encryption) printf("Result chunk: %s\nChunk length: %d\n", result_chunk, result_length); free(crypt_chunk); // this is to omit the dummy character behind // i.e. Result chunk: ABC-1234567-201308101427371250-abcdefghijklmnopqrstuv\240Z // Chunk length: 53 // New chunk: ABC-1234567-201308101427371250-abcdefghijklmnopqrstuv // // by copying the chunk to a temporary variable with an extra length (i.e. in this case is 54) // and then set the last character of temporary variable to NULL char tmp_result[result_length + 1]; memcpy(tmp_result, result_chunk, result_length); tmp_result[result_length] = '\0'; printf("New chunk: %s\n", tmp_result); free(result_chunk); if (result_length == -1) { ERR_load_CRYPTO_strings(); fprintf(stderr, "Error %s\n", ERR_error_string(ERR_get_error(), err)); fprintf(stderr, "Error %s\n", err); } strcat(plain_char, tmp_result); } RSA_free(rsa_publicKey); free(crypt); printf("Final result: %s\n", plain_char); return plain_char; }
static struct ast_key *try_load_key (char *dir, char *fname, int ifd, int ofd, int *not2) { int ktype = 0; char *c = NULL; char ffname[256]; unsigned char digest[16]; FILE *f; struct MD5Context md5; struct ast_key *key; static int notice = 0; int found = 0; /* Make sure its name is a public or private key */ if ((c = strstr(fname, ".pub")) && !strcmp(c, ".pub")) { ktype = AST_KEY_PUBLIC; } else if ((c = strstr(fname, ".key")) && !strcmp(c, ".key")) { ktype = AST_KEY_PRIVATE; } else return NULL; /* Get actual filename */ snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname); ast_mutex_lock(&keylock); key = keys; while(key) { /* Look for an existing version already */ if (!strcasecmp(key->fn, ffname)) break; key = key->next; } ast_mutex_unlock(&keylock); /* Open file */ f = fopen(ffname, "r"); if (!f) { ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno)); return NULL; } MD5Init(&md5); while(!feof(f)) { /* Calculate a "whatever" quality md5sum of the key */ char buf[256]; memset(buf, 0, 256); fgets(buf, sizeof(buf), f); if (!feof(f)) { MD5Update(&md5, (unsigned char *) buf, strlen(buf)); } } MD5Final(digest, &md5); if (key) { /* If the MD5 sum is the same, and it isn't awaiting a passcode then this is far enough */ if (!memcmp(digest, key->digest, 16) && !(key->ktype & KEY_NEEDS_PASSCODE)) { fclose(f); key->delme = 0; return NULL; } else { /* Preserve keytype */ ktype = key->ktype; /* Recycle the same structure */ found++; } } /* Make fname just be the normal name now */ *c = '\0'; if (!key) { if (!(key = ast_calloc(1, sizeof(*key)))) { fclose(f); return NULL; } } /* At this point we have a key structure (old or new). Time to fill it with what we know */ /* Gotta lock if this one already exists */ if (found) ast_mutex_lock(&keylock); /* First the filename */ ast_copy_string(key->fn, ffname, sizeof(key->fn)); /* Then the name */ ast_copy_string(key->name, fname, sizeof(key->name)); key->ktype = ktype; /* Yes, assume we're going to be deleted */ key->delme = 1; /* Keep the key type */ memcpy(key->digest, digest, 16); /* Can I/O takes the FD we're given */ key->infd = ifd; key->outfd = ofd; /* Reset the file back to the beginning */ rewind(f); /* Now load the key with the right method */ if (ktype == AST_KEY_PUBLIC) key->rsa = PEM_read_RSA_PUBKEY(f, NULL, pw_cb, key); else key->rsa = PEM_read_RSAPrivateKey(f, NULL, pw_cb, key); fclose(f); if (key->rsa) { if (RSA_size(key->rsa) == 128) { /* Key loaded okay */ key->ktype &= ~KEY_NEEDS_PASSCODE; if (option_verbose > 2) ast_verbose(VERBOSE_PREFIX_3 "Loaded %s key '%s'\n", key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name); if (option_debug) ast_log(LOG_DEBUG, "Key '%s' loaded OK\n", key->name); key->delme = 0; } else ast_log(LOG_NOTICE, "Key '%s' is not expected size.\n", key->name); } else if (key->infd != -2) { ast_log(LOG_WARNING, "Key load %s '%s' failed\n",key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name); if (ofd > -1) { ERR_print_errors_fp(stderr); } else ERR_print_errors_fp(stderr); } else { ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name); key->ktype |= KEY_NEEDS_PASSCODE; if (!notice) { if (!ast_opt_init_keys) ast_log(LOG_NOTICE, "Add the '-i' flag to the asterisk command line if you want to automatically initialize passcodes at launch.\n"); notice++; } /* Keep it anyway */ key->delme = 0; /* Print final notice about "init keys" when done */ *not2 = 1; } if (found) ast_mutex_unlock(&keylock); if (!found) { ast_mutex_lock(&keylock); key->next = keys; keys = key; ast_mutex_unlock(&keylock); } return key; }
int cmd_rsadec(const char **keyfiles, int nkeys) { RSA **keys = calloc(nkeys, sizeof(RSA *)); int *ispub = calloc(nkeys, sizeof(int)); int ecode = 0; int blksize = 0; int i; int off; int n; unsigned char *data_in; unsigned char *data_out; for (i = 0; i < nkeys; ++i) { FILE *fp; const char *sfx; sfx = strrchr(keyfiles[i], '.'); if (sfx && strcmp(sfx, ".pub") == 0) { fp = fopen(keyfiles[i], "r"); if (fp == NULL) { fprintf(stderr, "hammer2 rsaenc: unable to " "open %s\n", keyfiles[i]); ecode = 1; goto done; } keys[i] = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL); ispub[i] = 1; fclose(fp); if (keys[i] == NULL) { fprintf(stderr, "hammer2 rsaenc: unable to " "parse public key from %s\n", keyfiles[i]); ecode = 1; goto done; } } else if (sfx && strcmp(sfx, ".prv") == 0) { fp = fopen(keyfiles[i], "r"); if (fp == NULL) { fprintf(stderr, "hammer2 rsaenc: unable to " "open %s\n", keyfiles[i]); ecode = 1; goto done; } keys[i] = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL); fclose(fp); if (keys[i] == NULL) { fprintf(stderr, "hammer2 rsaenc: unable to " "parse private key from %s\n", keyfiles[i]); ecode = 1; goto done; } } else { fprintf(stderr, "hammer2: rsaenc: key files must end " "in .pub or .prv\n"); ecode = 1; goto done; } if (i == 0) blksize = RSA_size(keys[i]); else assert(blksize == RSA_size(keys[i])); } /* * */ data_in = malloc(blksize); data_out = malloc(blksize); off = 0; while ((n = read(0, data_in + off, blksize - off)) > 0) { off += n; if (off == blksize) { for (i = 0; i < nkeys; ++i) { if (ispub[i]) RSA_public_decrypt(blksize, data_in, data_out, keys[i], RSA_NO_PADDING); else RSA_private_decrypt(blksize, data_in, data_out, keys[i], RSA_NO_PADDING); if (i + 1 != nkeys) bcopy(data_out, data_in, blksize); } if (write(1, data_out, blksize) != blksize) { perror("write"); ecode = 1; break; } off = 0; } } if (off) { if (off < blksize) bzero(data_in + off, blksize - off); for (i = 0; i < nkeys; ++i) { if (ispub[i]) RSA_public_decrypt(blksize, data_in, data_out, keys[i], RSA_NO_PADDING); else RSA_private_decrypt(blksize, data_in, data_out, keys[i], RSA_NO_PADDING); if (i + 1 != nkeys) bcopy(data_out, data_in, blksize); } if (write(1, data_out, blksize) != blksize) { perror("write"); ecode = 1; } } if (n < 0) { perror("read"); ecode = 1; } free(data_out); free(data_in); done: for (i = 0; i < nkeys; ++i) { if (keys[i]) RSA_free(keys[i]); } free(keys); free(ispub); return (ecode); }
int verify(char* public_key_path, unsigned char *msg, int msg_len, unsigned char *sig, unsigned int sig_len) { //Load public key FILE *fp = fopen(public_key_path, "r"); if(!fp) { printf("Could not find public key\n"); return 0; } RSA *rsa = (RSA *) PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL); if(!rsa) return 0; fclose(fp); //Compute Hash unsigned char md[SHA256_DIGEST_LENGTH]; sha(msg, msg_len, md); //Verify signature int verified = RSA_verify(NID_sha256, md, SHA256_DIGEST_LENGTH, (unsigned char*)sig, (unsigned int)sig_len, rsa); if(!verified){ printf("Error: %ul\n", (unsigned int)ERR_get_error()); } RSA_free(rsa); return verified; }