Giter VIP home page Giter VIP logo

cbaker6 / certificatesigningrequest Goto Github PK

View Code? Open in Web Editor NEW
96.0 5.0 39.0 1.43 MB

Generate a certificate signing request (CSR) programmatically on iOS/macOS/watchOS/tvOS devices

Home Page: https://swiftpackageindex.com/cbaker6/CertificateSigningRequest/main/documentation/certificatesigningrequest

License: GNU General Public License v2.0

Swift 97.56% Ruby 2.44%
csr privatekey certificate-signing-request publickey swift elliptic-curve-diffie-hellman secure-enclave rsa ios keychain

certificatesigningrequest's Introduction

CertificateSigningRequest

Documentation CI Status Codecov Pod License

Generate a certificate signing request (CSR) in iOS/macOS using Swift.

iOS

Supports RSA (key size: 512, 1024, 2048) and EC inside/outside of secure enclave (iOS only supports 256 bit keys for now), SHA1, SHA256, and SHA512.

macOS

Supports RSA (key size: 1024, 2048) and EC inside/outside of secure enclave, SHA1, SHA256, and SHA512.

Usage

To use, follow the following steps:

  1. Generate your publicKey/privateKey pair. This can be done using Keychain in iOS. An example can be found in the generateKeysAndStoreInKeychain function in the testfile.
  2. Get your publicKey in bits by querying it from the iOS keychain using String(kSecReturnData): true in your query. For example:
//Set block size
let keyBlockSize = SecKeyGetBlockSize(publicKey)
//Ask keychain to provide the publicKey in bits
let query: [String: Any] = [
    String(kSecClass): kSecClassKey,
    String(kSecAttrKeyType): algorithm.secKeyAttrType,
    String(kSecAttrApplicationTag): tagPublic.data(using: .utf8)!,
    String(kSecReturnData): true
]

var tempPublicKeyBits:CFTypeRef?
var _ = SecItemCopyMatching(query as CFDictionary, &tempPublicKeyBits)

guard let keyBits = tempPublicKeyBits as? Data else {
    return (nil,nil)
}
  1. Initialize the CertificateSigningRequest using KeyAlgorithm.ec or KeyAlgorithm.rsa (an example of how to do can be found in the test file. Below are 3 possible ways to initialize:
let csr = CertificateSigningRequest() //CSR with no fields, will use defaults of an RSA key with sha512
let algorithm = KeyAlgorithm.ec(signatureType: .sha256)
let csr = CertificateSigningRequest(keyAlgorithm: algorithm) //CSR with a specific key 
let csr = CertificateSigningRequest(commonName: String?, organizationName: String?, organizationUnitName: String?, countryName: String?, stateOrProvinceName: String?, localityName: String?, emailAddress: String?, description: String?, keyAlgorithm: algorithm) //Define any field you want in your CSR along with the key algorithm
  1. Then simply build your CSR using your publicKey(bits) and privateKey using:
let builtCSR = csr.buildCSRAndReturnString(publicKeyBits, privateKey: privateKey)
//Or if you want `CertificateSigningRequest` to verify the signature after building, pass in your publicKey to the same method:
let builtCSR = csr.buildCSRAndReturnString(publicKeyBits, privateKey: privateKey, publicKey: publicKey)
  • Two other methods are available depending on your needs.
  • To get CSR without header and footer info use: let builtCSR = csr.buildAndEncodeDataAsString(publicKeyBits, privateKey: privateKey).
  • To get CSR as Data use: let builtCSR = csr.build(publicKeyBits, privateKey: privateKey).

Note:

You can test if your CSRs are correct by running and setting a break point the test file. You can also let all test run and test the different CSR's. The output of the CSR will print in the console window. You can output the CSR's and your own app by printing to the console and check if they are created correctly by pasting them here: https://redkestrel.co.uk/products/decoder/ or by using openssl.

Example

To run the example project, clone the repo, and run pod install from the Example directory first. An example certificate from this framework is below:

-----BEGIN CERTIFICATE REQUEST-----
MIIBYTCCAQcCAQAwgaQxCzAJBgNVBAYMAlVTMQswCQYDVQQIDAJLWTENMAsGA1UE
BwwEVGVzdDENMAsGA1UECgwEVGVzdDENMAsGA1UECwwEVGVzdDEnMCUGA1UEAwwe
Q2VydGlmaWNhdGVTaWduaW5nUmVxdWVzdCBUZXN0MSIwIAYJKoZIhvcNAQkBDBNu
ZXRyZWNvbkBjcy51a3kuZWR1MQ4wDAYDVQQNDAVoZWxsbzBZMBMGByqGSM49AgEG
CCqGSM49AwEHA0IABN5Wp7zEAVkffuqmkC22j3mOCJalTo2Beff23N8Bv7sZ0iTM
AdqeeF+A1fAO5yUwykbTYhAyNiwkT82jtOy09xKgADAKBggqhkjOPQQDAgNIADBF
AiEAt85IAQ9kOptiplqYkLyRz4is/uB4DffNpWuP9EUJY74CIHtjMZ6QRwY1zPGI
bXC5eX6Kpv5QLfvR6xX7Xqaoy6Ai
-----END CERTIFICATE REQUEST-----

You can test if the CSR was created correctly here: https://redkestrel.co.uk/products/decoder/

Requirements

  • iOS 10+
  • mac OS 10.13+

Installation

Swift Package Manager (SPM) - Option 1

CertificateSigningRequest can be installed via SPM. Open an existing project or create a new Xcode project and navigate to File > Swift Packages > Add Package Dependency. Enter the url https://github.com/cbaker6/CertificateSigningRequest.git and tap Next. Choose the main branch, and on the next screen, check off the package.

Cocoapods - Option 2

CertificateSigningRequest is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'CertificateSigningRequest'

Embedded Framework - Option 3

If you would like to use as a framework, clone and build the project, look under frameworks, and drag "CertificateSigningRequest.framework" into "Frameworks" section of your project, "check copy if needed".

  • In your project Targets, click on "General", make sure "CertificateSigningRequest.framework" shows up under "Embedded Binaries" and it should automatically appear in "Linked Frameworks and Libraries"
  • Then, simply place import CertificateSigningRequest at the top of any file that needs the framework.

Author

cbaker6, [email protected]

License

Components of CertificateSigningRequest was originally in ios-csr by Ales Teska written in Objective-C and ported by the author of CertificateSigningRequest to Swift. Therefore CertificateSigningRequest has the same GPLv2 license. See the LICENSE file for more info.

certificatesigningrequest's People

Contributors

cbaker6 avatar dependabot[bot] avatar milanpro avatar mortengregersen avatar pheckenlwork avatar stoexn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

certificatesigningrequest's Issues

Domain=NSOSStatusErrorDomain Code=-50 "Key generation failed

Hi I am getting below error when I run in device and simulator,

Error creating keys occured: Error Domain=NSOSStatusErrorDomain Code=-50 "Key generation failed, error -50" UserInfo={NSDescription=Key generation failed, error -50}, keys weren't created

The private key is not generating,

I am using below code,

        if keyAlgorithm.type == KeyAlgorithm.rsa(signatureType: .sha512).type{
                let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault,
                                                             kSecAttrAccessibleAlwaysThisDeviceOnly,
                                                             .privateKeyUsage,
                                                             nil)!   // Ignore error
                
                privateKeyParameters[String(kSecAttrAccessControl)] = access
            }

//Define what type of keys to be generated here
var parameters: [String: AnyObject] = [
String(kSecAttrKeyType): keyAlgorithm.secKeyAttrType,
String(kSecAttrKeySizeInBits): keyAlgorithm.availableKeySizes.last! as AnyObject,
String(kSecReturnRef): kCFBooleanTrue,
kSecPublicKeyAttrs as String: publicKeyParameters as AnyObject,
kSecPrivateKeyAttrs as String: privateKeyParameters as AnyObject,
]

Support for ECDSA public keys

I am wondering if you have any plans to support ECDSA public keys as well. I tried your code and it works for RSA very well, but for ecdsa, it seems we need to have another buildPublicKeyInfo as public keys for ecdsa look different.

FAILED - CSR has an invalid signature. Key Size WARNING (0 bits)

Hi, I am trying to generate private key and public key and save them in MAC's login keychain. Then I want to generate csr by using those private key public keys and ASN.1. I followed exactly what you have described. My csr is generated but it has invalid signature and the keysize showed 0. I have attached my csr informations in below pdf.

csr.pdf
My major files are attached here.
csr.zip

CSR key size = 0 when decoding, MacOS

Hey there.

I have been trying to generate a CSR based on your code, and for the most part it is going swimmingly. However I have noticed that when I decode the out put on Red Kestrel, the CSR is invalid and the key size is 0?

Is this something you have come across on MacOS? As when I run your test suite on on iOS, the CSR generated is fine.

Code=-67808 "RSA signature verification failed, no match"

Hi,

i've used this CertificateSigningRequest to create CSR with rsa 2048 with sha 256.
the CSR was successfully created, but if i using this method to verification signature :

let builtCSR = csr.buildCSRAndReturnString(potentialPublicKeyBits!, privateKey: privateKeys!, publicKey: publicKeys!)

it always return "Code=-67808 "RSA signature verification failed, no match""

is there any idea and how to solve it?

thank you

Email should be IA5STRING instead of UTF8STRING

First, THANK YOU for developing this library. We used it to develop a
VPN solution for our company.

While working with CertificateSigningRequest, I believe I encountered
a bug. In CSRs, emails are supposed to be IA5STRING, but this library
encodes with UTF8STRING.

I would be happy to provide a PR for this issue. I thought an issue
would be more friendly than a "drive by PR". :-)

EC key SHA1 oid size mismatch

let sequenceObjectSHA1WithECEncryption: [UInt8] =
[0x30, 0x0A, 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x01]

The second slot, 0x0A should be 0x09 instead since it occupied 9 slots only

FAILED - CSR has an invalid signature

I have tried to create Secure Enclave keys and CSR. This Error was prompted.

Error Domain=NSOSStatusErrorDomain Code=-67808 "EC signature verification failed, no match" UserInfo={NSDescription=EC signature verification failed, no match}

CSR Generation CODE -
let csrBuild1 = csr.build(pubkeyBits!, privateKey: privateKeySec!, publicKey: publicKeySec!)
let certificateRequestB64 = csrBuild1.base64EncodedString()
let certificateRequestPEM =
"-----BEGIN CERTIFICATE REQUEST-----\n(certificateRequestB64)\n-----END CERTIFICATE REQUEST-----\n"

CSR Enhancement

Need to add following Certificate Attributes to the CSR,

  • Key Usage
  • Extend Key Usage

Is there any function to add above attributes to the CSR
MicrosoftTeams-image

Not really an issue, it's an improvement suggestion

If you pass the options [.lineLength64Characters, .endLineWithLineFeed] to the base64 encoding method you can omit the cumbersome logic in buildCSRAndReturnString to insert the newline characters.

public func buildAndEncodeDataAsString(_ publicKeyBits:Data, privateKey: SecKey)-> String? {
    
    guard let buildData = self.build(publicKeyBits, privateKey: privateKey) else{
        return nil
    }
    
    return buildData.base64EncodedString(options: [.lineLength64Characters, .endLineWithLineFeed]).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
    
}

public func buildCSRAndReturnString(_ publicKeyBits:Data, privateKey: SecKey)-> String? {
    
    guard let csrString = self.buildAndEncodeDataAsString(publicKeyBits, privateKey: privateKey) else{
        return nil
    }
    
    let head = "-----BEGIN CERTIFICATE REQUEST-----\n"
    let foot = "-----END CERTIFICATE REQUEST-----\n"
    return head+csrString+foot
}

Signature FAILED - CSR has an invalid signature problem using this library

Hello Corey,

We're using your iOSCSRSwift library in order to generate a valid CSR file on a Swift 3 Project but once it is generated and we tested against https://redkestrel.co.uk/products/decoder/ it has this
Signature | FAILED - CSR has an invalid signature problem.

The rest of the CSR seems fine.

I am including the code we're using based on your library and also the generated CSR

CSR.zip

When tested from CLI and it gives usan error.

openssl req -text -verify -in netki.csr
verify failure
38978:error:0407006A:rsa routines:RSA_padding_check_PKCS1_type_1:block
type is not
01:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-64.50.6/src/crypto/rsa/rsa_pk1.c:102:
38978:error:04067072:rsa routines:RSA_EAY_PUBLIC_DECRYPT:padding check
failed:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-64.50.6/src/crypto/rsa/rsa_eay.c:719:
38978:error:0D0C5006:asn1 encoding routines:ASN1_item_verify:EVP
lib:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-64.50.6/src/crypto/asn1/a_verify.c:191:

Kind regards

Invalid signature

All my CSRs created with this library have an invalid signature. The CSR example that is given in the https://github.com/cbaker6/CertificateSigningRequestSwift_Test readme(copied below) also has an invalid signature. How can I resolve this problem?

-----BEGIN CERTIFICATE REQUEST----- MIIBFTCBuwIBADBZMQswCQYDVQQGDAJVUzENMAsGA1UECgwEVGVzdDENMAsGA1UE CwwEVGVzdDEsMCoGA1UEAwwjQ2VydGlmaWNhdGVTaWduaW5nUmVxdWVzdFN3aWZ0 IFRlc3QwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATC24iJCr7abrZN0BPaYcM+ cKd/4iXBtHuIM4LzOszsU5pQ9dc9s+srChfWu6m1nCgN48ZHwApTyKV/O0yWWcLA oAAwCgYIKoZIzj0EAwIDSQAwRgIhAPI2FW/izEz8SHAMStctamIzTne+g6AHQWai X0OfkwoBAiEAzXqgv6WVn+VMyxiA25eMc8/Zzrj/mWpew6INRZ1pA1g= -----END CERTIFICATE REQUEST-----

Open SSL config

Hello Corey, i use your library and my friend to couldn't decode csr, cause he has different open ssl config. Can i somehow change default open ssl config to custom file?

GPL 2.0 licensed?

Hi Corey,

Did you port ios-csr via some form of clean room methodology so that the GPL 2.0 doesn't apply to your code? Usually it seems that ports contain the licensing of the thing that was ported.

Adding Certificate Extensions

Hello,

I'm currently having some trouble to add certificate extensions with subject alternative name.
I don't understand the attributes before my extensions. normally I think they need a ASN.1 code, but they don't have one and it is working...

the ASN.1 code for the certificate extension is: 0x06, 0x02, 0x55, 0x1D and for subject alternative name it is: 0x06, 0x03, 0x55, 0x1D, 0x11.

would be amazing if someone can help me.

Thank you!!

CSR Enhancement : CSR To Self Signed Certificate

Hello,

I am trying to Generate Self-Signed Certificate from the generated CSR.

The Field missing in the CSR is

SerialNumber,
Validity,
Issuer

i don't know this Information can helpful or not, But If we need to Generate Self-Signed Certificate i think if we add the above information while creating certificate info then may be it will treat as a Self-Signed Certificate

Let me correct if i am wrong.

and anyone can help me with the code sample how i could add these things in code.

for your reference i tried to add serial number in this way but when i tried to check weather it generate correct or not from https://redkestrel.co.uk/products/decoder/

its unable to decode

MY CODE SAMPLE

in the function : func buldCertificationRequestInfo(_ publicKeyBits: Data) -> Data

i try to add serial number this way

//Add Serial Number
let serialNumberString = "123"
var serialNumber = Data(capacity: 128)
appendSerialNumber(objectSerialNumber, value: serialNumberString, into: &serialNumber)
enclose(&serialNumber, by: sequenceTag)
certificationRequestInfo.append(serialNumber)

here objectSerialNumber is : private let objectSerialNumber: [UInt8] = [0x06, 0x03, 0x55, 0x04, 0x05]

private func appendSerialNumber(_ what: [UInt8], value: String, into: inout Data ) {
var serialNumber = Data(capacity: 128)

    serialNumber.append(what, count: what.count)
    appendUTF8String(string: value, into: &serialNumber)
    enclose(&serialNumber, by: sequenceTag)
    enclose(&serialNumber, by: setTag)
    
    into.append(serialNumber)
}

Thanks

Publishing cocoapods library

Sorry - silly question - clearly there is a problem with modulemap

In the description it says you cannot add pod
Have you tried simple command? :

pod trunk push --allow-warnings

Country field MUST be PRINTABLESTRING

All CSR fields are encoded as UTF8, and if the openssl.conf that is used to create a cert from the CSR
specifies 'match' for country, it will fail because the encoding is different. See this section in RFC5280

-- Naming attributes of type X520countryName (digraph from IS 3166)

id-at-countryName       AttributeType ::= { id-at 6 }

X520countryName ::=     PrintableString (SIZE (2))

How can we set UID attribute in CSR?

I have a requiremnent to set UID attribute (0.9.2342.19200300.100.1.1) in the CSR that I'm building, but the implementation doesn't expose a way to do this.
Can you suggest the easiest way we can do this?

Swift 2.3 version

Hi,

Just wondering if there are any plans to create a swift 2.3 version of this library.

Regards,
Pascal

Convert OID to ECDSA

I'm working CSR with objective c, and same you did for RSA I tried to convert this into EC I used https://www.viathinksoft.com/~daniel-marschall/asn.1/oid-converter/online.php url to convert OID into Hex value convert "1.2.840.10045.4.3.2" into "//x06\x08\x2A\x86\x48\xCE\x3D\x04\x03\x02" but I converted into PEM then there is issue in signature.
Here below result.

-----BEGIN CERTIFICATE REQUEST-----
MIIBRTCB7AIBADBIMREwDwYDVQQGDAhQYWtpc3RhbjERMA8GA1UECgwIQXNjZXJ0
aWExDDAKBgNVBAsMA0FTQzESMBAGA1UEAwwJRCBTaWduaW5nMIGaMAsGCCqGSM49
BAMCAAOBigAwgYYCQQSh/pTk2/oGZ1BtNcFLzLeUTQbQzNybf6FaHho2W7xdRN/b
UTgiRGQWkzF/Scaeq77JLnGbchsJXoIwBjNhrHNmAkEEof6U5Nv6BmdQbTXBS8y3
lE0G0Mzcm3+hWh4aNlu8XUTf21E4IkRkFpMxf0nGnqu+yS5xm3IbCV6CMAYzYaxz
ZqAABggqhkjOPQQDAgADSQAwRgIhAJmUE9HhPogU3M9NkWUaVSSZajLSPBANF3to
oDmfj5+UAiEA4mylQoe5221sB7huNCwtW+J2MhukWYqhh6ItYE40JD0=
-----END CERTIFICATE REQUEST-----

Here below my whole code:
`/*
This file is part of ios-csr.
Copyright (C) 2013-14 Ales Teska

ios-csr is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

ios-csr is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with ios-csr.  If not, see <http://www.gnu.org/licenses/>.

*/

#import "SCCSR.h"
#include <CommonCrypto/CommonDigest.h>

/*

Certification Request Syntax Specification: http://www.ietf.org/rfc/rfc2986.txt

*/

static uint8_t OBJECT_commonName[5] = {0x06, 0x03, 0x55, 0x04, 0x03};
static uint8_t OBJECT_countryName[5] = {0x06, 0x03, 0x55, 0x04, 0x06};
static uint8_t OBJECT_organizationName[5] = {0x06, 0x03, 0x55, 0x04, 0x0A};
static uint8_t OBJECT_organizationalUnitName[5] = {0x06, 0x03, 0x55, 0x04, 0x0B};

//1.2.840.10045.4.3.2
//x06\x08\x2A\x86\x48\xCE\x3D\x04\x03\x02
static uint8_t OBJECT_rsaEncryptionNULL[11] = {0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x00};

//f6:fc:1c:03:17:5f:67:4f:1f:0b:50:5a:9f:f9:30:e5
//static uint8_t OBJECT_rsaEncryptionNULL[13] = {0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00};

//f6:fc:1c:03:17:5f:67:4f:1f:0b:50:5a:9f:f9:30:e5

// See: http://oid-info.com/get/1.2.840.113549.1.1.5

static uint8_t SEQUENCE_OBJECT_sha1WithRSAEncryption[] = {0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02, 0x00};
//static uint8_t SEQUENCE_OBJECT_sha1WithRSAEncryption[] = {0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 1, 1, 5, 0x05, 0x00};

static uint8_t SEQUENCE_tag = 0x30;
static uint8_t SET_tag = 0x31;

///

@implementation SCCSR

@synthesize countryName;
@synthesize organizationName;
@synthesize organizationalUnitName;
@synthesize commonName;
@synthesize subjectDER;

-(SCCSR *)init
{
self = [super init];
if (!self) return self;

countryName = nil;
organizationName = nil;
organizationalUnitName = nil;
commonName = nil;

subjectDER = nil;

return self;

}

-(NSData *) build:(NSData *)publicKeyBits privateKey:(SecKeyRef)privateKey
{
NSMutableData * CertificationRequestInfo = [self buildCertificationRequestInfo:publicKeyBits];

// Build signature - step 1: SHA1 hash
CC_SHA256_CTX SHA1;
CC_SHA256_Init(&SHA1);
CC_SHA256_Update(&SHA1, [CertificationRequestInfo mutableBytes], (unsigned int)[CertificationRequestInfo length]);
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256_Final(digest, &SHA1);

// Build signature - step 2: Sign hash
uint8_t signature[256];
size_t signature_len = sizeof(signature);
OSStatus osrc = SecKeyRawSign(
	privateKey,
	kSecPaddingNone,
	digest, sizeof(digest),
	signature, &signature_len
);
assert(osrc == noErr);

NSMutableData * CertificationRequest = [[NSMutableData alloc] initWithCapacity:1024];
[CertificationRequest appendData:CertificationRequestInfo];
[CertificationRequest appendBytes:SEQUENCE_OBJECT_sha1WithRSAEncryption length:sizeof(SEQUENCE_OBJECT_sha1WithRSAEncryption)];

NSMutableData * signdata = [NSMutableData dataWithCapacity:257];
uint8_t zero = 0;
[signdata appendBytes:&zero length:1]; // Prepend zero
[signdata appendBytes:signature length:signature_len];
[SCCSR appendBITSTRING:signdata into:CertificationRequest];

[SCCSR enclose:CertificationRequest by:SEQUENCE_tag]; // Enclose into SEQUENCE

return CertificationRequest;

}

-(NSMutableData *)buildCertificationRequestInfo:(NSData *)publicKeyBits
{
NSMutableData * CertificationRequestInfo = [[NSMutableData alloc] initWithCapacity:512];

// Add version
uint8_t version[3] = {0x02, 0x01, 0x00}; // ASN.1 Representation of integer with value 1
[CertificationRequestInfo appendBytes:version length:sizeof(version)];


// Add subject
NSMutableData * Subject = [[NSMutableData alloc] initWithCapacity:256];
if (countryName != nil) [SCCSR appendSubjectItem:OBJECT_countryName value:countryName into:Subject];
if (organizationName != nil) [SCCSR appendSubjectItem:OBJECT_organizationName value:organizationName into:Subject];
if (organizationalUnitName != nil) [SCCSR appendSubjectItem:OBJECT_organizationalUnitName value:organizationalUnitName into:Subject];
if (commonName != nil) [SCCSR appendSubjectItem:OBJECT_commonName value:commonName into:Subject];
[SCCSR enclose:Subject by:SEQUENCE_tag]; // Enclose into SEQUENCE

subjectDER = [NSData dataWithData:Subject];

[CertificationRequestInfo appendData:Subject];


//Add public key info
NSData * publicKeyInfo = [SCCSR buildPublicKeyInfo:publicKeyBits];
[CertificationRequestInfo appendData:publicKeyInfo];

// Add attributes
uint8_t attributes[2] = {0xA0, 0x00};
[CertificationRequestInfo appendBytes:attributes length:sizeof(attributes)];


[SCCSR enclose:CertificationRequestInfo by:SEQUENCE_tag]; // Enclose into SEQUENCE

return CertificationRequestInfo;

}

/// Utility class methods ...
+(NSData *)buildPublicKeyInfo:(NSData *)publicKeyBits
{
NSMutableData * publicKeyInfo = [[NSMutableData alloc] initWithCapacity:390];

[publicKeyInfo appendBytes:OBJECT_rsaEncryptionNULL length:sizeof(OBJECT_rsaEncryptionNULL)];
[SCCSR enclose:publicKeyInfo by:SEQUENCE_tag]; // Enclose into SEQUENCE

NSMutableData * publicKeyASN = [[NSMutableData alloc] initWithCapacity:260];

NSData * mod = [SCCSR getPublicKeyMod:publicKeyBits];
char Integer = 0x02; // Integer
[publicKeyASN appendBytes:&Integer length:1];
[SCCSR appendDERLength:[mod length] into:publicKeyASN];
[publicKeyASN appendData:mod];

NSData * exp = [SCCSR getPublicKeyExp:publicKeyBits];
[publicKeyASN appendBytes:&Integer length:1];
[SCCSR appendDERLength:[exp length] into:publicKeyASN];
[publicKeyASN appendData:exp];

[SCCSR enclose:publicKeyASN by:SEQUENCE_tag]; // Enclose into ??
[SCCSR prependByte:0x00 into:publicKeyASN]; // Prepend 0 (?)

[SCCSR appendBITSTRING:publicKeyASN into:publicKeyInfo];

[SCCSR enclose:publicKeyInfo by:SEQUENCE_tag]; // Enclose into SEQUENCE

return publicKeyInfo;

}

+(void)appendSubjectItem:(const uint8_t[5])what value:(NSString *)value into:(NSMutableData *)into
{
NSMutableData * SubjectItem = [[NSMutableData alloc] initWithCapacity:128];
[SubjectItem appendBytes:what length:5];
[SCCSR appendUTF8String:value into:SubjectItem];
[SCCSR enclose:SubjectItem by:SEQUENCE_tag]; // Enclose into SEQUENCE
[SCCSR enclose:SubjectItem by:SET_tag]; // Enclose into SET

[into appendData:SubjectItem];

}

+(void)appendUTF8String:(NSString *)string into:(NSMutableData *)into
{
char strtype = 0x0C; //UTF8STRING
[into appendBytes:&strtype length:1];
[SCCSR appendDERLength:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] into:into];
[into appendData:[string dataUsingEncoding:NSUTF8StringEncoding]];
}

+(void)appendDERLength:(size_t)length into:(NSMutableData *)into
{
assert(length < 0x8000);

if (length < 128)
{
	uint8_t d = length;
	[into appendBytes:&d length:1];
}
else if (length < 0x100)
{
	uint8_t d[2] = {0x81, length & 0xFF};
	[into appendBytes:&d length:2];
}
else if (length < 0x8000)
{
	uint8_t d[3] = {0x82, (length & 0xFF00) >> 8, length & 0xFF};
	[into appendBytes:&d length:3];
}

}

+(void)appendBITSTRING:(NSData *)data into:(NSMutableData *)into
{
char strtype = 0x03; //BIT STRING
[into appendBytes:&strtype length:1];
[SCCSR appendDERLength:[data length] into:into];
[into appendData:data];
}

+(void)enclose:(NSMutableData )data by:(uint8_t)by
{
NSMutableData
newdata = [[NSMutableData alloc]initWithCapacity:[data length]+4];

[newdata appendBytes:&by length:1];
[SCCSR appendDERLength:[data length] into:newdata];
[newdata appendData:data];

[data setData:newdata];

}

+(void)prependByte:(uint8_t)byte into:(NSMutableData )into
{
NSMutableData
newdata = [[NSMutableData alloc]initWithCapacity:[into length]+1];

[newdata appendBytes:&byte length:1];
[newdata appendData:into];

[into setData:newdata];

}

///

// From http://stackoverflow.com/questions/3840005/how-to-find-out-the-modulus-and-exponent-of-rsa-public-key-on-iphone-objective-c

  • (NSData *)getPublicKeyExp:(NSData *)publicKeyBits
    {
    int iterator = 0;

    iterator++; // TYPE - bit stream - mod + exp
    [SCCSR derEncodingGetSizeFrom:publicKeyBits at:&iterator]; // Total size

    iterator++; // TYPE - bit stream mod
    int mod_size = [SCCSR derEncodingGetSizeFrom:publicKeyBits at:&iterator];
    iterator += mod_size;

    iterator++; // TYPE - bit stream exp
    int exp_size = [SCCSR derEncodingGetSizeFrom:publicKeyBits at:&iterator];
    return publicKeyBits;
    return [publicKeyBits subdataWithRange:NSMakeRange(iterator, exp_size)];
    }

+(NSData *)getPublicKeyMod:(NSData *)publicKeyBits
{
int iterator = 0;

iterator++; // TYPE - bit stream - mod + exp
[SCCSR derEncodingGetSizeFrom:publicKeyBits at:&iterator]; // Total size

iterator++; // TYPE - bit stream mod
int mod_size = [SCCSR derEncodingGetSizeFrom:publicKeyBits at:&iterator];
return publicKeyBits;
//TODO: Changed in Code
return [publicKeyBits subdataWithRange:NSMakeRange(iterator, mod_size)];

}

+(int)derEncodingGetSizeFrom:(NSData*)buf at:(int*)iterator
{
const uint8_t* data = [buf bytes];
int itr = *iterator;
int num_bytes = 1;
int ret = 0;

if (data[itr] > 0x80) {
	num_bytes = data[itr] - 0x80;
	itr++;
}

for (int i = 0 ; i < num_bytes; i++) ret = (ret * 0x100) + data[itr + i];

*iterator = itr + num_bytes;
return ret;

}

@EnD

`
Kindly help me on this.

CSR max linelength, parsing on macOS

The base64 body of the CSR is a continuous string, which works fine with some openssl implementations (e.g. linux), but the macOS version barfs because the lines are more than 64 characters. If I manually edit the CSR, adding newlines every 64 characters, macOS openssl can parse the CSR.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.