### Clone and Setup GMObjC Demo Source: https://github.com/muzipiao/gmobjc/blob/master/README.md Commands to clone the repository and prepare the workspace for development. ```ruby git clone https://github.com/muzipiao/GMObjC.git cd GMObjC pod install open GMObjC.xcworkspace ``` -------------------------------- ### Generate PEM/DER Key Pair Files Directly Source: https://context7.com/muzipiao/gmobjc/llms.txt Convenience methods to directly generate SM2 key pairs and save them as PEM or DER files. The methods return paths to the generated files. Ensure the output directory is writable. ```objc // Generate PEM/DER key pair files directly GMSm2KeyFiles *pemFiles = [GMSm2Bio generatePemKeyFiles]; NSLog(@"Public PEM: %@", pemFiles.publicKeyPath); NSLog(@"Private PEM: %@", pemFiles.privateKeyPath); GMSm2KeyFiles *derFiles = [GMSm2Bio generateDerKeyFiles]; NSLog(@"Public DER: %@", derFiles.publicKeyPath); NSLog(@"Private DER: %@", derFiles.privateKeyPath); ``` -------------------------------- ### Read SM2 Keys from PEM/DER Files Source: https://context7.com/muzipiao/gmobjc/llms.txt Demonstrates reading SM2 public and private keys from PEM and DER encoded files. Supports password-protected PEM files. Ensure keys are correctly formatted before reading. ```objc #import // Read public key from PEM file NSData *pubPemData = [NSData dataWithContentsOfFile:@"/path/to/public.pem"]; NSString *publicKeyHex = [GMSm2Bio readPublicKeyFromPemData:pubPemData password:nil]; // Read private key from PEM file (with optional password) NSData *priPemData = [NSData dataWithContentsOfFile:@"/path/to/private.pem"]; NSString *privateKeyHex = [GMSm2Bio readPrivateKeyFromPemData:priPemData password:nil]; // Read from password-protected PEM NSData *protectedPem = [NSData dataWithContentsOfFile:@"/path/to/encrypted.pem"]; NSData *passwordData = [@"password123" dataUsingEncoding:NSUTF8StringEncoding]; NSString *decryptedKey = [GMSm2Bio readPrivateKeyFromPemData:protectedPem password:passwordData]; // Read keys from DER format files NSData *pubDerData = [NSData dataWithContentsOfFile:@"/path/to/public.der"]; NSData *priDerData = [NSData dataWithContentsOfFile:@"/path/to/private.der"]; NSString *pubFromDer = [GMSm2Bio readPublicKeyFromDerData:pubDerData]; NSString *priFromDer = [GMSm2Bio readPrivateKeyFromDerData:priDerData]; ``` -------------------------------- ### Implement SM2/SM4 Encryption Workflow in Objective-C Source: https://context7.com/muzipiao/gmobjc/llms.txt Demonstrates a full cycle of key exchange, shared secret derivation, message encryption, and signature verification. Requires the GMObjC library and assumes secure handling of private keys. ```objc #import // === SETUP: Both parties generate key pairs === GMSm2Key *clientKeys = [GMSm2Utils generateKey]; GMSm2Key *serverKeys = [GMSm2Utils generateKey]; // === KEY EXCHANGE: Exchange public keys (can be done over insecure channel) === NSString *clientPublicKey = clientKeys.publicKey; NSString *serverPublicKey = serverKeys.publicKey; // === ECDH: Derive shared secret === NSString *clientSecret = [GMSm2Utils computeECDH:serverPublicKey privateKey:clientKeys.privateKey]; NSString *serverSecret = [GMSm2Utils computeECDH:clientPublicKey privateKey:serverKeys.privateKey]; // Both secrets are identical // === DERIVE SM4 KEY: Use first 32 hex chars of shared secret === NSString *sm4Key = [clientSecret substringToIndex:32]; NSString *sm4IV = [serverSecret substringWithRange:NSMakeRange(32, 32)]; // === CLIENT: Encrypt message === NSString *originalMessage = @"Confidential business data"; NSString *encryptedMessage = [GMSm4Utils encryptTextWithCBC:originalMessage keyHex:sm4Key ivecHex:sm4IV]; // === CLIENT: Sign the ciphertext for authenticity === NSString *signature = [GMSm2Utils signText:encryptedMessage privateKey:clientKeys.privateKey userText:nil]; // === TRANSMIT: Send (encryptedMessage, signature) to server === // === SERVER: Verify signature === BOOL isAuthentic = [GMSm2Utils verifyText:encryptedMessage signRS:signature publicKey:clientPublicKey userText:nil]; if (isAuthentic) { // === SERVER: Decrypt message === NSString *decryptedMessage = [GMSm4Utils decryptTextWithCBC:encryptedMessage keyHex:sm4Key ivecHex:sm4IV]; NSLog(@"Received: %@", decryptedMessage); // Output: "Confidential business data" // === SERVER: Send encrypted response === NSString *response = @"Message received and processed"; NSString *encryptedResponse = [GMSm4Utils encryptTextWithCBC:response keyHex:sm4Key ivecHex:sm4IV]; NSString *responseSignature = [GMSm2Utils signText:encryptedResponse privateKey:serverKeys.privateKey userText:nil]; // === CLIENT: Verify and decrypt response === BOOL responseValid = [GMSm2Utils verifyText:encryptedResponse signRS:responseSignature publicKey:serverPublicKey userText:nil]; if (responseValid) { NSString *serverResponse = [GMSm4Utils decryptTextWithCBC:encryptedResponse keyHex:sm4Key ivecHex:sm4IV]; NSLog(@"Server says: %@", serverResponse); } } ``` -------------------------------- ### Save SM2 Keys to PEM/DER Files Source: https://context7.com/muzipiao/gmobjc/llms.txt Shows how to save SM2 public and private keys to PEM and DER format files. Keys are generated using `GMSm2Utils` and then saved using `GMSm2Bio` methods. Ensure the file paths are valid and writable. ```objc // Save keys to PEM files GMSm2Key *keyPair = [GMSm2Utils generateKey]; BOOL pubSaved = [GMSm2Bio savePublicKey:keyPair.publicKey toPemFileAtPath:@"/tmp/my-pub.pem"]; BOOL priSaved = [GMSm2Bio savePrivateKey:keyPair.privateKey toPemFileAtPath:@"/tmp/my-pri.pem"]; // Save keys to DER files [GMSm2Bio savePublicKey:keyPair.publicKey toDerFileAtPath:@"/tmp/my-pub.der"]; [GMSm2Bio savePrivateKey:keyPair.privateKey toDerFileAtPath:@"/tmp/my-pri.der"]; ``` -------------------------------- ### Convert Between PEM and DER Key Formats Source: https://context7.com/muzipiao/gmobjc/llms.txt Utility for converting SM2 keys between PEM and DER formats. This is useful for interoperability when different systems expect different key encodings. Specify whether the key is a public key. ```objc // Convert between PEM and DER formats NSData *pemData = [NSData dataWithContentsOfFile:@"/path/to/key.pem"]; NSData *derData = [GMSm2Bio convertPemToDer:pemData isPublicKey:YES]; NSData *backToPem = [GMSm2Bio convertDerToPem:derData isPublicKey:YES]; ``` -------------------------------- ### String and Data Encoding/Decoding with GMSmUtils Source: https://context7.com/muzipiao/gmobjc/llms.txt Utilize GMSmUtils for converting strings to HEX, HEX to strings, NSData to HEX, HEX to NSData, and for Base64 encoding and decoding. Also includes validation for HEX and Base64 string formats, and padding HEX strings. ```objc #import // String to HEX encoding NSString *text = @"Hello"; NSString *hexString = [GMSmUtils hexStringFromString:text]; // Result: "48656C6C6F" ``` ```objc // HEX to String decoding NSString *decoded = [GMSmUtils stringFromHexString:hexString]; // Result: "Hello" ``` ```objc // NSData to HEX encoding NSData *data = [வைக்Binary" dataUsingEncoding:NSUTF8StringEncoding]; NSString *dataHex = [GMSmUtils hexStringFromData:data]; // Result: "42696E617279" ``` ```objc // HEX to NSData decoding NSData *decodedData = [GMSmUtils dataFromHexString:dataHex]; ``` ```objc // Base64 encoding NSData *originalData = [வைக்Encode me" dataUsingEncoding:NSUTF8StringEncoding]; NSString *base64String = [GMSmUtils base64EncodedStringWithData:originalData]; ``` ```objc // Base64 decoding NSData *base64Decoded = [GMSmUtils dataFromBase64EncodedString:base64String]; ``` ```objc // Validate HEX string format BOOL isValidHex = [GMSmUtils isValidHexString:@"0123456789ABCDEF"]; // YES BOOL isInvalidHex = [GMSmUtils isValidHexString:@"GHIJK"]; // NO ``` ```objc // Validate Base64 string format BOOL isValidBase64 = [GMSmUtils isValidBase64String:@"SGVsbG8="]; // YES ``` ```objc // Pad HEX string with leading zeros (useful for BIGNUM alignment) NSString *shortHex = @"ABC"; NSString *paddedHex = [GMSmUtils prefixPaddingZero:shortHex maxLen:8]; // Result: "00000ABC" ``` -------------------------------- ### Generate and Manipulate SM2 Keys Source: https://context7.com/muzipiao/gmobjc/llms.txt Create SM2 key pairs and perform public key compression or decompression. Keys are handled as HEX-encoded strings. ```objective-c #import // Generate a new SM2 key pair GMSm2Key *keyPair = [GMSm2Utils generateKey]; // Public key: 04 + 64-byte X coordinate + 64-byte Y coordinate (130 hex chars total) NSString *publicKey = keyPair.publicKey; // Example: "0408E3FFF9505BCFAF9307E665E9229F4E1B3936437A870407EA3D97886BAFBC9C624537215DE9507BC0E2DD276CF74695C99DF42424F28E9004CDE4678F63D698" // Private key: 64 hex characters (32 bytes) NSString *privateKey = keyPair.privateKey; // Example: "90F3A42B9FE24AB196305FD92EC82E647616C3A3694441FB3422E7838E24DEAE" // Calculate public key from private key NSString *calculatedPubKey = [GMSm2Utils calcPublicKeyFromPrivateKey:privateKey]; // Result matches the original publicKey // Compress public key (04 prefix -> 02/03 prefix) NSString *compressedKey = [GMSm2Utils compressPublicKey:publicKey]; // Example: "0208E3FFF9505BCFAF9307E665E9229F4E1B3936437A870407EA3D97886BAFBC9C" // Decompress public key back to original format NSString *decompressedKey = [GMSm2Utils decompressPublicKey:compressedKey]; // Result equals original publicKey ``` -------------------------------- ### Compute SM3 Hash Digest for Binary Data Source: https://context7.com/muzipiao/gmobjc/llms.txt Compute the SM3 cryptographic hash digest for binary data such as files or images. The output is a 32-byte hash, returned as a 64-character HEX string after conversion. Use this for verifying data integrity. ```objc #import // Hash binary data (files, images, etc.) NSData *fileData = [NSData dataWithContentsOfFile:@"/path/to/file.pdf"]; NSData *hashData = [GMSm3Utils hashWithData:fileData]; NSString *fileHashHex = [GMSm3Utils hexStringFromData:hashData]; // Verify data integrity NSString *originalHash = [GMSm3Utils hashWithText:@"Original content"]; NSString *verifyHash = [GMSm3Utils hashWithText:@"Original content"]; if ([originalHash isEqualToString:verifyHash]) { NSLog(@"Data integrity verified"); } // Multiple hashes of same input always produce identical output NSString *hash1 = [GMSm3Utils hashWithText:@"Consistent input"]; NSString *hash2 = [GMSm3Utils hashWithText:@"Consistent input"]; // hash1 == hash2 is always true ``` -------------------------------- ### Generate SM4 Keys and IVs in Objective-C Source: https://context7.com/muzipiao/gmobjc/llms.txt Generates 16-byte keys and IVs as 32-character HEX strings. Use GMSmUtils to convert these to NSData for binary operations. ```objc #import // Generate a random SM4 key (32 hex chars = 16 bytes) NSString *keyHex = [GMSm4Utils generateKey]; // Example: "0123456789ABCDEF0123456789ABCDEF" // Generate IV for CBC mode (same length as key) NSString *ivHex = [GMSm4Utils generateKey]; // Example: "FEDCBA9876543210FEDCBA9876543210" // Convert HEX key to NSData for data-based operations NSData *keyData = [GMSmUtils dataFromHexString:keyHex]; // keyData.length == 16 // Generate multiple keys for different purposes NSString *encryptionKey = [GMSm4Utils generateKey]; NSString *macKey = [GMSm4Utils generateKey]; NSLog(@"Encryption Key: %@", encryptionKey); NSLog(@"MAC Key: %@", macKey); ``` -------------------------------- ### Perform SM4 CBC Mode Encryption and Decryption Source: https://context7.com/muzipiao/gmobjc/llms.txt Encrypts and decrypts data using CBC mode, which requires an initialization vector (IV). It is recommended to generate a unique IV for each encryption operation. ```objc #import // SM4 key and IV (both 32 hex chars = 16 bytes) NSString *keyHex = @"0123456789ABCDEF0123456789ABCDEF"; NSString *ivHex = @"FEDCBA9876543210FEDCBA9876543210"; // Encrypt string with CBC mode NSString *plaintext = @"Sensitive data requiring CBC encryption for better security!"; NSString *ciphertextHex = [GMSm4Utils encryptTextWithCBC:plaintext keyHex:keyHex ivecHex:ivHex]; // Decrypt - must use same key and IV NSString *decryptedText = [GMSm4Utils decryptTextWithCBC:ciphertextHex keyHex:keyHex ivecHex:ivHex]; // Result: "Sensitive data requiring CBC encryption for better security!" // Encrypt binary data with CBC NSData *sensitiveData = [@"Top secret information" dataUsingEncoding:NSUTF8StringEncoding]; NSData *keyData = [GMSmUtils dataFromHexString:keyHex]; NSData *ivData = [GMSmUtils dataFromHexString:ivHex]; NSData *encryptedData = [GMSm4Utils encryptDataWithCBC:sensitiveData keyData:keyData ivecData:ivData]; // Decrypt binary data NSData *decryptedData = [GMSm4Utils decryptDataWithCBC:encryptedData keyData:keyData ivecData:ivData]; NSString *result = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding]; // Best practice: Generate random IV for each encryption NSString *randomIV = [GMSm4Utils generateKey]; NSString *encrypted = [GMSm4Utils encryptTextWithCBC:@"Message" keyHex:keyHex ivecHex:randomIV]; // Store IV alongside ciphertext (IV doesn't need to be secret) ``` -------------------------------- ### Generate SM2 Key Pair Source: https://github.com/muzipiao/gmobjc/blob/master/README.md Generate SM2 public and private keys as HEX-encoded strings. ```objc // Generate public and private keys, both of which are in HEX-encoded string format GMSm2Key *keyPair = [GMSm2Utils generateKey]; // SM2 public key "0408E3FFF9505BCFAF9307E665...695C99DF42424F28E9004CDE4678F63D698" NSString *pubKey = keyPair.publicKey; // SM2 private key "90F3A42B9FE24AB196305FD92EC82E647616C3A3694441FB3422E7838E24DEAE" NSString *priKey = keyPair.privateKey; ``` -------------------------------- ### Read X.509 Certificate Information Source: https://context7.com/muzipiao/gmobjc/llms.txt Parses X.509 certificates from data, supporting CER, DER, and PKCS#12 formats. Extracts details like version, public key, serial number, validity dates, subject/issuer information, and fingerprints. Handles password-protected PKCS#12 files. ```objc #import // Read X.509 certificate information NSData *certData = [NSData dataWithContentsOfFile:@"/path/to/certificate.cer"]; GMSm2X509Info *certInfo = [GMSm2Bio readX509InfoFromData:certData password:nil]; // Access certificate properties NSLog(@"Version: %@", certInfo.version); NSLog(@"Public Key: %@", certInfo.publicKey); NSLog(@"Serial Number: %@", certInfo.serialNumber); NSLog(@"Valid From: %@", certInfo.effectiveDate); // Format: yyyyMMddHHmmss (UTC) NSLog(@"Valid Until: %@", certInfo.expirationDate); // Format: yyyyMMddHHmmss (UTC) NSLog(@"Signature Algorithm: %@", certInfo.signatureAlgorithm); // Subject information NSLog(@"Common Name: %@", certInfo.commonName); NSLog(@"Organization: %@", certInfo.organization); NSLog(@"Country: %@", certInfo.country); // Issuer information NSLog(@"Issuer CN: %@", certInfo.issuerCommonName); NSLog(@"Issuer Org: %@", certInfo.issuerOrganization); // Fingerprints for verification NSLog(@"SHA-1 Fingerprint: %@", certInfo.sha1Fingerprint); NSLog(@"SHA-256 Fingerprint: %@", certInfo.sha256Fingerprint); // Read PKCS#12 file (.p12/.pfx) with password NSData *p12Data = [NSData dataWithContentsOfFile:@"/path/to/keystore.p12"]; NSData *p12Password = [@"keystorePassword" dataUsingEncoding:NSUTF8StringEncoding]; GMSm2X509Info *p12Info = [GMSm2Bio readX509InfoFromData:p12Data password:p12Password]; // PKCS#12 may contain private key if (p12Info.privateKey.length > 0) { NSLog(@"Private Key extracted: %@", p12Info.privateKey); } // Use extracted public key for encryption NSString *encrypted = [GMSm2Utils encryptText:@"Secret" publicKey:certInfo.publicKey]; ``` -------------------------------- ### SM4 CBC Encryption and Decryption Source: https://github.com/muzipiao/gmobjc/blob/master/README.md Performs SM4 encryption and decryption using the CBC mode. Requires a 16-byte (32-byte HEX encoded) initialization vector (IV) in addition to the key. ```objc // CBC mode requires 16 bytes (32 bytes in HEX encoding format) initialization vector (IV) NSString *ivecHex = @"0123456789abcdef0123456789abcdef"; // Encryption. The ciphertext is in HEX encoding format NSString *ciphertext = [GMSm4Utils encryptTextWithCBC:plaintext keyHex:sm4KeyHex ivecHex:ivecHex]; // Decryption. The decrypted result is "Hello, SM4!" NSString *decrypted = [GMSm4Utils decryptTextWithCBC:ciphertext keyHex:sm4KeyHex ivecHex:ivecHex]; ``` -------------------------------- ### Compute SM3 Hash Digest for Text Source: https://context7.com/muzipiao/gmobjc/llms.txt Compute the SM3 cryptographic hash digest for a given string. The output is a 256-bit (32-byte) hash, returned as a 64-character HEX string. Multiple hashes of the same input will always produce identical output. ```objc #import // Hash a string - returns 64-char HEX digest NSString *text = @"Hello, SM3 hash algorithm!"; NSString *hashHex = [GMSm3Utils hashWithText:text]; // Example output: "A1B2C3D4E5F6..." (64 hex characters) ``` -------------------------------- ### SM4 String Encryption/Decryption (CBC Mode) Source: https://github.com/muzipiao/gmobjc/blob/master/README-CN.md Encrypts and decrypts strings using SM4 in CBC mode. Requires a 32-byte HEX encoded key and a 16-byte (32-byte HEX encoded) initialization vector (IV). The output ciphertext is HEX encoded. ```objc // CBC 模式需要 16 字节(HEX 编码格式为 32 字节)初始化向量(IV) NSString *ivecHex = @"0123456789abcdef0123456789abcdef"; // 加密。密文为 HEX 编码格式 NSString *ciphertext = [GMSm4Utils encryptTextWithCBC:plaintext keyHex:sm4KeyHex ivecHex:ivecHex]; // 解密。解密结果为 "Hello, SM4!" NSString *decrypted = [GMSm4Utils decryptTextWithCBC:ciphertext keyHex:sm4KeyHex ivecHex:ivecHex]; ``` -------------------------------- ### Perform SM2 Encryption and Decryption Source: https://github.com/muzipiao/gmobjc/blob/master/README.md Encrypt and decrypt text using SM2, including conversions between ASN1 and C1C3C2/C1C2C3 formats. ```objc // Plain text (string type) NSString *plaintext = @"123456"; // SM2 encryption string type, the result is ASN1 format ciphertext, and encoded in HEX format NSString *asn1Hex = [GMSm2Utils encryptText:plaintext publicKey:pubKey]; // Decrypt to get the string plain text "123456" NSString *plaintext = [GMSm2Utils decryptHex:asn1Hex privateKey:priKey]; // ASN1 decoded to C1C3C2 format (HEX encoding format) NSString *c1c3c2Hex = [GMSm2Utils asn1DecodeToC1C3C2Hex:asn1Hex hasPrefix:NO]; // Ciphertext order C1C3C2 and C1C2C3 can be converted to each other NSString *c1c2c3Hex = [GMSm2Utils convertC1C3C2HexToC1C2C3:c1c3c2Hex hasPrefix:NO]; ``` -------------------------------- ### SM2 Digital Signature and Verification Source: https://context7.com/muzipiao/gmobjc/llms.txt Sign data using an SM2 private key and verify signatures with the corresponding public key. Supports both text and NSData inputs, with optional User ID for signing and verification. Signatures are returned as 128-character HEX strings (R + S concatenation). ```objc #import NSString *publicKey = @"0408E3FFF9505BCFAF9307E665E9229F4E1B3936437A870407EA3D97886BAFBC9C624537215DE9507BC0E2DD276CF74695C99DF42424F28E9004CDE4678F63D698"; NSString *privateKey = @"90F3A42B9FE24AB196305FD92EC82E647616C3A3694441FB3422E7838E24DEAE"; // Sign text with optional user ID (default: "1234567812345678") NSString *message = @"Important document content"; NSString *userID = @"user@example.com"; // Sign - returns 128-char HEX string (64 chars R + 64 chars S) NSString *signatureRS = [GMSm2Utils signText:message privateKey:privateKey userText:userID]; // Verify signature - returns YES if valid BOOL isValid = [GMSm2Utils verifyText:message signRS:signatureRS publicKey:publicKey userText:userID]; // Result: YES // Sign with default userID (nil uses "1234567812345678") NSString *signDefault = [GMSm2Utils signText:message privateKey:privateKey userText:nil]; BOOL isValidDefault = [GMSm2Utils verifyText:message signRS:signDefault publicKey:publicKey userText:nil]; // DER encode signature for standard compliance NSString *derSignature = [GMSm2Utils encodeDerWithSignRS:signatureRS]; // Decode DER back to RS format NSString *decodedRS = [GMSm2Utils decodeDerToSignRS:derSignature]; // decodedRS equals original signatureRS // Sign NSData (for binary content like files) NSData *documentData = [message dataUsingEncoding:NSUTF8StringEncoding]; NSData *userData = [userID dataUsingEncoding:NSUTF8StringEncoding]; NSString *dataSignature = [GMSm2Utils signData:documentData privateKey:privateKey userData:userData]; // Verify NSData signature BOOL isDataValid = [GMSm2Utils verifyData:documentData signRS:dataSignature publicKey:publicKey userData:userData]; // Result: YES ``` -------------------------------- ### Perform ECDH Key Agreement Source: https://context7.com/muzipiao/gmobjc/llms.txt Use this to derive a shared secret between two parties for symmetric encryption. Both parties must compute the same 32-byte symmetric key. ```objc #import // Client generates key pair GMSm2Key *clientKey = [GMSm2Utils generateKey]; NSString *clientPublicKey = clientKey.publicKey; NSString *clientPrivateKey = clientKey.privateKey; // Server generates key pair GMSm2Key *serverKey = [GMSm2Utils generateKey]; NSString *serverPublicKey = serverKey.publicKey; NSString *serverPrivateKey = serverKey.privateKey; // Client computes shared secret using server's public key NSString *clientSharedSecret = [GMSm2Utils computeECDH:serverPublicKey privateKey:clientPrivateKey]; // Returns 64-char HEX string (32 bytes) // Server computes shared secret using client's public key NSString *serverSharedSecret = [GMSm2Utils computeECDH:clientPublicKey privateKey:serverPrivateKey]; // Returns 64-char HEX string (32 bytes) // Both shared secrets are identical if ([clientSharedSecret isEqualToString:serverSharedSecret]) { NSLog(@"ECDH key agreement successful!"); NSLog(@"Shared key: %@", clientSharedSecret); // Use first 32 hex chars (16 bytes) as SM4 key NSString *sm4Key = [clientSharedSecret substringToIndex:32]; // Now both parties can encrypt/decrypt using SM4 with the shared key NSString *encrypted = [GMSm4Utils encryptTextWithECB:@"Secret message" keyHex:sm4Key]; NSString *decrypted = [GMSm4Utils decryptTextWithECB:encrypted keyHex:sm4Key]; } ``` -------------------------------- ### Perform SM2 Encryption and Decryption Source: https://context7.com/muzipiao/gmobjc/llms.txt Encrypt and decrypt strings or binary data using SM2 public and private keys. Ciphertext is returned in ASN1 format by default. ```objective-c #import // Key pair for encryption/decryption NSString *publicKey = @"0408E3FFF9505BCFAF9307E665E9229F4E1B3936437A870407EA3D97886BAFBC9C624537215DE9507BC0E2DD276CF74695C99DF42424F28E9004CDE4678F63D698"; NSString *privateKey = @"90F3A42B9FE24AB196305FD92EC82E647616C3A3694441FB3422E7838E24DEAE"; // Encrypt string - returns ASN1 encoded ciphertext in HEX format NSString *plaintext = @"Hello, SM2 encryption!"; NSString *ciphertextHex = [GMSm2Utils encryptText:plaintext publicKey:publicKey]; // Decrypt HEX ciphertext - returns original plaintext NSString *decryptedText = [GMSm2Utils decryptHex:ciphertextHex privateKey:privateKey]; // Result: "Hello, SM2 encryption!" // Encrypt NSData - for binary data like files NSData *plainData = [@"Binary data content" dataUsingEncoding:NSUTF8StringEncoding]; NSData *cipherData = [GMSm2Utils encryptData:plainData publicKey:publicKey]; // Decrypt NSData NSData *decryptedData = [GMSm2Utils decryptData:cipherData privateKey:privateKey]; NSString *result = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding]; // Result: "Binary data content" ``` -------------------------------- ### ECDH Key Negotiation Source: https://github.com/muzipiao/gmobjc/blob/master/README.md Performs Elliptic Curve Diffie-Hellman key negotiation to establish a shared symmetric key. Both parties must exchange public keys and use their own private keys. ```objc // The client client obtains the public key serverPubKey from the server, and the client negotiates a 32-byte symmetric key clientECDH, which is 64 bytes after conversion to Hex NSString *clientECDH = [GMSm2Utils computeECDH:serverPubKey privateKey:clientPriKey]; // The client client sends the public key clientPubKey to the server, and the server negotiates a 32-byte symmetric key serverECDH, which is 64 bytes after conversion to Hex NSString *serverECDH = [GMSm2Utils computeECDH:clientPubKey privateKey:serverPriKey]; // In the case of all plaintext transmission, the client and server negotiate an equal symmetric key, and clientECDH==serverECDH holds if ([clientECDH isEqualToString:serverECDH]) { NSLog(@"ECDH key negotiation is successful, and the negotiated symmetric key is:\n%@", clientECDH); }else{ NSLog(@"ECDH Key negotiation failed"); } ``` -------------------------------- ### SM4 String Encryption/Decryption (ECB Mode) Source: https://github.com/muzipiao/gmobjc/blob/master/README-CN.md Encrypts and decrypts strings using SM4 in ECB mode. Requires a 32-byte HEX encoded key. The output ciphertext is also HEX encoded. ```objc // 字符串加解密,HEX 编码格式密钥长度为 32 字节 NSString *sm4KeyHex = @"0123456789abcdef0123456789abcdef"; NSString *plaintext = @"Hello, SM4!"; // ECB加密。密文为 HEX 编码格式 NSString *ciphertext = [GMSm4Utils encryptTextWithECB:plaintext keyHex:sm4KeyHex]; // 解密。解密结果为 "Hello, SM4!" NSString *decrypted = [GMSm4Utils decryptTextWithECB:ciphertext keyHex:sm4KeyHex]; ``` -------------------------------- ### Convert SM2 Ciphertext Formats Source: https://context7.com/muzipiao/gmobjc/llms.txt Convert between ASN1, C1C3C2, and C1C2C3 formats for SM2 ciphertext. Useful for interoperability with other cryptographic libraries. Supports both NSString and NSData operations. ```objc #import NSString *publicKey = @"0408E3FFF9505BCFAF9307E665..."; NSString *privateKey = @"90F3A42B9FE24AB196305FD92..."; // Encrypt to get ASN1 format ciphertext NSString *plaintext = @"Test message"; NSString *asn1Hex = [GMSm2Utils encryptText:plaintext publicKey:publicKey]; // Decode ASN1 to C1C3C2 format (no 04 prefix) NSString *c1c3c2Hex = [GMSm2Utils asn1DecodeToC1C3C2Hex:asn1Hex hasPrefix:NO]; // Convert C1C3C2 to C1C2C3 (Java BouncyCastle compatible format) NSString *c1c2c3Hex = [GMSm2Utils convertC1C3C2HexToC1C2C3:c1c3c2Hex hasPrefix:NO]; // Convert back to C1C3C2 NSString *backToC1C3C2 = [GMSm2Utils convertC1C2C3HexToC1C3C2:c1c2c3Hex hasPrefix:NO]; // Encode C1C3C2 back to ASN1 format NSString *backToAsn1 = [GMSm2Utils asn1EncodeWithC1C3C2Hex:backToC1C3C2 hasPrefix:NO]; // Decrypt the re-encoded ciphertext NSString *decrypted = [GMSm2Utils decryptHex:backToAsn1 privateKey:privateKey]; // Result: "Test message" // NSData versions for binary operations NSData *plainData = [plaintext dataUsingEncoding:NSUTF8StringEncoding]; NSData *asn1Data = [GMSm2Utils encryptData:plainData publicKey:publicKey]; NSData *c1c3c2Data = [GMSm2Utils asn1DecodeToC1C3C2Data:asn1Data hasPrefix:NO]; NSData *c1c2c3Data = [GMSm2Utils convertC1C3C2DataToC1C2C3:c1c3c2Data hasPrefix:NO]; NSData *reconvertedData = [GMSm2Utils convertC1C2C3DataToC1C3C2:c1c2c3Data hasPrefix:NO]; NSData *asn1Encoded = [GMSm2Utils asn1EncodeWithC1C3C2Data:reconvertedData hasPrefix:NO]; ``` -------------------------------- ### SM4 ECB Encryption and Decryption Source: https://github.com/muzipiao/gmobjc/blob/master/README.md Performs SM4 encryption and decryption using the ECB mode. The key must be 32 bytes in HEX encoding. ```objc // String encryption and decryption, the key length of HEX encoding format is 32 bytes NSString *sm4KeyHex = @"0123456789abcdef0123456789abcdef"; NSString *plaintext = @"Hello, SM4!"; // ECB encryption. The ciphertext is in HEX encoding format NSString *ciphertext = [GMSm4Utils encryptTextWithECB:plaintext keyHex:sm4KeyHex]; // Decryption. The decrypted result is "Hello, SM4!" NSString *decrypted = [GMSm4Utils decryptTextWithECB:ciphertext keyHex:sm4KeyHex]; ``` -------------------------------- ### Compute SM3 HMAC Authentication Source: https://context7.com/muzipiao/gmobjc/llms.txt Compute HMAC-SM3 for message authentication and integrity verification. The default output is a 64-character HEX string. This method can also compute HMAC for other hash algorithms like MD5, SHA1, SHA256, SHA512. ```objc #import // HMAC-SM3 (default) NSString *message = @"Message to authenticate"; NSString *secretKey = @"my-secret-key-12345"; // Compute HMAC-SM3 - returns 64-char HEX string NSString *hmacSM3 = [GMSm3Utils hmacWithText:message keyText:secretKey]; // HMAC with other hash algorithms NSString *hmacMD5 = [GMSm3Utils hmacWithText:message keyText:secretKey keyType:GMHashType_MD5]; // Returns 32-char HEX (16 bytes) NSString *hmacSHA1 = [GMSm3Utils hmacWithText:message keyText:secretKey keyType:GMHashType_SHA1]; // Returns 40-char HEX (20 bytes) NSString *hmacSHA256 = [GMSm3Utils hmacWithText:message keyText:secretKey keyType:GMHashType_SHA256]; // Returns 64-char HEX (32 bytes) NSString *hmacSHA512 = [GMSm3Utils hmacWithText:message keyText:secretKey keyType:GMHashType_SHA512]; // Returns 128-char HEX (64 bytes) // HMAC with NSData for binary content NSData *binaryData = [@"Binary content" dataUsingEncoding:NSUTF8StringEncoding]; NSData *keyData = [secretKey dataUsingEncoding:NSUTF8StringEncoding]; NSData *hmacData = [GMSm3Utils hmacWithData:binaryData keyData:keyData]; NSData *hmacSHA384Data = [GMSm3Utils hmacWithData:binaryData keyData:keyData keyType:GMHashType_SHA384]; // Verify message authenticity NSString *receivedHmac = @"..."; // HMAC received with message NSString *computedHmac = [GMSm3Utils hmacWithText:message keyText:secretKey]; if ([receivedHmac isEqualToString:computedHmac]) { NSLog(@"Message is authentic and unmodified"); } ``` -------------------------------- ### Perform SM4 ECB Mode Encryption and Decryption Source: https://context7.com/muzipiao/gmobjc/llms.txt Encrypts and decrypts data using ECB mode, which processes blocks independently. Suitable for single blocks or random-access scenarios. ```objc #import // SM4 key (32 hex chars = 16 bytes) NSString *keyHex = @"0123456789ABCDEF0123456789ABCDEF"; // Encrypt string - returns HEX encoded ciphertext NSString *plaintext = @"Hello, SM4 ECB mode!"; NSString *ciphertextHex = [GMSm4Utils encryptTextWithECB:plaintext keyHex:keyHex]; // Decrypt - returns original plaintext NSString *decryptedText = [GMSm4Utils decryptTextWithECB:ciphertextHex keyHex:keyHex]; // Result: "Hello, SM4 ECB mode!" // Encrypt binary data (files, images, etc.) NSData *fileData = [NSData dataWithContentsOfFile:@"/path/to/document.pdf"]; NSData *keyData = [GMSmUtils dataFromHexString:keyHex]; NSData *encryptedData = [GMSm4Utils encryptDataWithECB:fileData keyData:keyData]; // Decrypt binary data NSData *decryptedData = [GMSm4Utils decryptDataWithECB:encryptedData keyData:keyData]; [decryptedData writeToFile:@"/path/to/decrypted.pdf" atomically:YES]; // Example: Encrypt user credentials NSString *password = @"user_password_123"; NSString *encryptedPassword = [GMSm4Utils encryptTextWithECB:password keyHex:keyHex]; // Store encryptedPassword securely // Decrypt when needed NSString *originalPassword = [GMSm4Utils decryptTextWithECB:encryptedPassword keyHex:keyHex]; ``` -------------------------------- ### SM2 Signature Verification Source: https://github.com/muzipiao/gmobjc/blob/master/README.md Verifies an SM2 signature using a public key. Ensure the userID matches between signing and verification. ```objc NSString *plaintext = @"123456"; // When userID is nil or empty, the default is 1234567812345678; when it is not empty, the signature and verification need the same ID NSString *userID = @"lifei_zdjl@126.com"; // The signature result is a 128-byte Hex string concatenated by RS, the first 64 bytes are R, and the last 64 bytes are S NSString *signRS = [GMSm2Utils signText:plaintext privateKey:priKey userText:userID]; // Verify the signature, return YES if the verification is successful, otherwise the verification fails BOOL isOK = [GMSm2Utils verifyText:plaintext signRS:signRS publicKey:pubKey userText:userID]; ``` -------------------------------- ### Configure Elliptic Curve Type for SM2 Operations Source: https://context7.com/muzipiao/gmobjc/llms.txt Set the elliptic curve type for SM2 operations using GMSm2Utils. Supports sm2p256v1 (default), secp256k1, and secp256r1. Ensure consistent curve settings for key generation and cryptographic operations. ```objc #import // Check current curve type int currentCurve = [GMSm2Utils curveType]; // Default: GMSm2CurveSm2p256v1 (1172) ``` ```objc // Use SM2 recommended curve (default) - GM/T 0003-2012 standard [GMSm2Utils setCurveType:GMSm2CurveSm2p256v1]; GMSm2Key *sm2Key = [GMSm2Utils generateKey]; ``` ```objc // Use secp256k1 curve (Bitcoin/Ethereum compatible) [GMSm2Utils setCurveType:GMSm2CurveSecp256k1]; GMSm2Key *secp256k1Key = [GMSm2Utils generateKey]; ``` ```objc // Use secp256r1 curve (NIST P-256) [GMSm2Utils setCurveType:GMSm2CurveSecp256r1]; GMSm2Key *secp256r1Key = [GMSm2Utils generateKey]; ``` ```objc // Reset to default SM2 curve [GMSm2Utils setCurveType:GMSm2CurveSm2p256v1]; ``` ```objc // Important: Keys generated with one curve type cannot be used with another // Always ensure consistent curve settings across encryption/decryption operations ``` -------------------------------- ### SM3 Digest Calculation Source: https://github.com/muzipiao/gmobjc/blob/master/README.md Calculates the SM3 digest for text or HMAC digests. The SM3 digest is a 64-byte HEX-encoded string. ```objc // String input, return hexadecimal digest NSString *digest = [GMSm3Utils hashWithText:@"Hello, SM3!"]; // SM3 is used to calculate HMAC digest by default, and other algorithms such as MD5, SHA1, SHA224/256/384/512 are also supported NSString *hmac = [GMSm3Utils hmacWithText:@"Message" keyText:@"SecretKey"]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.