PublicKey from iOS doesn't supported by OpenSSL - iphone

I had created key pair on iOS with using SecKeyGeneratePair and then exported keys to publicKey and privateKey with using SecItemCopyMatching (Base64 encoded before exporting of course). Now I have a problem to encrypt data with using public key. I use next OpenSSL command:
openssl rsautl -encrypt -inkey publicKey -pubin -in text.txt -out text.enc
I got "unable to load Public Key" response from OpenSSL.
I have analyzed publicKey and noticed that it contains only next content:
SEQUENCE(2 elem)
| INTEGER(1023 bit)
| INTEGER 65537
when public keys generated by OpenSSL contains additional info about algorithm like that sample which was created by OpenSSL:
SEQUENCE(2 elem)
| SEQUENCE(2 elem)
| | OBJECT IDENTIFIER 1.2.840.113549.1.1.1
| | NULL
| BIT STRING(1 elem)
| | SEQUENCE(2 elem)
| | | INTEGER(1024 bit)
| | | INTEGER 65537
First question is why publicKey contains only 1023 bit for key? OpenSSL's public key has 1024 bit length for that.
I tried to create additional ASN.1 structure for publicKey which was generated by iOS (with using HEX editor and fixing SEQUENCE length). Its format is correct (I have checked that here http://lapo.it/asn1js/), but I still can't use it for OpenSSL. Looks like because public key returned by SecItemCopyMatching has lost byte.
I checked the content of privateKey also, because it contains publicKey inside. The length of the publicKey there also 1023 bits.
Can you help me please? Thanks in advance. Here is a key pair which was generated on iOS device:
publicKey:
MIGIAoGAaXp7vlZ5WmCzaL1rrBKXC8rJuc7EpH7Us/0t4R3hJoDOtRJxywegPY6wm45Oiud7UDh+9loebAg4dcpUP1le5SkbxrC9Qp8XahmvYVMXUYVGDiLTWID3e3PdE7CwEM5/lz1c1vRRWjR+2GzvV4xf5gRwCzZW1tXvXCNWsraqwE8CAwEAAQ==
privateKey:
MIICWwIBAAKBgGl6e75WeVpgs2i9a6wSlwvKybnOxKR+1LP9LeEd4SaAzrUSccsHoD2OsJuOTorne1A4fvZaHmwIOHXKVD9ZXuUpG8awvUKfF2oZr2FTF1GFRg4i01iA93tz3ROwsBDOf5c9XNb0UVo0fths71eMX+YEcAs2VtbV71wjVrK2qsBPAgMBAAECgYBolCowc2hqdUosZPJmbyAXbv5HHXzWY3Hc6v8cHhXnqPpJiXoNhQgZQGpWMOgqzIv0467t7jgPgK8KCosxLBjqvQTVzBkHTsBpBAaJgxzgP04pD8EnJp6uwwx8fZcP3PQOwGkmtWf2KyAcBZD3A+snCxGTRMDOrEPzQe6kBapBwQJBASG9Go92pjIqTRMMam5A5oUt9R1/iNx0wHowStyf2KHik1GRidaENIYkobZEzjKEbskcq3LGJGna163uu/Y55l8CQF0yLFHBdMi9hYX49s8Abzkd+3sGI29hFkLrL01ZB2xV/WceNLQH7jxplRClri9Ccr1QFkMGcaXRv2X+eNu6DBECQQEdlTxZzhQwfBtuPB2nwNa2zL6+rZdj3Lxfc7xGTFQF9MNKcg6P3825rt+qPZWUm45rMpQXVBBOOkO+kAK6xwU3AkBIE8vPFy25K0qfSOOpSQ68QAIFLcQuGgpbiwU0bwycrwyiuevM6O1J7+aHz3udtWiEHfJ5t/whYM0ElwDl/0fhAkEAq0EWoY8mQjHAGPMIhIty48fDbJCeFWFPx8lR+gegR1KwcIzcCGrYnHt8ihrfPm9ySjXwWDLYhBx0A5m+IbRZaA==

OpenSSL requires the key in X.509 format (see RFC 3280):
SubjectPublicKeyInfo ::= SEQUENCE {
algorithm AlgorithmIdentifier,
subjectPublicKey BIT STRING }
AlgorithmIdentifier ::= SEQUENCE {
algorithm OBJECT IDENTIFIER,
parameters ANY DEFINED BY algorithm OPTIONAL }
The "subjectPublicKey" string depends on the algorithm. For RSA it is (RFC 3447):
RSAPublicKey ::= SEQUENCE {
modulus INTEGER, -- n
publicExponent INTEGER -- e
}
I don't think it's a problem that the key is 1023 and not 1024 bits. But you can try to generate a few more and see if they're all 1023 bits long.
What does OpenSSL say when you try to use your own creation (the updated ASN.1 structure)? Can you post it here?
Also, OpenSSL expects it in PEM format with "-----BEGIN RSA PUBLIC KEY-----" and "-----END RSA PUBLIC KEY-----" around the Base64 data.

Related

How does salt get used in openssl passwd hash (md5)?

I was trying to manually generate the password hash stored in /etc/shadow (just for curiosity).
For example using salt a and password a with md5 hash algorithm, with the command
openssl passwd -1 -salt "a" a
i get
$1$a$44cUw6Nm5bX0muHWNIwub0
Where 1 correspond to md5 hashing algorithm, a is the salt and 44cUw6Nm5bX0muHWNIwub0 should be the actual hash.
I was expecting to get the same result calculating the md5 hash of aa (password and hash concatenated), and converting it in B64 (as explained on wikipedia) but I get a different output.
What is the right way to hash and encode the password and the salt?

Error decoding ciphertext with RSA using pycryptodome

I'm using pycryptodome to encrypt a text in this way:
def encrypt_with_rsa(plain_text):
#First Public Key Encryption
cipher_pub_obj = PKCS1_OAEP.new(RSA.importKey(my_public_key))
#encrypt
_secret_byte_obj = cipher_pub_obj.encrypt(plain_text.encode())
return _secret_byte_obj
After that, I want to divide all the string in 8 parts to get a char of each one. What I receive has this form:
b"gi?\xf4\xa8{\xe8\x1b\xec8\xd5\x96\*,t\xad\xb8D=\rCGq\xc5\xed........"
So I Try to decode that with utf-8, throws error:
** 'utf-8' codec can't decode byte 0x81 in position 5: invalid start byte **
I tried with utf-16 and 32, but no one works. I tried with latin1 too, but it ignores some parts and I don't want that. The text encoded above is changed to:
"gi?ô¨{è\x1bì8Õ\x96\*,t\xad¸D=\rCGqÅíh\x1b\x84\x0eí ó=#ÉîKô4B......"
Some parts are the same, i don´t know what type of encoding it uses, what can I do to use the encrypted text?

How to allow SHA1 hash function in chrony?

I use chrony to the synchronization between two devices. When I try to create a key with the SHA1 function, the next error appears:
chronyc>keygen 73 SHA1 256
Unknown hash function SHA1
How could I set up the SHA1 hash function?
i ran the command " keygen 73 sha1 256"
and got the same error message, the fix is to type SHA1 capital letters, and that made it working. hope this help someone.

Sign sha256 hash with RSA using pkcs#11 api?

I'm currently using pyPkcs11 to sign files.
The following call works for signing common files with RSA and sha256,
session.sign(privKey, toSign, Mechanism(CKM_SHA256_RSA_PKCS, None)
But some of my files are already hashed (sha256), and the signature needs to give the same output that would be given by this openSSL command:
openssl pkeyutl -sign -pkeyopt digest:sha256 -in <inFilePath> -inkey <keyPath> -out <outFilePath>
I have tried the following call, which does not generate a hash of the file before signature,
session.sign(privKey, toSign, Mechanism(CKM_RSA_PKCS, None)
But the result is not the one i expected, and according to the first answer of this post CKM_RSA_PKCS vs CKM_RSA_X_509 mechanisms in PKCS#11,
CKM_RSA_PKCS on the other hand also performs the padding as defined in the PKCS#1 standards. This padding is defined within EMSA-PKCS1-v1_5, steps 3, 4 and 5. This means that this mechanism should only accept messages that are 11 bytes shorter than the size of the modulus. To create a valid RSASSA-PKCS1-v1_5 signature, you need to perform steps 1 and 2 of EMSA-PKCS1-v1_5 yourself.
After some research it appears that my file contains the first step of the signature described by the RFC 3447, so the missing part is the second one, where the ASN.1 value is generated.
Can I force this operation with pkcs11 and how ?
The PKCS#11 documentation doesn't seem to contain any information about it.
I see two ways to do this; the appropriate one depends on the token (not all tokens/wrappers do all machanisms).
As explained in this other answer, you could decorate the 32-octet SHA-256 that you start from into a full padded message representative. Basically, as explained in PKCS#1, if the RSA key is k octets (with I assume k≥51+11=62 octets, that is a public modulus at least 8⋅62-7=489 bits, which is a must for security), you
Append on the left the 19-octet string
30 31 30 0d 06 09 60 86 48 01 65 03 04 02 01 05 00 04 20
yielding a 51-octet string, which really is the ASN.1 DER encoding for the hash type and value per
DigestInfo ::= SEQUENCE {
digestAlgorithm DigestAlgorithm,
digest OCTET STRING
}
Further append on the left the string of k-51 octets (of which k-51-3 are FF)
00 01 FF FF FF FF..FF FF FF FF 00
yielding a k-octet string
Sign with mechanism CKM_RSA_X_509 (length k octets).
Or, alternatively: perform as in [1.]; skip [2.]; and in [3.] use mechanism CKM_RSA_PKCS (length 51 octets).
Disclaimer: I did not check, and have not used a PKCS#11 device lately.
Note: While there is no known attack against proper implementations of it, use of PKCS#1 v1.5 signature padding is increasingly frowned at; e.g. French authorities recommend
RecomSignAsym-1. Il est recommandé d’employer des mécanismes de signature asymétrique disposant d’une preuve de sécurité.
Or, in English:
It is recommended to use asymmetric signature mechanisms featuring a security proof
They mention RSA-SSA-PSS (sic). As a bonus, the PKCS#11 implementation of that is mechanism CKM_RSA_PKCS_PSS which accepts a hash, rather than the data to sign, making what's asked trivial.
I'm afraid, there is no PKCS#11 function, which can do what you want.
The only solution that I am aware of would be, to apply the PKCS#1 v1.5 padding manually to your hash and then sign the block using the CKM_RSA_X_509 (raw or textbook RSA) mechanism.
Rather than issuing the command,
openssl pkeyutl -sign -pkeyopt digest:sha256 -in <inFilePath> -inkey <keyPath> -out <outFilePath>
try
openssl dgst --sha256 -sign <keyPath> -sha256 -out <signature file> <inFilePath>
This produces 256 bytes signature that would probably be identical to
one generated by Pkcs11 C_Sign

SignatureValue calculation for XML-DSIG

I am trying to write a method that returns a signature of an XML element for XMLDSIG using NET framework components (RSACryptoServiceProvider) in C++/CLI. Could please someone explain this excerpt from XMLDSIG specs ( http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/ ) in simpler words, for I am have very little programming and maths background and therefore have trouble undrestanding this - Or provide an excerpt form a real code as an example where this is implemented?
The SignatureValue content for an RSA signature is the base64 [MIME]
encoding of the octet string computed as per RFC 2437 [PKCS1, section
8.1.1: Signature generation for the RSASSA-PKCS1-v1_5 signature scheme]. As specified in the EMSA-PKCS1-V1_5-ENCODE function RFC 2437
[PKCS1, section 9.2.1], the value input to the signature function MUST
contain a pre-pended algorithm object identifier for the hash
function, but the availability of an ASN.1 parser and recognition of
OIDs is not required of a signature verifier. The PKCS#1 v1.5
representation appears as: CRYPT (PAD (ASN.1 (OID, DIGEST (data))))
Note that the padded ASN.1 will be of the following form: 01 | FF*
| 00 | prefix | hash where "|" is concatenation, "01", "FF", and "00"
are fixed octets of the corresponding hexadecimal value, "hash" is the
SHA1 digest of the data, and "prefix" is the ASN.1 BER SHA1 algorithm
designator prefix required in PKCS1 [RFC 2437], that is, hex 30 21
30 09 06 05 2B 0E 03 02 1A 05 00 04 14 This prefix is included to make
it easier to use standard cryptographic libraries. The FF octet MUST
be repeated the maximum number of times such that the value of the
quantity being CRYPTed is one octet shorter than the RSA modulus.
In other words, if I am have the hash value for a certain XML element (not encoded in base64, is that right?), what do I do with it before sending it to the SignHash (in RSACryptoServiceProvider) function?
I know it's in the text, but I have troubles understanding it.
I don't understand "CRYPT (PAD (ASN.1 (OID, DIGEST (data))))" at all, although I understand parts of it... I don't understand the way to get the OID and then ASN and how to pad it...
Let me try to explain the components, and see if this gets you any closer:
DIGEST(data) is the hash-value you already computed
OID is a globally unique identifier representing the hash-algorithm used. For SHA1 this is 1.3.14.3.2.26
ANS.1 means ANS.1-encoding of the OID and the hash-value as an ASN.1-sequence. This means the hex-values listed in the reference, followed by the actual hash.
PAD means concatenating 01 FF* 01 with the ASN.1-encoded prefix and the hash to get the desired length (FF* means repeat FF an appropriate number of times, the RFC gives details)
CRYPT is the RSA-encryption-function
However, I believe the signHash-function does all of this for you, you just provide the OID and the hash-value.