Encrypt message using RSA on ESP32 - rsa

What I try to achieve here is to encrypt a message inside ESP32 app built using PlatformIO + Arduino framework.
After some searchings, I found this repo: https://github.com/espressif/arduino-esp32
There is a tool inside it seems able to help me achieve what I want https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/include/mbedtls/mbedtls/rsa.h
I imported the library "mbedtls" at https://platformio.org/lib/show/10874/mbedtls to the PlatformIO project and start work from there.
Question: How to load private key file in the app and encrypt the message using the RSA tool?
What I have currently is:
int ret = 1;
char buf[1024];
mbedtls_pk_init(&pk);
memset(buf, 0, sizeof(buf));
mbedtls_mpi_init(&N);
mbedtls_mpi_init(&P);
mbedtls_mpi_init(&Q);
mbedtls_mpi_init(&D);
mbedtls_mpi_init(&E);
mbedtls_mpi_init(&DP);
mbedtls_mpi_init(&DQ);
mbedtls_mpi_init(&QP);
ret = mbedtls_pk_parse_key(&pk, vendorPrivateKey, sizeof(vendorPrivateKey), NULL, NULL);
if (ret != 0) {
Serial.print(" failed! mbedtls_pk_parse_key returned: ");
Serial.print(-ret);
Serial.println();
}
if (mbedtls_pk_get_type(&pk) == MBEDTLS_PK_RSA) {
mbedtls_rsa_context *rsa = mbedtls_pk_rsa(pk);
if ((ret = mbedtls_rsa_export(rsa, &N, &P, &Q, &D, &E)) != 0
|| (ret = mbedtls_rsa_export_crt(rsa, &DP, &DQ, &QP)) != 0) {
Serial.println(" failed! could not export RSA parameters.");
}
}
For now I import the private key content directly in char* form (I'm not sure how to import a pem key file into app.) through the header file:
const unsigned char *vendorPrivateKey = reinterpret_cast<const unsigned char *>(VENDOR_PRIVATE_KEY);
where the value is stored inside secrets.h
Then when I ran the program, it yields the following error message for me:
failed! mbedtls_pk_parse_key returned: 15616
According to the pk.h file description, this error code 15616 in hexa is 3D00 which indicates /**< Invalid key tag or value. */
Is there any website that provides format checking and see if my private key file fits the requirements of the mbedtls?

Related

stop working when I write device manager information in txt file.

I found some sample code for device manager information, I try to write on txt file but there will stop working.
I don't know what is the root cause for this problem.
below link is the original sample code.
http://white5168.blogspot.com/2013/05/drivercmgetdevnodestatus.html#.W1FLpdIzaM9
below code is where I added.
Please help to check.
while (!SetupDiGetDeviceRegistryProperty(hDevInfo,
&DeviceInfoData,
ucSPDRP[j],
&DataType,
(PBYTE)Buffer,
BufferSize,
&BufferSize)) {
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
// Change the buffer size.
if (Buffer) LocalFree(Buffer);
Buffer = (LPSTR)LocalAlloc(LPTR, BufferSize * 2);
}
else
break;// Insert error handling here.
}
file << cStatus[j];
file << (const char *)Buffer << "\n";
file.flush();
}
printf("%s : %s\n", cStatus[j], (const char *)Buffer);
if (Buffer) LocalFree(Buffer);

PKCS#11 C_Encrypt fails with Bad Arguments for 128 bit AES key

I generate a 128-bit AES object using "C_CreateObject".
I then do the following to encrypt a piece of data and get a "Bad Argumnents" error on the call to "C_Encrypt" to get the encrypted data length.
char clear[] = "My name is Eric!";
buf_len = sizeof(clear) -1;
rv = pfunc11->C_EncryptInit(session, pMechanism, hObject);
if (rv != CKR_OK)
{
printf("ERROR: rv=0x%08X: initializing encryption:\n", (unsigned int)rv);
return false;
}
rv = pfunc11->C_Encrypt(session, (CK_BYTE_PTR)clear, (CK_ULONG)buf_len, NULL, pulEncryptedDataLen);
if (rv != CKR_OK)
{
printf("ERROR: rv=0x%08X: derror getting encryption data buffer length:\n", (unsigned int)rv);
return false;
}
What am I doing wrong here ?
Here is my mechanism definition -
CK_MECHANISM myMechanism = {CKM_AES_CBC_PAD, (CK_VOID_PTR)"01020304050607081122334455667788", (CK_ULONG)16};
CK_MECHANISM_PTR pMechanism = &myMechanism;
Your pulEncryptedDataLen is probably NULL which causes CKR_ARGUMENTS_BAD.
It is better to use e.g.:
CK_ULONG ulEncryptedDataLen;
...
rv = pfunc11->C_Encrypt(session, (CK_BYTE_PTR)clear, (CK_ULONG)buf_len, NULL, &ulEncryptedDataLen);
The number of bytes sufficient to store encryption result of a single-part encryption gets stored into ulEncryptedDataLen.
Also please note that your way of passing IV value is not correct as "01020304050607081122334455667788" results in an ASCII string (giving IV as 30313032303330343035303630373038 -- which is probably not what you want).
To get correct IV use "\x01\x02\x03\x04\x05\x06\x07\x08\x11\x22\x33\x44\x55\x66\x77\x88" instead.
Good luck!

error getting interface index using SIOCGIFINDEX

Hi i am trying to do packet injection using raw sockets, i have a problem in getting the interface index using SIOCGIFINDEX command of the ioctl. I am using ubuntu 12.04 as my OS. Please help the code is:
int BindRawSocketToInterface(char *device, int rawsock, int protocol)
{
struct sockaddr_ll sll;
struct ifreq ifr;
bzero(&sll, sizeof(sll));
bzero(&ifr, sizeof(ifr));
/* First Get the Interface Index */
strncpy ((char*) ifr.ifr_name, device, IFNAMSIZ);
if ((ioctl(rawsock, SIOCGIFINDEX, &ifr))== -1)
{
printf ("Error getting interface index!\n");
exit(-1);
}
/* Bind our rawsocket to this interface */
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons(protocol);
if ((bind(rawsock, (struct sockaddr*)&sll,sizeof(sll)))== -1)
{
perror("Error binding raw socket to interface \n");
exit(-1);
}
return 1;
}
Here is an example:
http://austinmarton.wordpress.com/2011/09/14/sending-raw-ethernet-packets-from-a-specific-interface-in-c-on-linux/
I hope this helps
As a reminder for anyone searching for such a function, i've seen many variants of this function and many of them have the following bug, so its probably a copy paste bug to be warned of:
strncpy ((char*) ifr.ifr_name, device, IFNAMSIZ);
This line has an OBOE (off-by-one error) and an unnecessary cast to char *.
strncpy (ifr.ifr_name, device, sizeof ifr.ifr_name - 1);
should be used instead.

How to get mach-o uuid of a running process?

to get UUID on mac i can use
dwarfdump -u path/to/compile/executable
also i can get UUID with simple crash
in 'Binary Images' section
Is the way to get UUID without crash on ios device?
An executable's (mach-o file) UUID is created by the linker ld and is stored in a load command named LC_UUID. You can see all load commands of a mach-o file using otool:
otool -l path_to_executable
> ...
> Load command 8
> cmd LC_UUID
> cmdsize 24
> uuid 3AB82BF6-8F53-39A0-BE2D-D5AEA84D8BA6
> ...
Any process can access its mach-o header using a global symbol named _mh_execute_header. Using this symbol you can iterate over the load commands to search LC_UUID. The payload of the command is the UUID:
#import <mach-o/ldsyms.h>
NSString *executableUUID()
{
const uint8_t *command = (const uint8_t *)(&_mh_execute_header + 1);
for (uint32_t idx = 0; idx < _mh_execute_header.ncmds; ++idx) {
if (((const struct load_command *)command)->cmd == LC_UUID) {
command += sizeof(struct load_command);
return [NSString stringWithFormat:#"%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
command[0], command[1], command[2], command[3],
command[4], command[5],
command[6], command[7],
command[8], command[9],
command[10], command[11], command[12], command[13], command[14], command[15]];
} else {
command += ((const struct load_command *)command)->cmdsize;
}
}
return nil;
}

collect packet length in pcap file

hi guys how can i collect the packet length for each packet in the pcap file? thanks a lot
I suggest a high-tech method, which very few people know: reading the documentation.
man pcap tells us there are actually two different lengths available:
caplen a bpf_u_int32 giving the number of bytes of the packet that are
available from the capture
len a bpf_u_int32 giving the length of the packet, in bytes (which
might be more than the number of bytes available from the cap-
ture, if the length of the packet is larger than the maximum num-
ber of bytes to capture)
An example in C:
/* Grab a packet */
packet = pcap_next(handle, &header);
if (packet == NULL) { /* End of file */
break;
}
printf ("Got a packet with length of [%d] \n",
header.len);
Another one in Python with the pcapy library:
import pcapy
reader = pcapy.open_offline("packets.pcap")
while True:
try:
(header, payload) = reader.next()
print "Got a packet of length %d" % header.getlen()
except pcapy.PcapError:
break
Those two examples below work fine:
using C, WinPcap
using python, SCAPY
(WinPcap)(Compiler CL , Microsoft VC)
I have wrote this function (in C) to get packet size and it works fine.
Don't forget to include pcap.h and set HAVE_REMOTE in compiler preprocessors
u_int getpkt_size(char * pcapfile){
pcap_t *indesc;
char errbuf[PCAP_ERRBUF_SIZE];
char source[PCAP_BUF_SIZE];
u_int res;
struct pcap_pkthdr *pktheader;
u_char *pktdata;
u_int pktsize=0;
/* Create the source string according to the new WinPcap syntax */
if ( pcap_createsrcstr( source, // variable that will keep the source string
PCAP_SRC_FILE, // we want to open a file
NULL, // remote host
NULL, // port on the remote host
pcapfile, // name of the file we want to open
errbuf // error buffer
) != 0)
{
fprintf(stderr,"\nError creating a source string\n");
return 0;
}
/* Open the capture file */
if ( (indesc= pcap_open(source, 65536, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf) ) == NULL)
{
fprintf(stderr,"\nUnable to open the file %s.\n", source);
return 0;
}
/* get the first packet*/
res=pcap_next_ex( indesc, &pktheader, &pktdata);
if (res !=1){
printf("\nError Reading PCAP File");
return 0;
}
/* Get the packet size*/
pktsize=pktheader->len;
/* Close the input file */
pcap_close(indesc);
return pktsize;
}
Another wroking Example in Python using the wonderful SCAPY
from scapy.all import *
pkts=rdpcap("data.pcap",1) # reading only 1 packet from the file
OnePkt=pkts[0]
print len(OnePkt) # prints the length of the packet