How to get X509Certificate field in Swift - ios

I’m trying to Sign a XML document in iOS. I already created a digestValue and a SignatureValue using a pfx file, but I cannot generate the X509Certificate field inside KeyInfo field. I know I only need the pfx file to generate this, but how could I do it in iOS?
Thank you.

I got it.
I had to import OpenSSL lib to my project as a pod:
pod 'OpenSSL-Universal', '~> 1.0'
Then I created an Objective-C file to use the C functions of OpenSSL, and use the following functions to get the PEM value:
d2i_PKCS12: read certificate
PKCS12_parse: parse the certificate to X509 object.
PEM_write_bio_X509: parse the X509 data to a BIO object.
BIO_get_mem_ptr: parse the BIO data to a MEM data
Then I allocated a NSString using the mem->data, and there is the Certificate PEM value.
For more details about the functions, I followed this documentation:
https://www.openssl.org/docs/man1.0.2/crypto/

Related

Computing byte range digest

I'm building an app that lets user digitally sign a PDF. I'm using plugPDF SDK. It has no built in support for generating byte range digest so I have to do it myself. PlugPDF generates the PDF content from which I generate signed hash in Terminal:
openssl dgst -hex -sha256 -sign privateKey.pem -out encrypted.out invoice.content
From this hash I generate the PKCS#7 object:
openssl cms -in encrypted.out -sign -signer signer.pem -outform der -out cert.p7b
Then I inject it into the PDF using the plugPDF SDK. When I open it in Adobe Acrobat the PDF is signed but the signature is invalid. It says: “The Document has been altered or corrupted since the Signature was applied.”
I assume the problem is wrong hash value but I have no idea how else to generate it.
Here's an example tutorial: https://plugpdf.com/how-to-sign-pdf-document-with-pki-certificate-on-ios/
The byte range digest for PDFs typically exclude the area of the PDF where the signature will be injected, so that the digest value should be the same before and after adding the signature. If they are not the same, then the assumption is that the file has been in some way modified since being signed.
It doesn't look like openssl's dgst command allows you to specify discontinuous byte ranges.

How to integrate epub file in own ebook reader application using ExpressPlay sdk?

I have to integrate epub files in our existing ebook reader application by using ExpressPlay Sdk.However, I am unable to get solution.
I got some idea by given link : https://www.expressplay.com/ebooks/
but it is still not able to integrate.
Any idea will be appreciated.
Thanks in advance.
We need to setup proper details while encrypting file. And need to use token for the decryption.
So here are the steps to follow :
1. Encryption using bento4 packaging tools :
(You can find tools here : https://www.bento4.com/downloads/ ) :
Extract the package to some dir and open Terminal or CMD to that path
Follow the command
mp4dcfpackager --method CBC --key
CONTENT_KEY:00112233445566778899aabbccddeeff --content-id
CONTENT_ID --content-type CONTENT_TYPE
INPUT_FILE_PATH OUTPUT_FILE_NAME
Where,
CONTENT_KEY : content_key from https://admin.expressplay.com/bblicensetoken/
CONTENT_ID : content_id from https://admin.expressplay.com/bblicensetoken/
CONTENT_TYPE : for PDF use, application/pdf || for ePUB use application/epub
INPUT_FILE_PATH : File to be converted with DRM content
OUTPUT_FILE_PATH : File name after encryption (make file name same as input file name with extension so you can differentiate file type at app side)
2. Create a Marlin BB License Token (BB Token is used for offline validation):
Add following parameters from https://admin.expressplay.com/bblicensetoken/ :
Content ID
Content Key
Rights Type : "Buy to Own"
Output Control Override Id : "urn:marlin:organization:intertrust:wudo"
Output Control Override Parameter : "ImageContraintLevel"
Output Control Override Value : "0"
Wudo Extension = true
Click on Get Token
Store file to your project
Now, you can get an idea from the samples they provided in SDK that how to use this token file with project.
If you still have any confusion let me know. I've followed the same steps for android so it should work for iOS too.
Thanks.

Rails can't read certificate information from environment due to nested asn1 error

I've got some certificate files, namely a .key file which says:
-----BEGIN RSA PRIVATE KEY-----
IEpAIBAAKCAQEAwAwxt4edIh3UuK8r5
....blablabla..................
QSNoquaasdsaKDybrezemVqCxsQjg==
-----END RSA PRIVATE KEY-----
So it's a RSA Private Key.
I used to load them from files like so:
#private_key = OpenSSL::PKey::RSA.new(File.read(private_key_file))
But since I am using Heroku, I intend to have my certificates saved as their values in environment variables.
So I've pasted them in my .env file
COMPANY_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKC.....\n-----END RSA PRIVATE KEY-----"
Yeah, I switched the \n for explicits \\n based on Multi-line config variables in Heroku. So now my code looks like this:
#private_key = OpenSSL::PKey::RSA.new(ENV['COMPANY_KEY'])
And if I run it from the console I get the object built. But if I try to run it from the web server (Puma 3.4.0 over Rails 4.2.6, Ruby 2.2.3) it fails miserably saying: Neither PUB key nor PRIV key:: nested asn1 error when trying to run that same line.
If I use the debug console I get that the read file looks like
"Line 1\\nLine3\\nLinea3" and so on...
I'm pretty sure that it has something to do with the file format, but I'm all out of ideas and maybe you could help if you had a problem like mine.
I finally found a way to do it... mixing it all up!
So the file, for example company.key looks like
-----BEGIN PRIVATE RSA KEY ----
Mumbojumbomummbojumbo
-----END RSA PRIVATE KEY----
So I switched it to a one liner, making explicit \n in the string (so its a real \n)
COMPANY_KEY=""-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA+ztKEj\n-----END RSA PRIVATE KEY-----\n"
Don't forget the last \n in the file.
Now, the last part, in the place where I used to do
#private_key = OpenSSL::PKey::RSA.new(File.read(private_key_file))
Now I do
#private_key = OpenSSL::PKey::RSA.new(ENV['COMPANY_KEY'].gsub("\\n", "\n"))
And now works like a charm! No public certificates, every piece of info in environment variables.
Save yourself some trouble and store only the certificate or key body in the environment variable. No need to put in newline characters.
SECRET = <<-SECRET
-----BEGIN PRIVATE KEY-----
#{ENV['SECRET_KEY']}
-----END PRIVATE KEY-----
SECRET
CERTIFICATE = <<-CERT
-----BEGIN CERTIFICATE-----
#{ENV['CERT']}
-----END CERTIFICATE-----
CERT
I switched the \n for explicits \\n based on Multi-line config variables in Heroku.
...
If I use the debug console I get that the read file looks like "Line 1\\nLine3\\nLinea3" ...
You problem should be here. The post you are linking is not suggesting to double escape your new lines, it is suggesting to wrap your multi-line text into "double quotes". In bash, it would allow to enter multi-line text at the terminal. The post also suggests to do it an in much easier way:
heroku config:add MASISA_KEY ="$(cat your_private_key.pem)"

Proper way to insert a .pem cert into OpenSSL / a rails model?

I have a .pem cert that I'm reasonably sure I generated correctly, and it is not being accepted by OpenSSL when I paste it into a Rails 3.0.2 model. What I do is this:
open up the .pem file in Textmate
select all and copy
user.cert = <paste into model>; user.save
OpenSSL::PKey::RSA.new(user.cert)
This gives me the error:
Neither PUB key nor PRIV key::
To test, I just loaded in the file instead, no errors:
OpenSSL::PKey::RSA.new(File.read("/path/to/cert.pem"))
I thought maybe it would be some encoding error or newline issue, I had tried gsub'ing out the newlines to no avail.
It was a weird copy and paste artifact indeed. I File.read'd it into the model instead of copy paste and it worked fine...
Perhaps late, but this is the answer:
You can put a public key inline in Ruby with copy/paste, but keep in mind that what looks like formatting to you is white space in the line - you need to make sure that the resulting pem string has no spaces. I just copied and pasted from a PEM file into Ruby code, and it did not work until I removed the extra spaces that text mate or whatever added to the lines.
Hard to show here:
SQS_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs3VeTxEgLQLL11UN2G6c
oQsc0LbpoEs4VTmu0S4XU82N4h/25XX5k4t5oTJ0JGGSBP4/gzTwz15vS5mrlnsG
MISSINGLINES
rMV5ZCXToG0VCNPEHpZQnUHMCg/nF9jnk9i1ZZHv2dpYYG7GHMUPG3rtcTWJvZxI
3wIDAQAB
-----END PUBLIC KEY-----".force_encoding("us-ascii")
SQS_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs3VeTxEgLQLL11UN2G6c
oQsc0LbpoEs4VTmu0S4XU82N4h/25XX5k4t5oTJ0JGGSBP4/gzTwz15vS5mrlnsG
MISSINGLINES
rMV5ZCXToG0VCNPEHpZQnUHMCg/nF9jnk9i1ZZHv2dpYYG7GHMUPG3rtcTWJvZxI
3wIDAQAB
-----END PUBLIC KEY-----".force_encoding("us-ascii")
ie - NOT the second one - ruby adds spaces to the start of each line, and the RSA tools do not ignore spaces - they only seem to ignore line feeds.
I use the copy/pasted key as a fallback - in other words if an ENV is set I use that, otherwise use the pasted in public key.
--Tom

C# Export cert in pfx format

NET to export a certificate from the cert store into a PFX file. I'm trying to use the X509certificate2.Export method with the X509ContentType.Pfx flag set, but am unsure how to handle the returned byte array and output it correctly to file.
Any help appreciated.
Judging by the date, you may have already figured this out, but all you have to do is write the returned byte array directly to a file:
byte[] certData = cert.Export(X509ContentType.Pfx, "MyPassword");
File.WriteAllBytes(#"C:\MyCert.pfx", certData);

Resources