2016-02-16 60 views
0

這是我的代碼。任何時候項目返回爲null.I已嘗試swiftobjective c,但沒有。SecPKCS12任何時候都可以返回空物品

let certName : String = "private_key"//name of the certificate// 
        //get p12 file path 
let resourcePath: String = NSBundle.mainBundle().pathForResource(certName, ofType: "p12")! 
let p12Data: NSData = NSData(contentsOfFile: resourcePath)! 
        //create key dictionary for reading p12 file 
let key : NSString = kSecImportExportPassphrase as NSString 
let options : NSDictionary = [key : "password"] 
        //create variable for holding security information 
var privateKeyRef: SecKeyRef? = nil 

var items : CFArray? 

let securityError: OSStatus = SecPKCS12Import(p12Data, options, &items) 
print(items) 
+0

它返回什麼錯誤?你在'securityError'中捕獲錯誤,但是忽略它。 –

+0

securityError等於0,但項目總是返回零 –

+0

@ArthurSahakyan你有答案,爲什麼項目是零? – virus

回答

0
I'm using pkcs8. And you need to include 
#include <CommonCrypto/CommonDigest.h> 
#include <openssl/engine.h> 
openssl download from Github 




    + (NSString*) getSignatureData:(NSString*) signableData { 
      // get private key path 
      NSString* path = [[NSBundle mainBundle] pathForResource:@"private" 
                  ofType:@"der"]; 

     NSData* datasss = [signableData dataUsingEncoding:NSNonLossyASCIIStringEncoding];  
     char* text = (char*) [signableData UTF8String]; 
      unsigned char *data; 
      data = (unsigned char *) text; 

      //creates a new file BIO with mode, mode the meaning of mode is the same as the stdio function fopen() 
      BIO *in = BIO_new_file([path cStringUsingEncoding:NSUTF8StringEncoding], "rb"); 

      //PKCS#8 private key info structure 
      PKCS8_PRIV_KEY_INFO *p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL); 


      EVP_PKEY *pkey = EVP_PKCS82PKEY(p8inf); 
      PKCS8_PRIV_KEY_INFO_free(p8inf); 
      BIO_free(in); 

      uint8_t * cipherBuffer = NULL; 

      // Calculate the buffer sizes. 
      unsigned int cipherBufferSize = RSA_size(pkey->pkey.rsa); 
      unsigned int signatureLength; 

      // Allocate some buffer space. 
      cipherBuffer = malloc(cipherBufferSize); 
      memset((void *)cipherBuffer, 0x0, cipherBufferSize); 
      unsigned char hashedChars[32]; 
      //return a pointer to the hash value 
      unsigned char *openSSLHash = CC_SHA256(datasss.bytes, (CC_LONG)signableData.length, hashedChars); 
      //unsigned char *openSSLHash1 = SHA256(data, signableData.length, NULL); 
      /* 
      * The following function sign and verify a X509_SIG ASN1 object inside 
      * PKCS#8 padded RSA encryption 
      */ 
      RSA_sign(NID_sha256, openSSLHash, SHA256_DIGEST_LENGTH, cipherBuffer, &signatureLength, pkey->pkey.rsa); 

      NSData *signedData = [NSData dataWithBytes:(const void*)cipherBuffer length:signatureLength]; 

      EVP_PKEY_free(pkey); 
      NSString *base64String = [signedData base64EncodedStringWithOptions:0]; 


      return base64String; 


     } 
相關問題