2017-12-08 36 views
1

개인 디지털 서명 (암호가있는 문자열) (원시 또는 base64 인코딩)에 서명해야하는 프로젝트가 있습니다. 인터넷에서 검색 한 결과 개인 디지털 인증서가 x.509 형식 (RSA)임을 확인했습니다. xcode에서 UIFileSharingEnabled를 Enabled로 설정하고 Itunes를 사용하여 rsa.p12 인증서를 업로드했습니다. 다음으로 (데이터 또는 문자열) 형식의 문서 디렉토리에서 인증서를 가져옵니다. 내 질문은 어떻게 디지털 서명을 사용하여 모든 텍스트를 암호화 할 수 있습니까? 이 라이브러리 https://github.com/TakeScoop/SwiftyRSA/issues을 사용하려했지만이 라이브러리는 x.509 인증서를 지원하지 않습니다.디지털 서명이 포함 된 빠른 서명 문자열

+0

누군가가 대신 문자열의 파일에 서명하는 방법을 알고 있나요? –

답변

1

난 그냥 문자열 텍스트를 인코딩 코드를 발견하고는

func signRequestorId(requestorID: String) -> String? { 

    let name = "RSA256_4f1826090c554a439c419043270d40f7d.p12" 
    guard let certificateData = CustomFileManager.getFile(by: name) else { 
     return nil 
    } 

    var status: OSStatus 

    let certificateKey = "123456" 
    let options = [kSecImportExportPassphrase as String : certificateKey] 

    var optItems: CFArray? 
    status = SecPKCS12Import(certificateData as CFData, options as CFDictionary, &optItems) 
    if status != errSecSuccess { 
     print("Cannot sign the device id info: failed importing keystore.") 
     return nil 
    } 
    guard let items = optItems else { 
     return nil 
    } 

    // Cast CFArrayRef to Swift Array 
    let itemsArray = items as [AnyObject] 
    // Cast CFDictionaryRef as Swift Dictionary 
    guard let myIdentityAndTrust = itemsArray.first as? [String : AnyObject] else { 
     return nil 
    } 

    // Get our SecIdentityRef from the PKCS #12 blob 
    let outIdentity = myIdentityAndTrust[kSecImportItemIdentity as String] as! SecIdentity 
    var myReturnedCertificate: SecCertificate? 
    status = SecIdentityCopyCertificate(outIdentity, &myReturnedCertificate) 
    if status != errSecSuccess { 
     print("Failed to retrieve the certificate associated with the requested identity.") 
     return nil 
    } 

    // Get the private key associated with our identity 
    var optPrivateKey: SecKey? 
    status = SecIdentityCopyPrivateKey(outIdentity, &optPrivateKey) 
    if status != errSecSuccess { 
     print("Failed to extract the private key from the keystore.") 
     return nil 
    } 
    // Unwrap privateKey from optional SecKeyRef 
    guard let privateKey = optPrivateKey else { 
     return nil 
    } 

    // Retrieve the digital signature and sign the requestor 

    // Get the maximum size of the digital signature 
    var signedBytesSize: size_t = SecKeyGetBlockSize(privateKey) 
    var signedBytes: UnsafeMutablePointer<UInt8> 

    // alloc a buffer to hold the signature 
    signedBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: signedBytesSize) 
    memset(signedBytes, 0x0, signedBytesSize) 
    // We're calling alloc here, so we need to destroy and deinit 
    defer { 
     signedBytes.deinitialize() 
     signedBytes.deallocate(capacity: signedBytesSize) 
    } 

    // Sign data 
    let requestorData = requestorID.data(using: String.Encoding.utf8)! 
    // Generate a digital signature for our requestor from our cert 
    let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: requestorData.count) 
    let stream = OutputStream(toBuffer: buffer, capacity: requestorData.count) 

    stream.open() 
    requestorData.withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> Void in 
     stream.write(p, maxLength: requestorData.count) 
    }) 

    stream.close() 

    let weidformat = UnsafePointer<UInt8>(buffer) 

    status = SecKeyRawSign(privateKey, .PKCS1, weidformat, 
          requestorData.count, signedBytes, &signedBytesSize) 

    if status != errSecSuccess { 
     print("Cannot sign the device id info: failed obtaining the signed bytes.") 
     return nil 
    } 

    let encryptedBytes = NSData(bytes: signedBytes, length: signedBytesSize) 
    let signedRequestorId = encryptedBytes.base64EncodedString(options: []) 

    print(signedRequestorId) 
    return signedRequestorId 
} 

U는 이름으로 문서를 얻을 기능을 필요

작동

static func getFile(by name: String)-> Data?{ 
    let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first 
    let destinationUrl = documentsUrl!.appendingPathComponent("\(name)") 

    let isFileFound = FileManager.default.fileExists(atPath: destinationUrl.path) 
    if isFileFound { 
     let documentContent = FileManager.default.contents(atPath: destinationUrl.path) 
     return documentContent 
    } 
    return nil 
} 
enter code here