Esempio n. 1
0
//-------------------------------------------------------------------------------------
bool KBE_RSA::loadPrivate(const std::string& keyname)
{
    FILE *fp = NULL;

	if(rsa_private == NULL)
	{
		fp = fopen(keyname.c_str(), "rb");
		if (!fp) {
			return false;
		}
		
		rsa_private = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
		if(NULL == rsa_private)
		{
			ERR_load_crypto_strings();
			char err[1024];
			char* errret = ERR_error_string(ERR_get_error(), err);
			ERROR_MSG(fmt::format("KBE_RSA::loadPrivate: PEM_read_RSAPrivateKey error({} : {})\n",
				errret, err));

			fclose(fp);
			return false;
		}
	}

	if(fp)
		fclose(fp);
	return rsa_private != NULL;
}
Esempio n. 2
0
File: 2cca.c Progetto: randunel/2cca
/*
 * Load CA certificate and private key from current dir
 */
static int load_ca(char * ca_name, identity * ca)
{
    FILE * f ;
    RSA  * rsa ;
    char filename[FIELD_SZ+1] ;

    sprintf(filename, "%s.crt", ca_name);
    if ((f=fopen(filename, "r"))==NULL) {
        fprintf(stderr, "Cannot find: %s\n", filename);
        return -1 ; 
    }
    ca->cert = PEM_read_X509(f, NULL, NULL, NULL);
    fclose(f);

    sprintf(filename, "%s.key", ca_name);
    if ((f=fopen(filename, "r"))==NULL) {
        return -1 ; 
    }
    rsa = PEM_read_RSAPrivateKey(f, NULL, NULL, NULL);
    fclose(f);

    ca->key = EVP_PKEY_new();
    EVP_PKEY_assign_RSA(ca->key, rsa);

    if (!X509_check_private_key(ca->cert, ca->key)) {
        fprintf(stderr, "CA certificate and private key do not match\n");
        return -1 ;
    }
    return 0;
}
Esempio n. 3
0
//使用私钥解密
int rsa_decrypt(char *in, const char *key_path, char* out)
{
    RSA *p_rsa;
    FILE *file;
    int rsa_len;
    if ((file=fopen(key_path, "r"))==NULL)
    {
        perror("open key file error");
        return 0;
    }

    if ((p_rsa=PEM_read_RSAPrivateKey(file, NULL, NULL, NULL))==NULL)
    {
        ERR_print_errors_fp(stdout);
        return 0;
    }

    rsa_len=RSA_size(p_rsa);
    if (RSA_private_decrypt(rsa_len, (unsigned char*)in, (unsigned char*)out, p_rsa, RSA_NO_PADDING)<0)
    {
        return 0;
    }
    RSA_free(p_rsa);
    fclose(file);
    return 1;
}
Esempio n. 4
0
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;
}
Esempio n. 5
0
Key::Key(string publicKeyFile, string privateKeyFile)
{
    rsa = NULL;
    privateKey = NULL;
    publicKey = NULL;
    priName = privateKeyFile;
    pubName = publicKeyFile;
    
    if (!privateKeyFile.empty()) {
        FILE *fp = fopen(privateKeyFile.c_str(), "r");
        if (fp == NULL) {
            cout << "Private Key File Error!" << endl;
            return ;
        }
        privateKey = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
        fclose(fp);
    }
    if (!publicKeyFile.empty()) {
        FILE *fp = fopen(publicKeyFile.c_str(), "r");
        if (fp == NULL) {
            cout << "Public Key File Error!" << endl;
            return ;
        }
//        rsa = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL);
        publicKey = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
        fclose(fp);
        return ;
    }
    cout << "Error Open Private Key or Public Key!" << endl;
}
char * decrypt(char * p_ecypt,int len_ecypt,char * priv_key){
    char * p_dcypt;
    int rsa_len;

    // open private key file
    FILE* priv_fp=fopen(priv_key,"r");
    if(priv_fp==NULL){
        printf("failed to open priv_key file %s!\n", priv_key);
        return NULL;
    }
    
    // read private key from private key file
    RSA *rsa2=PEM_read_RSAPrivateKey(priv_fp,NULL,NULL,NULL);
    if(rsa2==NULL){
        printf("unable to read private key!\n");
        return NULL;
    }
    
    rsa_len=RSA_size(rsa2);
    p_dcypt=(char *)malloc(rsa_len+1);
    memset(p_dcypt,0,rsa_len+1);
 
    // decrypt by using private key 
    decrylen=RSA_private_decrypt(len_ecypt,(const unsigned char*)p_ecypt,(unsigned char*)p_dcypt,rsa2,RSA_PKCS1_PADDING);
    if(decrylen==-1){
        printf("failed to decrypt!\n");
        return NULL;
    }
    
    fclose(priv_fp);
    return p_dcypt;
}
Esempio n. 7
0
int
sign(char* private_key_path, unsigned char *msg, int msg_len,
     unsigned char *sig, unsigned int *sig_len)
{

    //Load private key
    FILE *fp = fopen(private_key_path, "r");
    if(!fp) {
        DEBUGMSG(ERROR, "Could not find private key\n");
        return 0;
    }
    RSA *rsa = (RSA *) PEM_read_RSAPrivateKey(fp,NULL,NULL,NULL);
    fclose(fp);
    if(!rsa) return 0;

    unsigned char md[SHA256_DIGEST_LENGTH];
    sha(msg, msg_len, md);

    //Compute signatur
    int err = RSA_sign(NID_sha256, md, SHA256_DIGEST_LENGTH, (unsigned char*)sig, (unsigned int*)sig_len, rsa);
    if(!err){
        printf("Error: %ul\n", (unsigned int)ERR_get_error());
    }
    RSA_free(rsa);
    return err;
}
Esempio n. 8
0
char* my_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_RSAPrivateKey(file,NULL,NULL,NULL)) == NULL) {
		ERR_print_errors_fp(stdout);
		return NULL;
	}

	rsa_len = RSA_size(p_rsa);
	p_de = (unsigned char*)malloc(rsa_len + 1);
	memset(p_de,0,rsa_len+1);
	if(RSA_private_decrypt(rsa_len,(unsigned char*)str,(unsigned char*)p_de,p_rsa,RSA_NO_PADDING) < 0) {
		return NULL;
	}

	RSA_free(p_rsa);
	fclose(file);
	return p_de;
}
Esempio n. 9
0
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;
}
Esempio n. 10
0
/*
 * rsa public key encrypt
 */
char* rsa_encrypt_public(unsigned char*txt,int txt_len,char* public_key_str,int p_len,int* enc_len)
{
	//char *public_key = "-----BEGIN RSA PUBLIC KEY-----\nMIGJAoGBAL331YpDOljAJznk4eNt0TfZJREYypIhWTN/gx0g1iUIaLPlFR7ydjaB\npd9V7G3GvvOf3mGijP+9LjKdgQ8p1pgDW7DeXZk2dTAeQ4hdY287/sw6NFKJxMXA\nFGoUdARObVespCZBdHSqo8kFMAjVGge6ZoH6nAjGzvIfijgsj+2jAgMBAAE=\n-----END RSA PUBLIC KEY-----\n";
	//char * private_key = "-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC999WKQzpYwCc55OHjbdE32SURGMqSIVkzf4MdINYlCGiz5RUe\n8nY2gaXfVextxr7zn95hooz/vS4ynYEPKdaYA1uw3l2ZNnUwHkOIXWNvO/7MOjRS\nicTFwBRqFHQETm1XrKQmQXR0qqPJBTAI1RoHumaB+pwIxs7yH4o4LI/towIDAQAB\nAoGBAI1ALF2EI2w+ZGxdzcBntXtLUI5n2qfReBwcogcUlWYv3Hp2yb+bFV7uA8IO\nh6AQeYd4xcffL+wwZJtqFb6Ko25XAei8Os3xjb9k5fCcyrmyY+5oeXdQHlcbd/f8\niy8/rOEHZTr4iBXe/8ADlQZlRUkYCblPZ4i4BgzBUB6HzhxhAkEA8wJRx/FjOo6F\noO1aTewbvFIv4Dckqq5j/pBu9fkv1AhMxSfdGnsYcuIn15Y1/RlnpxrmJNWgryvd\n+6LJGDgjWQJBAMgfoINe80YiPCdMoboMd/u1uf1BhwujbiJPSrS40lc3jfyPmHA4\n8hppo8QuELI4rXRE/im4c+zmyphxEyULpVsCQQDnD96JGin65MeE1AsYqpdYwmEJ\ndgVkUXt88wK+2ZizqMyubpAa/M6rdgTiRc7CASUAzF/myEYIKdLh0NAbOk3JAkAE\nxEQVfPh8bipSoU+k19EvzKdOcfYef9kKtirIXTKdYzRdlKoD2kdh+6wr6xD4vcLb\n5xzKr5sLRIAE24SiOEHLAkB1TBlvvvIltttSc9lOpq3UhmtHQJaS32lD2Lk2/zNx\nW6Jbsk+sCQXM0ww4GTCpHMISfokEPtqOPikPcVFs98Oj\n-----END RSA PRIVATE KEY-----\n";
    RSA* rsa;
    int rsa_len;
    char *p_en;
    #if 1
    //public_key = rsa_key_seliaze(public_key_str);
    BIO* p_bio = BIO_new_mem_buf(public_key_str, -1);
    printf("rsa_encrypt is %p \n",p_bio);
    rsa = PEM_read_bio_RSAPublicKey(p_bio, NULL, NULL, NULL); //PEM_read_bio_RSAPrivateKey
    if ( rsa == NULL ) {
        printf("RSA is NULL\n");
        return NULL;
    }
    #else
    FILE* file=fopen("/tmp/r_pub.key","r");
    rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL);//PEM_read_RSAPrivateKey
    #endif
    rsa_len=RSA_size(rsa);
    p_en=(unsigned char *)calloc(rsa_len+1,1);
    printf("rsa length = %d\n",rsa_len);
    int rc=0;
    if((rc=RSA_public_encrypt(txt_len,(unsigned char *)txt,(unsigned char*)p_en,rsa,RSA_PKCS1_PADDING))<=0) {
        int e=ERR_get_error();
        printf("error code is:%s\n",ERR_error_string(e,NULL));
        return NULL;
    }
    printf("rsa length = %d\n",strlen(p_en));
    RSA_free(rsa);
    *enc_len = rc;
    return p_en;
}
Esempio n. 11
0
void get_privkey_from_file(Octstr* s, RSA** priv_key, Octstr* passwd)
{
		char *password;
		char *filename;
		
        /* Check errors!!!! */
        FILE* fp;

		filename = octstr_get_cstr(s);
		password = passwd != NULL ? octstr_get_cstr(passwd) : NULL;
        
		/* Open the file specified by "s" */
        fp = fopen(filename,"r");
        if (fp == NULL) warning(0,"Can't read private key %s", filename);
        
        /* Load up that there certificate */
        *priv_key = PEM_read_RSAPrivateKey(fp,NULL,NULL,password);

        /* Close the file specified by "s" */        
        fclose(fp);
        
        if (priv_key == NULL) { 
                ERR_print_errors_fp (stderr);
        }
}
Esempio n. 12
0
wi_boolean_t wi_socket_context_set_ssl_privkey(wi_socket_context_t *context, wi_string_t *path) {
#ifdef WI_SSL
	FILE		*fp;
	
	fp = fopen(wi_string_cstring(path), "r");
	
	if(!fp) {
		wi_error_set_errno(errno);
		
		return false;
	}
		
	context->priv_rsa = PEM_read_RSAPrivateKey(fp, NULL, 0, NULL);
	
	if(!context->priv_rsa)
		wi_error_set_ssl_error();
	
	fclose(fp);
	
	return (context->priv_rsa != NULL);
#else
	wi_error_set_lib_error(WI_ERROR_SOCKET_NOSSL);
	
	return false;
#endif
}
Esempio n. 13
0
static RSA *
load_rsa_privkey(const char *path)
{
	FILE *fp;
	RSA *rsa = NULL;
	const char *p;
	char *passphrase = NULL;

	if ((fp = fopen(path, "r")) == 0)
		return NULL;

	if ((rsa = RSA_new()) == NULL) {
		fclose(fp);
		return NULL;
	}

	p = getenv("XBPS_PASSPHRASE");
	if (p) {
		passphrase = strdup(p);
	}
	rsa = PEM_read_RSAPrivateKey(fp, 0, NULL, passphrase);
	if (passphrase) {
		free(passphrase);
		passphrase = NULL;
	}
	fclose(fp);
	return rsa;
}
Esempio n. 14
0
/*
 * rsa private encrypt
*/
char* rsa_encrypt_private(unsigned char*txt,int txt_len,char* public_key_str,int p_len,int* enc_len)
{
    RSA* rsa;
    int rsa_len;
    char *p_en;
    #if 1
    //public_key = rsa_key_seliaze(public_key_str);
    BIO* p_bio = BIO_new_mem_buf(public_key_str, -1);
    printf("rsa_encrypt is %p \n",p_bio);
    rsa = PEM_read_bio_RSAPrivateKey(p_bio, NULL, NULL, NULL); //PEM_read_bio_RSAPrivateKey
    if ( rsa == NULL ) {
        printf("RSA is NULL\n");
        return NULL;
    }
    #else
    FILE* file=fopen("/tmp/r_pub.key","r");
    rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL);//PEM_read_RSAPrivateKey
    #endif
    rsa_len=RSA_size(rsa);
    p_en=(unsigned char *)calloc(rsa_len+1,1);
    //printf("rsa length = %d\n",rsa_len);
    int rc=0;
    if((rc=RSA_private_encrypt(txt_len,(unsigned char *)txt,(unsigned char*)p_en,rsa,RSA_PKCS1_PADDING))<=0) {
        int e=ERR_get_error();
        printf("error code is:%s\n",ERR_error_string(e,NULL));
        return NULL;
    }
    RSA_free(rsa);
    *enc_len = rc;
    return p_en;
}
Esempio n. 15
0
wi_rsa_t * wi_rsa_init_with_pem_file(wi_rsa_t *rsa, wi_string_t *path) {
	FILE		*fp;
	
	fp = fopen(wi_string_cstring(path), "r");
	
	if(!fp) {
		wi_error_set_errno(errno);
		
		wi_release(rsa);
		
		return NULL;
	}
	
	rsa->rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
	
	fclose(fp);
	
	if(!rsa->rsa) {
		wi_error_set_openssl_error();
		
		wi_release(rsa);
		
		return NULL;
	}
	
	return rsa;
}
Esempio n. 16
0
int
openssl_read_pem_seckey(const char *f, __ops_key_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_RSAPrivateKey(fp, NULL, NULL, NULL);
        
        key->key.seckey.key.rsa.d = rsa->d;
		key->key.seckey.key.rsa.p = rsa->p;
		key->key.seckey.key.rsa.q = rsa->q;
		key->key.seckey.key.rsa.d = rsa->d;
	} else if (strcmp(type, "ssh-dss") == 0) {
		if ((dsa = PEM_read_DSAPrivateKey(fp, NULL, NULL, NULL)) == NULL) {
			ok = 0;
		} else {
			key->key.seckey.key.dsa.x = dsa->priv_key;
		}
	} else {
		ok = 0;
	}
	(void) fclose(fp);
	return ok;
}
Esempio n. 17
0
    int rsa_priv_decrypt(char ** str_out, char *str_in, size_t str_in_sz, char *key_file, char * keypass)
    {
        RSA * priv_key = NULL;
        FILE * priv_key_file;
        
        OpenSSL_add_all_algorithms();
        OpenSSL_add_all_ciphers();
        ERR_load_crypto_strings();
        
        priv_key_file = fopen(key_file, "rb");
        priv_key = PEM_read_RSAPrivateKey(priv_key_file, NULL, NULL, keypass);
        fclose(priv_key_file);

        if (!priv_key) {
            std::cerr << ERR_error_string(ERR_get_error(), NULL) << std::endl;
            return -1;
        }

        int key_size = RSA_size(priv_key);
        unsigned char *ustr_out = (unsigned char *)malloc(key_size);
        
        int len = RSA_private_decrypt(str_in_sz, (unsigned char *)&str_in[0], ustr_out, priv_key, RSA_PKCS1_PADDING);
        
        if (len == -1) {
            std::cerr << "RSA_private_decrypt error (rsa_priv_decrypt)." << std::endl;
            std::cerr << ERR_error_string(ERR_get_error(), NULL) << std::endl;
            return -1;
        }
        
        *str_out = (char *)ustr_out;
        return len;
    }
Esempio n. 18
0
static gint
lua_rsa_privkey_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 private key from file: %s, %s",
				filename,
				strerror (errno));
			lua_pushnil (L);
		}
		else {
			if (!PEM_read_RSAPrivateKey (f, &rsa, NULL, NULL)) {
				msg_err ("cannot open private key 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_privkey}", -1);
				*prsa = rsa;
			}
			fclose (f);
		}
	}
	else {
		lua_pushnil (L);
	}
	return 1;
}
Esempio n. 19
0
/**
 * rsa_get_priv_key() - read a private key from a .key file
 *
 * @keydir:	Directory containins the key
 * @name	Name of key file (will have a .key extension)
 * @rsap	Returns RSA object, or NULL on failure
 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
 */
static int rsa_get_priv_key(const char *keydir, const char *name, RSA **rsap)
{
	char path[1024];
	RSA *rsa;
	FILE *f;

	*rsap = NULL;
	snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
	f = fopen(path, "r");
	if (!f) {
		fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
			path, strerror(errno));
		return -ENOENT;
	}

	rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path);
	if (!rsa) {
		rsa_err("Failure reading private key");
		fclose(f);
		return -EPROTO;
	}
	fclose(f);
	*rsap = rsa;

	return 0;
}
Esempio n. 20
0
int
main(int argc, char **argv)
{
	FILE *kfile;
	RSA *rsa = NULL;
	char ndata[257], ddata[257];
	/* respond privatefile challenge */
	if (argc < 3)
	{
		puts("Usage: respond privatefile challenge [passphrase]");
		return 0;
	}

	if (argc == 4)
	{
		/* This is TOTALLY insecure and not recommended, but for
		** interfacing with irc client scripts, it's either this
		** or don't use a passphrase.
		**
		** The likelihood of a passphrase leaking isn't TOO great,
		** only ps auxww will show it, and even then, only at the
		** precise moment this is called.
		*/
		insecure_mode = 1;
		pass_param = argv[3];
	}

	if (!(kfile = fopen(argv[1], "r")))
	{
		puts("Could not open the private keyfile.");
		return 0;
	}
	
	SSLeay_add_all_ciphers();
	rsa = PEM_read_RSAPrivateKey(kfile, NULL,pass_cb, NULL);
  
	if(!rsa)
	{
		puts("Unable to read your private key, is the passphrase wrong?");
		return 0;
	}

	 fclose(kfile);
	if (hex_to_binary(argv[2], ndata, 128) != 128)
	{
		puts("Bad challenge.");
		return -1;
	}

	if (RSA_private_decrypt(128, (unsigned char*)ndata,
		(unsigned char*)ddata, rsa, RSA_PKCS1_PADDING) == -1)
	{
		puts("Decryption error.");
		return -1;
	}
	binary_to_hex((unsigned char*)ddata, ndata, 32);
	puts(ndata);
	return 0;
}
Esempio n. 21
0
bool read_rsa_private_key(void) {
    FILE *fp;
    char *fname, *key, *pubkey;
    struct stat s;

    if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) {
        if(!get_config_string(lookup_config(config_tree, "PublicKey"), &pubkey)) {
            logger(LOG_ERR, "PrivateKey used but no PublicKey found!");
            return false;
        }
        myself->connection->rsa_key = RSA_new();
//		RSA_blinding_on(myself->connection->rsa_key, NULL);
        BN_hex2bn(&myself->connection->rsa_key->d, key);
        BN_hex2bn(&myself->connection->rsa_key->n, pubkey);
        BN_hex2bn(&myself->connection->rsa_key->e, "FFFF");
        free(key);
        free(pubkey);
        return true;
    }

    if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
        xasprintf(&fname, "%s/rsa_key.priv", confbase);

    fp = fopen(fname, "r");

    if(!fp) {
        logger(LOG_ERR, "Error reading RSA private key file `%s': %s",
               fname, strerror(errno));
        free(fname);
        return false;
    }

#if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
    if(fstat(fileno(fp), &s)) {
        logger(LOG_ERR, "Could not stat RSA private key file `%s': %s'",
               fname, strerror(errno));
        free(fname);
        return false;
    }

    if(s.st_mode & ~0100700)
        logger(LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
#endif

    myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
    fclose(fp);

    if(!myself->connection->rsa_key) {
        logger(LOG_ERR, "Reading RSA private key file `%s' failed: %s",
               fname, strerror(errno));
        free(fname);
        return false;
    }

    free(fname);
    return true;
}
Esempio n. 22
0
int load_rsa_pkey(RSA ** rsa_priv_key) {
	FILE *fp;
	// Read PEM Private Key
	fp = fopen(f_rsa_private_key, "r");
	if (fp) {
		LOG(DEBUG, "[API] Private key found");
		*rsa_priv_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
	} else {
                LOG(DEBUG, "[API] No private key found, generating new key");
                if (generate_rsa_pkey() < 0)
			return -1;

		fp = fopen(f_rsa_private_key, "r");
		*rsa_priv_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
	}
	fclose(fp);
	return 0;
}
Esempio n. 23
0
void OAuthTokenEndpoint::setRSAKey(const std::string &path)
{
  if (privateKey)
    RSA_free(privateKey);
  RSA* rsa = RSA_new();
  privateKey = PEM_read_RSAPrivateKey(fopen(path.c_str(), "rb"), &rsa, NULL, NULL);
  if (!privateKey) {
    throw WException("OAuthTokenEndpoint: invalid RSA key \"" + path + "\"");
  }
}
Esempio n. 24
0
int
openssl_read_pem_seckey(const char *f, __ops_key_t *key, const char *type, int verbose)
{
	FILE	*fp;
	char	 prompt[BUFSIZ];
	char	*pass;
	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) {
		if ((rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL)) == NULL) {
			(void) snprintf(prompt, sizeof(prompt), "netpgp PEM %s passphrase: ", f);
			do {
				pass = getpass(prompt);
				rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, pass);
			} while (rsa == NULL);
		}
		key->key.seckey.key.rsa.d = rsa->d;
		key->key.seckey.key.rsa.p = rsa->p;
		key->key.seckey.key.rsa.q = rsa->q;
		key->key.seckey.key.rsa.d = rsa->d;
	} else if (strcmp(type, "ssh-dss") == 0) {
		if ((dsa = PEM_read_DSAPrivateKey(fp, NULL, NULL, NULL)) == NULL) {
			ok = 0;
		} else {
			key->key.seckey.key.dsa.x = dsa->priv_key;
		}
	} else {
		ok = 0;
	}
	(void) fclose(fp);
	return ok;
}
Esempio n. 25
0
/* caller must free the returned string */
char * euca_sign_url (const char * verb, const char * date, const char * url)
{
	if (!initialized) euca_init_cert ();
		
    char * sig_str = NULL;
    RSA * rsa = NULL;
    FILE * fp = NULL;

    if ( verb==NULL || date==NULL || url==NULL ) return NULL;

    if ( ( rsa = RSA_new() ) == NULL ) {
      logprintfl (EUCAERROR, "error: RSA_new() failed\n");
    } else if ( ( fp = fopen (pk_file, "r") ) == NULL) {
      logprintfl (EUCAERROR, "error: failed to open private key file %s\n", pk_file);
      RSA_free (rsa);
    } else {
      logprintfl (EUCADEBUG2, "euca_sign_url(): reading private key file %s\n", pk_file);
      PEM_read_RSAPrivateKey(fp, &rsa, NULL, NULL); /* read the PEM-encoded file into rsa struct */
      if ( rsa==NULL ) {
	logprintfl (EUCAERROR, "error: failed to read private key file %s\n", pk_file);
      } else {
	unsigned char * sig;
        
	// RSA_print_fp (stdout, rsa, 0); /* (for debugging) */
	if ( (sig = malloc(RSA_size(rsa))) == NULL) {
	  logprintfl (EUCAERROR, "error: out of memory (for RSA key)\n");
	} else {
	  unsigned char sha1 [SHA_DIGEST_LENGTH];
#define BUFSIZE 2024
	  char input [BUFSIZE];
	  unsigned int siglen;
	  int ret;
	  
	  /* finally, SHA1 and sign with PK */
	  assert ((strlen(verb)+strlen(date)+strlen(url)+4)<=BUFSIZE);
	  snprintf (input, BUFSIZE, "%s\n%s\n%s\n", verb, date, url);
	  logprintfl (EUCADEBUG2, "euca_sign_url(): signing input %s\n", get_string_stats(input));	
	  SHA1 ((unsigned char *)input, strlen(input), sha1);
	  if ((ret = RSA_sign (NID_sha1, sha1, SHA_DIGEST_LENGTH, sig, &siglen, rsa))!=1) {
	    logprintfl (EUCAERROR, "error: RSA_sign() failed\n");
	  } else {
	    logprintfl (EUCADEBUG2, "euca_sign_url(): signing output %d\n", sig[siglen-1]);	
	    sig_str = base64_enc (sig, siglen);
	    logprintfl (EUCADEBUG2, "euca_sign_url(): base64 signature %s\n", get_string_stats((char *)sig_str));	
	  }
	  free (sig);
	}
	RSA_free (rsa);
      }            
      fclose(fp);
    }
    
    return sig_str;
}
Esempio n. 26
0
int
read_keypair_pem(FILE *fp, struct keypair** KP)
{
	(*KP) = (struct keypair*) calloc(sizeof(struct keypair), 1);
	RSA *private_key_rsa;
	PEM_read_RSAPrivateKey(fp, &private_key_rsa, NULL, NULL);
	ccn_keypair_from_rsa(private_key_rsa, &(*KP)->private_key, &(*KP)->public_key);
	create_public_key_digest(private_key_rsa, &(*KP)->public_key_digest, &(*KP)->public_key_digest_len);
	RSA_free(private_key_rsa);
	return 0;
}
Esempio n. 27
0
int rsa_encrypt (const char *const private_key_name, void *input, int ilen, void **output, int *olen) {
  vkprintf (3, "rsa_encrypt (private_key_name = %s, ilen = %d)\n", private_key_name, ilen);
  int err = 0;
  RSA *privKey = NULL;
  *output = NULL;
  *olen = -1;
  FILE *f = fopen (private_key_name, "rb");
  if (f == NULL) {
    kprintf ("Couldn't open private key file: %s\n", private_key_name);
    return -1;
  }
  privKey = PEM_read_RSAPrivateKey (f, NULL, NULL, NULL);
  if (privKey == NULL) {
    kprintf ("PEM_read_RSAPrivateKey returns NULL.\n");
    err = -2;
    goto clean;
  }
  fclose (f);
  f = NULL;
  unsigned char key[32], iv[32];
  generate_aes_key (key, iv);
  const int rsa_size = RSA_size (privKey);
  *olen = 4 + rsa_size + 32 + ilen + AES_BLOCK_SIZE;
  unsigned char *b = *output = malloc (*olen);

  memcpy (b, &rsa_size, 4);
  if (!RSA_private_encrypt (32, key, b + 4, privKey, RSA_PKCS1_PADDING)) {
    kprintf ("RSA_private_encrypt fail.\n");
    err = -3;
    goto clean;
  }
  memcpy (b + 4 + rsa_size, iv, 32);
  EVP_CIPHER_CTX e;
  EVP_CIPHER_CTX_init (&e);
  EVP_EncryptInit_ex (&e, EVP_aes_256_cbc(), NULL, key, iv);
  int c_len, f_len;
  EVP_EncryptUpdate (&e, b + 4 + rsa_size + 32, &c_len, input, ilen);
  EVP_EncryptFinal_ex (&e, b + 4 + rsa_size + 32 + c_len, &f_len);
  EVP_CIPHER_CTX_cleanup (&e);
  int r = 4 + rsa_size + 32 + c_len + f_len;
  vkprintf (3, "c_len = %d, f_len = %d\n", c_len, f_len);
  assert (r <= *olen);
  *olen = r;
  clean:
  if (f != NULL) {
    fclose (f);
  }
  if (privKey) {
    RSA_free (privKey);
  }

  return err;
}
Esempio n. 28
0
/**
 * @brief Initialize the signing subsystem
 *
 * @param key_filename The pathname to the private key file
 * @param bad_passphrase Pointer to flag that is set if the failure was
 *        likley due to an incorrect passphrase
 *
 * @returns True on success, false on failure.
 */
bool sign_init(char * key_filename, bool * bad_passphrase) {
    FILE * fp;

    if (bad_passphrase) {
        *bad_passphrase = false;
    }

    if (!crypto_initialized) {

        /* (From: https://wiki.openssl.org/index.php/Libcrypto_API) */
        /* Load the human readable error strings for libcrypto */
        ERR_load_crypto_strings();

        /* Load all digest and cipher algorithms */
        OpenSSL_add_all_algorithms();

        /* Load config file, and other important initialisation */
        OPENSSL_config(NULL);

        crypto_initialized = true;
    }

    /**
     * Load the RSA key object from the private key file
     * (see: http://hayageek.com/rsa-encryption-decryption-openssl-c/#private-encrypt)
     */
    fp = fopen(key_filename,"rb");
    if (fp == NULL) {
        fprintf(stderr, "ERROR: Can't open private key '%s' (err %d)\n",
                key_filename, errno);
        return false;
    }
    rsa = RSA_new();
    if (rsa == NULL) {
        fprintf(stderr, "ERROR: Can't allocate RSA for key '%s': %s\n",
               key_filename, ERR_error_string(ERR_get_error(), NULL));
            return false;
    } else {
        rsa = PEM_read_RSAPrivateKey(fp, &rsa, NULL, passphrase);
        if (rsa == NULL) {
            fprintf(stderr,
                    "ERROR: Can't read private key '%s' (%s)\n", key_filename,
                    ERR_error_string(ERR_get_error(), NULL));
            if (bad_passphrase) {
                *bad_passphrase = true;
            }
            return false;
        }
    }

    return true;
}
Esempio n. 29
0
    RSA* rsa_read_private_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)
            return nullptr;

        RSA* rsa = PEM_read_RSAPrivateKey(pem_file, NULL,NULL, NULL);

        fclose(pem_file);

        return rsa;
    }
Esempio n. 30
0
RSA* get_private_key(){
	RSA* rsa=NULL;	
	FILE* bp=fopen("privatekey.pem","r");
	if(bp==NULL){
		printf("Error opening private key file\n");
	}
	rsa=PEM_read_RSAPrivateKey(bp,NULL,NULL,NULL);
	if(rsa==NULL){
		printf("Error reading private key from file\n");
	}
	fclose(bp);
	return rsa;
}