preface

Then 05- Cryptography (1) RSA algorithm, finally we introduced the signature and authentication, that is, private key encryption, public key decryption, corresponding to the actual application scenario, is we know the iOS system certificate application process. This article will be combined with RSA algorithm analysis of the certificate application process, as well as RSA code demonstration.

A, certificate

In the previous part 05- Cryptography (1), we introduced the Mac system built-in OpenSSL(open source encryption library) can help us generate public and private keys to complete encryption and decryption, but in the actual development, there is no way to directly use the. Pem file for encryption and decryption, but Xcode to help us to access the application certificate. We use this certificate to interact with Apple’s server for validation and so on.

1.1 Certificate Generation

Before the certificate is generated, we need to generate a request file 👉 CertificateSigningRequest. CertSigningRequest) (hereinafter referred to as the CSR file, there are two ways 👇

  1. Key string generationCSR file
  2. Command line generationCSR file
Key string generation

Path 👉 Keystring -> Keystring Access -> Certificate Assistant -> Request a certificate from a certificate Authority, as shown in 👇

Next fill in the basic information and create 👇

At this point, a request CSR file is generated.

Command line generation

Now look at how the command line works.

  • Generate a CSR file using a private key

openssl req -new -key private.pem -out rsacer.csr

Using the key.pem file generated in the previous article, generate the CSR request file 👇

Here you generate the request file with the private key you created. Send the request file to the signing agency for signature (⚠️ for a fee).

Generate your own signing certificates through CSR

Of course, we can also directly sign the CRT certificate without signing the certificate through the signature agency.

⚠️ Note: The CRT certificate is signed by the private key itself (there is no authentication here).

The command line 👇

openssl x509 -req -days 3650 -in rsacer.csr -signkey private.pem -out rsacert.crt

This CRT certificate is similar to the certificate on the company server, which is given to others to receive. However, the CRT certificate is still not available at this time, and needs to be converted to der👇

openssl x509 -outform der -in rsacert.crt -out rsacert.der

Because the certificate you apply for from Apple is the DER certificate.

p12

There is also a familiar, p12 format file, how to generate?

  1. Export from keystring 👇

  1. Command line operation

Obtain the P12 file from the CRT 👇

openssl pkcs12 -export -out p.p12 -inkey private.pem -in rsacert.crt

⚠️ Note: P12 (private key) and DER (certificate) are a pair. IOS development is to use these two encryption and decryption, is not the same as RSA public and private key principle…

Second, RSA code demonstration

Next, we continue the previous RSA algorithm, with code to demonstrate the process of encryption and decryption.

2.1 Base64 codec

Before we get started, what is Base64? Code encryption and decryption process often use Base64, why Base64 codec? Since the encrypted and decrypted data is in binary format, it is generally converted to Base64 for easy viewing.

  • Base64 encoding
base64 message.txt -o test.txt
Copy the code

Before encoding, message.txt contents 👇

After encoding, the contents of test.txt are 👇

It’s coded into 5a

The base64 encoding consists of 0 to 9 a-z A-Z / = 64 characters.

  • Base64 decoding
base64 test.txt -o message2.txt -D
Copy the code

Here is no longer the example demonstration, and coding is the same truth, the reader can type again to see.

Base64 encoding rules

For example, the encoding of Man is 👇

👇 can be seen in the figure above

Base64 is encoded in six binary numbers

Tables are available at 👇

This table is equivalent to the password book. Because a result is encoded in six binary bits, if the number of bytes to be encoded is not divisible by 3, you end up with an extra byte or two (plus zeros). For example 👇

The zero that I added becomes theta

In the restoration of the time through the lookup table can find the index, index can correspond to binary data, you can restore the data.

In the iOS Base64

The iOS system itself supports base64 codec 👇

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"base64 encode:%@",[self base64Encode:@"LGPerson"]);
    NSLog(@"base64 decode:%@",[self base64Decode:@"TEdQZXJzb24="]);
}

- (NSString *)base64Encode:(NSString *)message {
    NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding];
    return [messageData base64EncodedStringWithOptions:0];
}

- (NSString *)base64Decode:(NSString *)base64Message {
    NSData *base64Data = [[NSData alloc] initWithBase64EncodedString:base64Message options:0];
    return [[NSString alloc] initWithData:base64Data encoding:NSUTF8StringEncoding];
}
Copy the code

Run 👇

Base64 encodes binary files in the form of look-up tables, and applies only to binary files. It’s going to be bigger, it’s going to be 1/3 bigger.

Base64 Reference documents

2.2 RSA code

IOS supports RSA and provides SecKeyEncrypt encryption and SecKeyDecrypt. The specific definition is in the Security system library.

  • Loading public and private keys
//1. Load the public key [[RSACryptor sharedRSACryptor] loadPublicKey:[[NSBundle mainBundle] pathForResource:@"rsacert.der" ofType:nil]]; LoadPrivateKey [[RSACryptor sharedRSACryptor] loadPrivateKey: [[NSBundle mainBundle] pathForResource:@"p.p12" ofType:nil] password:@"123456"];Copy the code
  • Encryption & decryption
/ / encryption NSData * result = [[RSACryptor sharedRSACryptor] encryptData: [@ "hello" dataUsingEncoding: NSUTF8StringEncoding]]. / / base64 encoding nsstrings * base64 = [result base64EncodedStringWithOptions: 0]; NSLog(@" after encryption :%@\n",base64); // decrypt NSData * dcStr = [[RSACryptor sharedRSACryptor] decryptData:result]; NSLog (@ "after decryption: % @", [[nsstrings alloc] initWithData: dcStr encoding: NSUTF8StringEncoding]);Copy the code

Run 👇 again

You can find that the base64 result after each encryption is different, and the decryption is the same. This is due to the padding mode implemented inside RSA.

In SecPadding, the second argument to SecKeyEncrypt, 👇

/ *! @typedef SecPadding @abstract Supported padding types. */ typedef CF_OPTIONS(uint32_t, SecPadding) { kSecPaddingNone = 0, kSecPaddingPKCS1 = 1, kSecPaddingOAEP = 2, // __OSX_UNAVAILABLE __IOS_AVAILABLE(2.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0), /* For SecKeyRawSign/SecKeyRawVerify only, ECDSA signature is raw byte format {r,s}, big endian. First half is r, second half is s */ kSecPaddingSigRaw = 0x4000, /* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is an MD2 hash; standard ASN.1 padding will be done, As well as PKCS1 padding of the underlying RSA operation. */ kSecPaddingPKCS1MD2 = 0x8000, 10.12, "MD2 is deprecated") __IOS_DEPRECATED(2.0, 5.0, "MD2 is deprecated") __TVOS_UNAVAILABLE __WATCHOS_UNAVAILABLE, /* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is an MD5 hash; standard ASN.1 padding will be done, */ kSecPaddingPKCS1MD5 = 0x8001, // __OSX_DEPRECATED(10.0, 10.12, "MD5 is deprecated") __IOS_DEPRECATED(2.0, 5.0, "MD5 is deprecated") __TVOS_UNAVAILABLE __WATCHOS_UNAVAILABLE, /* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is a SHA1 hash; standard ASN.1 padding will be done, as well as PKCS1 padding of the underlying RSA operation. */ kSecPaddingPKCS1SHA1 = 0x8002, /* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is a SHA224 hash; standard ASN.1 padding will be done, as well as PKCS1 padding of the underlying RSA operation. */ kSecPaddingPKCS1SHA224 = 0x8003, / / __OSX_UNAVAILABLE __IOS_AVAILABLE (2.0), / * For SecKeyRawSign/SecKeyRawVerify only, data to be signed is a SHA256 hash; standard ASN.1 padding will be done, as well as PKCS1 padding of the underlying RSA operation. */ kSecPaddingPKCS1SHA256 = 0x8004, / / __OSX_UNAVAILABLE __IOS_AVAILABLE (2.0), / * For SecKeyRawSign/SecKeyRawVerify only, data to be signed is a SHA384 hash; standard ASN.1 padding will be done, as well as PKCS1 padding of the underlying RSA operation. */ kSecPaddingPKCS1SHA384 = 0x8005, / / __OSX_UNAVAILABLE __IOS_AVAILABLE (2.0), / * For SecKeyRawSign/SecKeyRawVerify only, data to be signed is a SHA512 hash; standard ASN.1 padding will be done, as well as PKCS1 padding of the underlying RSA operation. */ kSecPaddingPKCS1SHA512 = 0x8006, / / __OSX_UNAVAILABLE __IOS_AVAILABLE (2.0),};Copy the code

SecPadding is kSecPaddingNone and the ciphertext is the same every time.

Encryption Demo

XFCryptor

conclusion

  • certificate

    • csrRequest file, 2 ways to apply
      1. Keychain -> Keychain Access -> Certificate Assistant -> Request a certificate from a certificate Authority
      2. Terminal command lineopenssl req -new -key private.pem -out rsacer.csr
    • crtCertificate generated
      1. willcsrRequest file sent toSignature institutionsforThe signature(⚠ ️ needscharge)
      2. Self-signature generationCertificate (CRT)(here,No certification)
        • 2.1 openssl x509 -req -days 3650 -in rsacer.csr -signkey private.pem -out rsacert.crt
        • 2.2 fromcrtTo obtainP12 file👉 openssl pkcs12 -export -out p.p12 -inkey private.pem -in rsacert.crt
    • p12
      • fromKey stringexport
      • Run 👉 openssl pkcs12 -export -out p.p12 -inkey private.pem -in rsacert.crt
    • P12 (Private key)andDer (Certificate)isA pair of. IOS development uses both of theseEncryption and decryption.
  • RSA code Demo

    • Base64
      • by0-9 a-z A-Z / = The value contains 64 characters
      • In accordance with theSix binariesCode, multi-digitFill 0
      • In the iOS Base64
  1. Coding 👉NSDataThe method of 👇

- (nsstrings *) base64EncodedStringWithOptions: (NSDataBase64EncodingOptions) options API_AVAILABLE (macos (10.9), the ios (7.0), Tvos watchos (2.0), (9.0));

  1. Decoding 👉NSStringThe method of 👇

- (nullable instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;

  • RSA code
    • IOS supports RSA and provides SecKeyEncrypt and SecKeyDecrypt encryption and decryption functions

    • RSA is very secure (because the entire business logic is secure)

    • Low encryption efficiency (cannot be used for big data encryption)

    • Used to encrypt critical data