Node.JS C++ Native Addon read/write file? - c++

The current problem I am facing with my project is that I do not know how to read/write files from the native node.js addon.
I have to build a type of encryption decryption ( RC6 algorithm ) program. But in order to encrypt files, i should be able to somehow read and write to them from "node-webkit". I am building the .cc file with nw-gyp, and tried multiple possibilities but none worked.
I am building my project with "grunt-node-webkit-builder" and I simply want to read/write one file from the build folder "nw" where nw.exe is located.
The Structure looks like this:
.webkitbuilds
.releases
.nw
.win
.nw
encrypt.txt
ffmpegsumo.dll
icudt.dll
libEGL.dll
libGLESv2.dll
nw.exe
nw.pak
How can I read in my c++ native node.js addon that "encrypt.txt" file.
Help ?
Edit:
Is there any way to use libuv with crypto ++ ?
EDIT 2:
I have the following code. The moment I execute it, the window freezes.
hello.cc:
#include <node.h>
#include <v8.h>
#include <stdio.h>
#include <fcntl.h>
using namespace v8;
#define __S_IREAD 0400 /* Read by owner. */
#define __S_IWRITE 0200 /* Write by owner. */
#define __S_IEXEC 0100 /* Execute by owner. */
#define S_IRUSR __S_IREAD /* Read by owner. */
uv_loop_t* loop;
uv_fs_t open_req;
void open_cb(uv_fs_t* req);
const char* path = "encrypt.txt";
void open_cb(uv_fs_t* req) {
int result = req->result;
if (result == -1) {
fprintf(stderr, "Error at opening file: %s\n",
uv_strerror(uv_last_error(loop)));
}
uv_fs_req_cleanup(req);
printf("Successfully opened file.\n");
}
char *get(v8::Local<v8::Value> value, const char *fallback = "") {
if (value->IsString()) {
v8::String::AsciiValue string(value);
char *str = (char *) malloc(string.length() + 1);
strcpy(str, *string);
return str;
}
char *str = (char *) malloc(strlen(fallback) + 1);
strcpy(str, fallback);
return str;
}
Handle<Value> Encrypt(const Arguments& args) {
HandleScope scope;
char* textToEncrypt = get(args[0], "str");
char* password = get(args[1], "str");
loop = uv_default_loop();
int r = uv_fs_open(loop, &open_req, path, O_RDONLY, S_IRUSR, open_cb);
if (r) {
fprintf(stderr, "Error at opening file: %s\n",
uv_strerror(uv_last_error(loop)));
}
uv_run(loop, UV_RUN_DEFAULT);
return scope.Close(String::New("done"));
}
void Init(Handle<Object> exports) {
exports->Set(String::NewSymbol("Encrypt"),
FunctionTemplate::New(Encrypt)->GetFunction());
}
NODE_MODULE(hello, Init)
In Javascript :
var application = require('./js/build/Release/hello');
var encrypted_data = "";
$(document).ready(function() {
$('#btn_encrypt').on('click', function() {
encrypted_data = application.Encrypt("val","val");
console.log(encrypted_data);
})
});

Related

How can I start a download from c++ code compiled web assembly?

I've been trying to not do this javascript side and I haven't found anything satisfying yet.
Fetch API seems to be a good lead, but I can't seem to find a way to start the download in the browser so it can download a zip file.
This is emscripten code snippet, but it seems to be a local file of some sort.
#include <stdio.h>
#include <string.h>
#include <emscripten/fetch.h>
void downloadSucceeded(emscripten_fetch_t *fetch) {
printf("Finished downloading %llu bytes from URL %s.\n", fetch->numBytes, fetch->url);
// The data is now available at fetch->data[0] through fetch->data[fetch->numBytes-1];
emscripten_fetch_close(fetch); // Free data associated with the fetch.
}
void downloadFailed(emscripten_fetch_t *fetch) {
printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch->url, fetch->status);
emscripten_fetch_close(fetch); // Also free data on failure.
}
int main() {
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
attr.onsuccess = downloadSucceeded;
attr.onerror = downloadFailed;
emscripten_fetch(&attr, "myfile.dat");
}
Add this to your cpp file.
EM_JS(void, DownloadUrl, (const char* str),
{
url = UTF8ToString(str);
var hiddenIFrameID = 'hiddenDownloader';
var iframe = document.getElementById(hiddenIFrameID);
if (iframe === null)
{
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
});
And an example on how to use it.
void Device::DrawContent()
{
ImGui::Begin("DW Store");
if (ImGui::Button("Download"))
{
DownloadUrl("https://dotnet.microsoft.com/download/dotnet/thank-you/sdk-5.0.402-macos-x64-installer");
}
ImGui::End();
}

Calling a Constructor in a custom .NET Core Host

I am trying to write a .NET Core host using coreclr.h. To do this I am trying to create function pointers to the c# code. I am able to call the static methods from my host, but calling the methods that depend on an object directly are not able to be called, ideally I would like to be able to call the constructor and all non-static methods from the C++ without modifying the C#. I can call Multiply5 and Main fine, but there is a segfault when the Program constructor or Add is called, is there any way to fix this? This is a Linux system so C++/CLI is not an option.
C++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include "coreclrhost.h"
#include <iostream>
#define MANAGED_ASSEMBLY "TestConsole.dll"
#include <dirent.h>
#include <dlfcn.h>
#include <limits.h>
#define FS_SEPARATOR "/"
#define PATH_DELIMITER ":"
#define MAX_PATH PATH_MAX
#define CORECLR_FILE_NAME "libcoreclr.so"
// Function pointer types for the managed call and callback
typedef int (*report_callback_ptr)(int progress);
typedef char* (*doWork_ptr)(const char* jobName, int iterations, int dataSize, double* data, report_callback_ptr callbackFunction);
typedef int (*Multiply5_ptr)(const int i);
typedef (*Constructor_ptr)(int i1, int i2);
typedef int (*ReturnInt_ptr)();
void BuildTpaList(const char* directory, const char* extension, std::string& tpaList);
int main(int argc, char* argv[])
{
// Get the current executable's directory
// This sample assumes that both CoreCLR and the
// managed assembly to be loaded are next to this host
// so we need to get the current path in order to locate those.
char runtimePath[MAX_PATH];
#if WINDOWS
GetFullPathNameA(argv[0], MAX_PATH, runtimePath, NULL);
#elif LINUX
realpath(argv[0], runtimePath);
#endif
char *last_slash = strrchr(runtimePath, FS_SEPARATOR[0]);
if (last_slash != NULL)
*last_slash = 0;
// Construct the CoreCLR path
// For this sample, we know CoreCLR's path. For other hosts,
// it may be necessary to probe for coreclr.dll/libcoreclr.so
std::string coreClrPath(runtimePath);
coreClrPath.append(FS_SEPARATOR);
coreClrPath.append(CORECLR_FILE_NAME);
// Construct the managed library path
std::string managedLibraryPath(runtimePath);
managedLibraryPath.append(FS_SEPARATOR);
managedLibraryPath.append(MANAGED_ASSEMBLY);
//
// STEP 1: Load CoreCLR (coreclr.dll/libcoreclr.so)
//
#if WINDOWS
// <Snippet1>
HMODULE coreClr = LoadLibraryExA(coreClrPath.c_str(), NULL, 0);
// </Snippet1>
#elif LINUX
void *coreClr = dlopen(coreClrPath.c_str(), RTLD_NOW | RTLD_LOCAL);
#endif
if (coreClr == NULL)
{
printf("ERROR: Failed to load CoreCLR from %s\n", coreClrPath.c_str());
return -1;
}
else
{
printf("Loaded CoreCLR from %s\n", coreClrPath.c_str());
}
//
// STEP 2: Get CoreCLR hosting functions
//
#if WINDOWS
// <Snippet2>
coreclr_initialize_ptr initializeCoreClr = (coreclr_initialize_ptr)GetProcAddress(coreClr, "coreclr_initialize");
coreclr_create_delegate_ptr createManagedDelegate = (coreclr_create_delegate_ptr)GetProcAddress(coreClr, "coreclr_create_delegate");
coreclr_shutdown_ptr shutdownCoreClr = (coreclr_shutdown_ptr)GetProcAddress(coreClr, "coreclr_shutdown");
// </Snippet2>
#elif LINUX
coreclr_initialize_ptr initializeCoreClr = (coreclr_initialize_ptr)dlsym(coreClr, "coreclr_initialize");
coreclr_create_delegate_ptr createManagedDelegate = (coreclr_create_delegate_ptr)dlsym(coreClr, "coreclr_create_delegate");
coreclr_shutdown_ptr shutdownCoreClr = (coreclr_shutdown_ptr)dlsym(coreClr, "coreclr_shutdown");
#endif
if (initializeCoreClr == NULL)
{
printf("coreclr_initialize not found");
return -1;
}
if (createManagedDelegate == NULL)
{
printf("coreclr_create_delegate not found");
return -1;
}
if (shutdownCoreClr == NULL)
{
printf("coreclr_shutdown not found");
return -1;
}
//
// STEP 3: Construct properties used when starting the runtime
//
// Construct the trusted platform assemblies (TPA) list
// This is the list of assemblies that .NET Core can load as
// trusted system assemblies.
// For this host (as with most), assemblies next to CoreCLR will
// be included in the TPA list
std::string tpaList;
BuildTpaList(runtimePath, ".dll", tpaList);
tpaList.append(managedLibraryPath);
tpaList.append(":");
// <Snippet3>
// Define CoreCLR properties
// Other properties related to assembly loading are common here,
// but for this simple sample, TRUSTED_PLATFORM_ASSEMBLIES is all
// that is needed. Check hosting documentation for other common properties.
const char* propertyKeys[] = {
"TRUSTED_PLATFORM_ASSEMBLIES" // Trusted assemblies
};
const char* propertyValues[] = {
tpaList.c_str()
};
// </Snippet3>
//
// STEP 4: Start the CoreCLR runtime
//
// <Snippet4>
void* hostHandle;
unsigned int domainId;
// This function both starts the .NET Core runtime and creates
// the default (and only) AppDomain
int hr = initializeCoreClr(
runtimePath, // App base path
"SampleHost", // AppDomain friendly name
sizeof(propertyKeys) / sizeof(char*), // Property count
propertyKeys, // Property names
propertyValues, // Property values
&hostHandle, // Host handle
&domainId); // AppDomain ID
// </Snippet4>
if (hr >= 0)
{
printf("CoreCLR started\n");
}
else
{
printf("coreclr_initialize failed - status: 0x%08x\n", hr);
return -1;
}
//
// STEP 5: Create delegate to managed code and invoke it
//
// <Snippet5>
Multiply5_ptr managedDelegate;
// The assembly name passed in the third parameter is a managed assembly name
// as described at https://learn.microsoft.com/dotnet/framework/app-domains/assembly-names
hr = createManagedDelegate(
hostHandle,
domainId,
"TestConsole, Version=1.0.0.0",
"TestConsole.Program",
"Multiply5",
(void**)&managedDelegate);
// </Snippet5>
if (hr >= 0)
{
printf("Managed delegate created\n");
}
else
{
printf("coreclr_create_delegate failed - status: 0x%08x\n", hr);
return -1;
}
int i = 20;
// Invoke the managed delegate and write the returned intS to the console
//char* ret = managedDelegate("Test job", 1, sizeof(int), i, ReportProgressCallback);
int ret = managedDelegate(i);
printf("Managed code returned: %d\n", ret);
Constructor_ptr programDelegate;
hr = createManagedDelegate(hostHandle,
domainId,
"TestConsole, Version=1.0.0.0",
"TestConsole.Program",
"Program",
(void**)&programDelegate);
int i1 = i;
int i2 = ret;
programDelegate(i1,i2);//Will seg fault here
ReturnInt_ptr addDelegate;
hr = createManagedDelegate(hostHandle,
domainId,
"TestConsole, Version=1.0.0.0",
"TestConsole.Program",
"Add",
(void**)&addDelegate);
i = addDelegate(); //Also triggers a seg fault.
printf("Managed code returned: %d\n", i);
// Strings returned to native code must be freed by the native code
#if WINDOWS
CoTaskMemFree(ret);
#elif LINUX
// free(ret);
#endif
//
// STEP 6: Shutdown CoreCLR
//
// <Snippet6>
hr = shutdownCoreClr(hostHandle, domainId);
// </Snippet6>
if (hr >= 0)
{
printf("CoreCLR successfully shutdown\n");
}
else
{
printf("coreclr_shutdown failed - status: 0x%08x\n", hr);
}
return 0;
}
#if WINDOWS
// Win32 directory search for .dll files
// <Snippet7>
void BuildTpaList(const char* directory, const char* extension, std::string& tpaList)
{
// This will add all files with a .dll extension to the TPA list.
// This will include unmanaged assemblies (coreclr.dll, for example) that don't
// belong on the TPA list. In a real host, only managed assemblies that the host
// expects to load should be included. Having extra unmanaged assemblies doesn't
// cause anything to fail, though, so this function just enumerates all dll's in
// order to keep this sample concise.
std::string searchPath(directory);
searchPath.append(FS_SEPARATOR);
searchPath.append("*");
searchPath.append(extension);
WIN32_FIND_DATAA findData;
HANDLE fileHandle = FindFirstFileA(searchPath.c_str(), &findData);
if (fileHandle != INVALID_HANDLE_VALUE)
{
do
{
// Append the assembly to the list
tpaList.append(directory);
tpaList.append(FS_SEPARATOR);
tpaList.append(findData.cFileName);
tpaList.append(PATH_DELIMITER);
// Note that the CLR does not guarantee which assembly will be loaded if an assembly
// is in the TPA list multiple times (perhaps from different paths or perhaps with different NI/NI.dll
// extensions. Therefore, a real host should probably add items to the list in priority order and only
// add a file if it's not already present on the list.
//
// For this simple sample, though, and because we're only loading TPA assemblies from a single path,
// and have no native images, we can ignore that complication.
}
while (FindNextFileA(fileHandle, &findData));
FindClose(fileHandle);
}
}
// </Snippet7>
#elif LINUX
// POSIX directory search for .dll files
void BuildTpaList(const char* directory, const char* extension, std::string& tpaList)
{
DIR* dir = opendir(directory);
struct dirent* entry;
int extLength = strlen(extension);
while ((entry = readdir(dir)) != NULL)
{
// This simple sample doesn't check for symlinks
std::string filename(entry->d_name);
// Check if the file has the right extension
int extPos = filename.length() - extLength;
if (extPos <= 0 || filename.compare(extPos, extLength, extension) != 0)
{
continue;
}
// Append the assembly to the list
tpaList.append(directory);
tpaList.append(FS_SEPARATOR);
tpaList.append(filename);
tpaList.append(PATH_DELIMITER);
// Note that the CLR does not guarantee which assembly will be loaded if an assembly
// is in the TPA list multiple times (perhaps from different paths or perhaps with different NI/NI.dll
// extensions. Therefore, a real host should probably add items to the list in priority order and only
// add a file if it's not already present on the list.
//
// For this simple sample, though, and because we're only loading TPA assemblies from a single path,
// and have no native images, we can ignore that complication.
}
}
#endif
C#
namespace TestConsole
{
public class Program
{
IntTest i;
Program(int i1, int i2){
i = new IntTest(i1,i2);
}
public static void Main()
{
Program p = new Program(23,12);
Console.WriteLine(p.Add());
}
// This test method doesn't actually do anything, it just takes some input parameters,
// waits (in a loop) for a bit, invoking the callback function periodically, and
// then returns a string version of the double[] passed in.
//[return: MarshalAs(UnmanagedType.I4)]
public static int Return5(){
return 5;
}
public int Add(){
return i.Add();
}
private static int Multiply5(int i){
return 5*i;
}
}
}
IntTest is an external library.
So there is no way to do this all free c++, the other option is to wrap the C# method in a static one and create a function pointer that way.

Passing const char* into constructor gives null

I'm trying to make a simple logger to log to a file to give me debug information about my program. I want to avoid using a library so I'm making one myself.
logging.cpp
#include <string.h> // String stuff
#include <time.h> // Time
#include "logging.hpp"
// Cathooks main logging util
CatLogger g_CatLogging("/tmp/nekohook.log");
//CatLogger g_CatLogging;
CatLogger::CatLogger(const char* _file_path, bool _ptime) : ptime(_ptime) {
file_path = _file_path;
}
CatLogger::~CatLogger() { fclose(log_handle); }
void CatLogger::log(const char* fmt, ...) {
// Basicly an init, because this cant be done on construct
if (log_handle == nullptr) {
log_handle = fopen(file_path, "w");
}
// Print our time if needed
if (ptime) {
// Get our time
time_t current_time = time(0);
struct tm* time_info = localtime(&current_time);
// print it to a string
char timeString[10];
strftime(timeString, sizeof(timeString), "%H:%M:%S", time_info);
// Print the time into the log
fprintf(log_handle, "%% [%s] ", timeString);
}
// Get the string we want to log
char buffer[1024];
va_list list;
va_start(list, fmt);
vsprintf(buffer, fmt, list);
va_end(list);
// Write our log to the file
fprintf(log_handle, "%s\n", file_path, buffer);
fflush(log_handle);
// Push result var to a console here, if i ever make a console api
}
logging.hpp
#include <stdarg.h> // ... arg
#include <stdio.h> // fopen(), fprint(), fputs()
class CatLogger {
public:
CatLogger(const char* _file_path, bool _ptime = false);
~CatLogger();
void log(const char* fmt, ...); // Use to log with
private:
FILE* log_handle = 0; // Handle used to log to files with
const char* file_path; // Path to log file
const bool ptime; // Whether to print time
};
// Use this to log
extern CatLogger g_CatLogging;
When I use the log function, it fails. I have no idea why. I made a dummy function that crashes when ran to get info from gdb of the input. I input the file_path variable into it and it returns 0x0. I'm not sure why this happens, I've made a sample executable separate from the library I'm using this in and it works flawlessly. Could this be due to the way I'm linking libraries or the lack of?
Here is the library I am working on with a link directly to the logging file.
https://github.com/oneechanhax/nekohook/blob/master/src/util/logging.cpp
It crashes on fprintf() on both due to fopen not returning a file handle, which is in turn because const char* isn't being passes for some reason.
Please tell me a way to debug this or point out where this went wrong as I'm at a loss trying for myself.
EDIT:
If i replace the following in CatLogger::log
if (log_handle == nullptr) {
log_handle = fopen(file_path, "w");
}
With the following
if (log_handle == nullptr) {
log_handle = fopen("/tmp/nekohook.log", "w");
}
It now works but i cant change the log location for other log classes now...
EDIT2:
Here is some debug info. Somehow the const char* doesnt get saved into the class. Thats the main issue that i have...
example
Maybe the string becomes null after constructing...
There are a lot of potential bugs.
if (log_handle == nullptr) {
log_handle = fopen(file_path, "w");
if(!log_handle) {
perror("File opening failed"); // check your console output.
return EXIT_FAILURE;
}
}
// Get the string we want to log
char buffer[1024];
va_list list;
va_start(list, fmt);
vsprintf(buffer, fmt, list); // potential segmentation fault
va_end(list);
use this instead
int vsnprintf( char* buffer, std::size_t buf_size, const char* format, va_list vlist ); // (since C++11)
And more it the program is multithreaded.
This was a case of static init order fiasco where the const char* wouldn't get initialized before the function was called.
The solution was to make the file link first compared to other files and the object works now.

Get values from XML <tag> in C++ using libxml2

I am having a hard time to get the values from a XML file. We are using libxml2 and python (output to *.txt) and then C++ to read the *.txt file.
I would like to use libxml2 in C++ without going through Python. My problem is the reader (see example below). BTW: I do not get much from this example code from http://xmlsoft.org/examples/index.html#reader1.c
Could someone tell me how i get the value = xmlTextReaderConstValue(reader);
into a string?
In summary: Loop through XMLdoc {if "XML-tag-" == 'tag' then store value/content of "XML-tag-" in mystring}
M
/**
* section: xmlReader
* synopsis: Parse an XML file with an xmlReader
* purpose: Demonstrate the use of xmlReaderForFile() to parse an XML file
* and dump the informations about the nodes found in the process.
* (Note that the XMLReader functions require libxml2 version later
* than 2.6.)
* usage: reader1 <filename>
* test: reader1 test2.xml > reader1.tmp && diff reader1.tmp $(srcdir)/reader1.res
* author: Daniel Veillard
* copy: see Copyright for the status of this software.
*/
#include <stdio.h>
#include <libxml/xmlreader.h>
#ifdef LIBXML_READER_ENABLED
/**
* processNode:
* #reader: the xmlReader
*
* Dump information about the current node
*/
static void
processNode(xmlTextReaderPtr reader) {
const xmlChar *name, *value;
name = xmlTextReaderConstName(reader);
if (name == NULL)
name = BAD_CAST "--";
value = xmlTextReaderConstValue(reader);
printf("%d %d %s %d %d",
xmlTextReaderDepth(reader),
xmlTextReaderNodeType(reader),
name,
xmlTextReaderIsEmptyElement(reader),
xmlTextReaderHasValue(reader));
if (value == NULL)
printf("\n");
else {
if (xmlStrlen(value) > 40)
printf(" %.40s...\n", value);
else
printf(" %s\n", value);
}
}
/**
* streamFile:
* #filename: the file name to parse
*
* Parse and print information about an XML file.
*/
static void
streamFile(const char *filename) {
xmlTextReaderPtr reader;
int ret;
reader = xmlReaderForFile(filename, NULL, 0);
if (reader != NULL) {
ret = xmlTextReaderRead(reader);
while (ret == 1) {
processNode(reader);
ret = xmlTextReaderRead(reader);
}
xmlFreeTextReader(reader);
if (ret != 0) {
fprintf(stderr, "%s : failed to parse\n", filename);
}
} else {
fprintf(stderr, "Unable to open %s\n", filename);
}
}
int main(int argc, char **argv) {
if (argc != 2)
return(1);
/*
* this initialize the library and check potential ABI mismatches
* between the version it was compiled for and the actual shared
* library used.
*/
LIBXML_TEST_VERSION
streamFile(argv[1]);
/*
* Cleanup function for the XML library.
*/
xmlCleanupParser();
/*
* this is to debug memory for regression tests
*/
xmlMemoryDump();
return(0);
}
#else
int main(void) {
fprintf(stderr, "XInclude support not compiled in\n");
exit(1);
}
#endif
I've been using this cast to get the std::string out of the const xmlChar* :
my_std_string.assign(reinterpret_cast<const char*>(my_const_xmlchar_ptr));
Don't know if it's the best way but worked well.
I think that what you name the "XML-tag-" is actualy the return of xmlTextReaderConstName(reader), name, wich is a const xmlChar*. (See libxml2 xmlreader)
I suggest the use of string::compare to test the string equality with your "-tag-".
If strings match, you can then get the value, a const xmlChar* again, with the xmlTextReaderConstValue(reader); function, cast into a string with the same fashion way, then store it.
value is a C null-terminated (and statically allocated) string already.
If you want to get std::string, you can use something like:
std::string val = value;
If you want a C null-terminated string which will be owned by you:
xmlChar* val = xmlStrdup(value);

GnuPGME: GPG Signature C++

Has anyone written any tutorials or have any documentation on how to use GnuPGME so I would be able to write a function such as gpgSign(std::string fileToBeSigned, std::string outPutFileName) in C++?
Below is a C example with verbose comments that does what you are looking for - it is not the most direct approach, but should illustrate the how to accomplish signing a file. It does not handle selection of signers, but the GPGME docs should help you there.
You can save the file and make edits and test directly from the command line. To compile, just save as "gpgsign.c", and execute gcc gpgsign.c -lgpgme -o gpgsign (NOTE: you must have libgpgme installed). Then you can execute the using gpgsign <input file> <output file>
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <errno.h>
#include <locale.h>
#include <gpgme.h>
#define fail_if_err(err) \
do { \
if (err) { \
fprintf (stderr, "%s:%d: %s: %s\n", \
__FILE__, __LINE__, gpgme_strsource (err), \
gpgme_strerror (err)); \
exit (1); \
} \
} \
while (0)
void gpgSign(const char *fileToBeSigned, const char *outputFileName) {
gpgme_ctx_t ctx;
gpgme_error_t err;
gpgme_data_t in, out;
FILE *outputFile;
int BUF_SIZE = 512;
char buf[BUF_SIZE + 1];
int ret;
/* Set the GPGME signature mode
GPGME_SIG_MODE_NORMAL : Signature with data
GPGME_SIG_MODE_CLEAR : Clear signed text
GPGME_SIG_MODE_DETACH : Detached signature */
gpgme_sig_mode_t sigMode = GPGME_SIG_MODE_CLEAR;
/* Begin setup of GPGME */
gpgme_check_version (NULL);
setlocale (LC_ALL, "");
gpgme_set_locale (NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
#ifndef HAVE_W32_SYSTEM
gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
#endif
/* End setup of GPGME */
// Create the GPGME Context
err = gpgme_new (&ctx);
// Error handling
fail_if_err (err);
// Set the context to textmode
gpgme_set_textmode (ctx, 1);
// Enable ASCII armor on the context
gpgme_set_armor (ctx, 1);
// Create a data object pointing to the input file
err = gpgme_data_new_from_file (&in, fileToBeSigned, 1);
// Error handling
fail_if_err (err);
// Create a data object pointing to the out buffer
err = gpgme_data_new (&out);
// Error handling
fail_if_err (err);
// Sign the contents of "in" using the defined mode and place it into "out"
err = gpgme_op_sign (ctx, in, out, sigMode);
// Error handling
fail_if_err (err);
// Open the output file
outputFile = fopen (outputFileName, "w+");
// Rewind the "out" data object
ret = gpgme_data_seek (out, 0, SEEK_SET);
// Error handling
if (ret)
fail_if_err (gpgme_err_code_from_errno (errno));
// Read the contents of "out" and place it into buf
while ((ret = gpgme_data_read (out, buf, BUF_SIZE)) > 0) {
// Write the contents of "buf" to "outputFile"
fwrite (buf, ret, 1, outputFile);
}
// Error handling
if (ret < 0)
fail_if_err (gpgme_err_code_from_errno (errno));
// Close "outputFile"
fclose(outputFile);
// Release the "in" data object
gpgme_data_release (in);
// Release the "out" data object
gpgme_data_release (out);
// Release the context
gpgme_release (ctx);
}
int
main (int argc, char **argv) {
if (argc != 3) {
printf("Usage: gpgsign <input file> <output file>\n");
exit (1);
}
printf("Signing %s and placing the result into %s\n", argv[1], argv[2]);
gpgSign(argv[1], argv[2]);
return 0;
}
This answer probably comes too late, but if I were you I'd rather use Keyczar which is a high-level crypto toolkit with a simple API. Java, C++, Python bindings are available.
GPGME is still quite low-level IMO for someone who needs crypto functionality without too much tweaking. Of course a crypto expert needs this type of complexity.
Personally, I try to avoid libraries that require me to set up this engine and that context in 100 lines of boilerplate code before I can do something basic... but I am no expert at anything.