CX509PublicKeyClass initialize is failing at runtime with WIN32: 13 ERROR_INVALID_DATA - sdk

I am trying to populate the CX509PublicKeyClass() object using InitializeFromEncodedPublicKeyInfo(data); where data is from the file id_rsa.pub (KeyFilePath) that I created using ss-keygen client in windows.
Sample code I am tying with
The image also shows the exception that is being thrown.
I suspect the issue could be with the expected encoding
public virtual void InitializeFromEncodedPublicKeyInfo(string strEncodedPublicKeyInfo, EncodingType Encoding = EncodingType.XCN_CRYPT_STRING_BASE64);
and I have tried multiple combinations, Hex and base64 , default string etc but I am still seeing the same error.

The answer lies in understanding RSA key formats
Private key contains: modulus, private exponent, public exponent, prime 1, prime 2, exponent 1, exponent 2 and coefficient
Public key contains: only modulus and public exponent.
PEM format produced by OpenSSL is actually base64 encoded and wrapped key data in the binary format called DER. Thus, to work with PEM format you must actually work with DER.
DER format is based on Abstract Syntax Notation One (ASN.1) standard. The standard specifies the encoding of tree-like data structures. Two predefined data structures are used for private and public RSA keys. Though I didn’t find a good parser for the format, with a couple of notes from the standard in hand I wrote a class for encoding and decoding ASN.1 values.
PEM format contains base64 encoded DER data. It also adds a header and footer to it. Below is an example of PEM file for a private key.

Related

iOS AES256 decryption

I need to decrypt a string encrypted with AES256.
For example:
This is an encrypted string:
"U2FsdGVkX18egiyzJUY5gHS++2trNSYNSEXpJicKPBE="
using this key:
"70ca7c5b0f58ca290d39613fa3644251"
with the AES256 algorithm
The example string has been encrypted using:
https://code.google.com/p/crypto-js/
There are multiple tools that can be used to decrypt an AES256 encrypted string:
https://github.com/AlanQuatermain/aqtoolkit/tree/master/CommonCrypto
https://github.com/RNCryptor/RNCryptor
https://github.com/Gurpartap/AESCrypt-ObjC
I have tried them all but none of them was able to decrypt my string.
I'm sure it's encrypted correctly because I can decrypt it using this online tool:
http://www.appcove.com/tool/aes
Please help me.
Thank you,
George
-------------- EDIT --------------
Can you recommend a symmetric encryption/decryption algorithm for API(js)/iOS?
Something that you used to encrypt strings on the API and decrypt them on your iOS app.
Thank you
To get you started:
This is an encrypted string: "U2FsdGVkX18egiyzJUY5gHS++2trNSYNSEXpJicKPBE="
This is not an encrypted string. It is the Base64 rendering of an array of encrypted bytes. In order to decrypt it you first need to convert it from Base64 back into a byte array.
using this key: "70ca7c5b0f58ca290d39613fa3644251"
This is not a key. It is the hex string representation of the byte array which either is the actual key or can be used to derive the actual key. You need to convert it from a hex string back into a byte array.
with the AES256 algorithm
You need more information here: mode and padding at least.
What mode is being used? AES-ECB, AES-CBC, AES-CTR or some other mode? Look through the description to try and find out. The lack of an IV or a Nonce would probably indicate ECB mode, as Zaph's comment says. ECB mode is insecure, do not use it for any production code.
You also need to know what padding was used. Zaph says PKCS7 padding, which is very common, but the problem source should have told you that. You need to set the decryption method to expect the correct padding.
I'll give you a simple flow to show how AES works:
For the sake of clarity I'll use pseudo-objective-c to make it both understandable for you and fast for me.
// Here comes encryption process:
NSString *key = #"fsd7f897sfd8sfds…";
NSString *secretMessage = #"Confidential text";
AES *aes = [AES sharedAES];
NSString *encryptedMessage = [aes encryptWithKey:key message:secretMessage];
// Now is time for decryption:
Base64 *base64 = [Base64 sharedBase64];
NSString *messageToDecrypt = [base64 decode:encryptedMessage];
NSString *decryptedMesage = [aes decryptWithKey:key message:messageToDecrypt];
// Now you should have the result:
NSLog(decryptedMesage);
Take a look at http://travistidwell.com/jsencrypt/
From the google docs:
For the key, when you pass a string, it's treated as a passphrase and
used to derive an actual key and IV. Or you can pass a WordArray that
represents the actual key. If you pass the actual key, you must also
pass the actual IV.
For CryptoJS.AES.encrypt()
Is a string is passed in as the key another key will be derived and also an iv. This is going to be a compatibility problem because the method of actual key derivation would have to be know as well as the iv derivation and duplicated in iOS.
None of the above is a standard.
The solution is in JavaScript to pass in the key as a WordArray of the correct size (256 bits) and a WordArray iv.
Or per the docs:
"You can define your own formats in order to be compatible with other
crypto implementations. A format is an object with two
methods—stringify and parse—that converts between CipherParams objects
and ciphertext strings.
Then with these the same encryption/decryption can be matched in iOS.
Here is some information I figured out, this is WRT the encrypted data prior to base64 encoding:
The first 8 bytes are "Salted__" Probably used by the Javascript decryption to know the method to use.
The next 8 bytes are random. They are different for each encryption of the same data with same key They may be derived from the key with a random component.
The next bytes are in groups of 16 bytes (blocksize), just enough to contain the data + padding. Padding always adds at least one extra byte.
Because the iv is random the encrypted bytes will be different for each encryption with the same data and key but can be recovered by somehow using the key and leading bytes to re-generate the key and iv. The method is not secret, just unknown to me.
Of course this does not particularly help but does show the problem.

how to insert modulus and exponent of RSA public key into FGInt package(http://submanifold.be/)

I'm newby in RSA cryptographic methods... I need to verify incoming signature from device. The problem is, that I have to use a delphi IDE and delhi doesn't have implemented some RSA libraries. I find on web the FGInt package on this site: http://submanifold.be/. I download it(RSA.zip) and I'm in dark - I don't know, how can I put to this code my public key modulus and exponent.
The situation is as follows:
I have signature from device which I need to compare(verify) with calculated message(challenge). I have also an X509 certificate with embedded public key. I can extract this public key from these certificate. I can also extract modulus and exponent from public key. My problem is, that I don't know, how can I put the obtained modulus and exponent to RSAVerify procedure of FGInt package. The modulus is 128 bytes(I have it as an array of hexa numbers) long and exponent has value of 65537.
Can somebody help with my question, how can be modulus and exponent values inserted into procedure RSAVerify in FGint package?
If you need RSA functions and you're running on Windows, use the MSCRYPTO API. Info here: http://en.wikipedia.org/wiki/Microsoft_CryptoAPI and here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa380255(v=vs.85).aspx
If you intend to make your application available outside the US, incorporating custom or third party encryption logic into your application will make your app fall into the "software munitions" category of US export restrictions. You will have to apply for an export permit, have your code reviewed by US government reps, etc. or risk hefty fines and possibly criminal charges for export violations.
If your app instead links to the MSCRYPTO library, you don't have to do any of that. Microsoft takes care of getting export permits for the MSCRYPTO library shipped with Windows.

Storing RSA encrypted data as hexadecimal

I am using OpenSSL::PKey::RSA to encrypt/decrypt a string of data using a private key. I am storing the encrypted data in a column in a table as a string. I have gotten this implementation to work no problem using Base64.encode64 and Base64.decode64. However, I do not want to store the encrypted data as base 64, I would like to store it as hexadecimal in a string.
I'm currently using the following to store the encrypted data:
encrypted_data = pk.private_encrypt(plain_data).unpack('H*').first
This results in encrypted_Data equaling a string like that bellow, which easily stores in my database.
d70db8c36d6ccbadd1cca1263ff140df24e0112f636ac9ea92c28f27e443496c
My problem has come in the changing of this hexadecimal string back to the binary string that is needed to decrypt the data. I've tried several different approaches and none seem to work.
What is the best/easiest way to decrypt this hexadecimal string?
The opposite of unpack is pack, which is what you're looking for to get this hex string back to binary. Like so:
[encrypted_data].pack('H*')
Pack is a function on array, not string, so be sure you're passing the same array that unpack('H*') results in or else the output will not be the same.

Raw RSA decryption/signing

I'm implementing RSACryptoToken, that is an interface for RSA cryptographic tokens, according to the documentation.
There are twp methods, called decryptRSA and signRSA - they should be implemented.
In documentation there is an info, that they should perform a raw RSA decryption and raw RSA signing operations.
What means raw RSA operation?
Does it mean, without padding?
Does BlackBerry or Bouncy Castle provides such API?
Basically PKCS#1 v1.5 consists of three parts:
the RSA operations themselves,
the PKCS#1 padding and
an ASN.1 encodign of the hash.
The hash is ASN.1 encoded to include an ASN.1 Object Identifier which uniquely specifies the hash that is used, and the value, like this:
DigestInfo ::= SEQUENCE {
digestAlgorithm AlgorithmIdentifier,
digest OCTET STRING
}
This is directly copied from the PKCS#1 specifications (which are pretty readable and publicly available). Note that the encoding is directly specified as bytes as well in the standards.
Blackberry operations only provide 1) and 2), meaning that you have to supply an ASN.1, DER encoded structure containing the hash yourself. No such a structure is defined for the encryption/decryption, only the padding is removed.
Encryption uses random padding (internally) versus non-random padding for signatures. This allows you to encrypt "YES" twice, while an eavesdropper cannot detect if it is YES or NO. The padding is also required to protect the signature against attacks.
I solved the problem, the operations signRSA and decryptRSA should perform the same pure modulus operation
thanks for help

How to convert asn.1 erlang notation into asn.1 value notation

I want to receive aligned per encoded asn.1 message and decode it to asn.1 value notation. Is there any tools available? Erlang has support for encoding and decoding, and reading value notation from file, but decoding only gives erlang, not value notation.
'S1AP':decode('S1AP-PDU', [32,17,0,23,0,0,2,0,105,0,11,0,0,98,242,33,0,0,195,92,0,51,0,87,64,1,25]).
{ok,{successfulOutcome,{'SuccessfulOutcome',17,reject,{'S1SetupResponse',[{'ProtocolIE-Field',105,reject,[{'ServedGUMMEIsItem',["bò!"],["Ã\\"],["3"],asn1_NOVALUE}]},{'ProtocolIE-Field',87,ignore,25}]}}}}
How to continue with the above code. I would like to get the PDU like here http://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One#Example or below (taken from wiki site)
myQuestion FooQuestion ::= {
trackingNumber 5,
question "Anybody there?"
}
You need to include autogenerated hrl files that contain record definitions for your asn protocol data. They must be either in the same folder as asn1 source or in ../include. After that you'll be able to use record syntax myQuestion#'FooQuestion'{trackingNumber=TrackingNumber, question=Question} to pattern-match data.

Resources