如何使用SWIFT中的指数和模数生成RSA公钥?

时间:2018-01-15 08:58:15

标签: swift encryption aes rsa public-key-encryption

我正在尝试使用RSAEncryption加密AES密钥,我已经为两者创建了一个函数,AES加密将首先对DATA进行加密,然后调用RSAEncryption来加密AES加密密钥本身,然后将其发送到服务器以进行响应

下面是我试过的,现在我只是检查我在运行时创建的公钥是否与公钥相匹配,当我运行程序时,我打印公共的pem表示对应于模数和指数的密钥,RSA公钥的前缀缺少32个字符。

CODE:

import Foundation

import Alamofire

import SwiftyRSA

class Encryption {

private let rsaModulus: String = ""

private let rsaExponent: String = ""


public func rsaEncryption(password: String, data: Data, modulus: String, exponent: String) -> String? {

            if let modData = Data(base64Encoded: modulus),
            let expData = Data(base64Encoded: exponent),
            let keyData = Rsa.generatePublicKey(withModulus: modData, exponent: expData) {

            let keyDict:[NSObject:NSObject] = [
                kSecAttrKeyType: kSecAttrKeyTypeRSA,
                kSecAttrKeyClass: kSecAttrKeyClassPublic,
                kSecAttrKeySizeInBits: NSNumber(value: 2048),
                kSecReturnPersistentRef: true as NSObject
            ]

            let publicKey = SecKeyCreateWithData(keyData as CFData, keyDict as CFDictionary, nil)
            let pub = try! PublicKey(reference: publicKey!)
            let pem = try! pub.pemString() 

            let clear = try! ClearMessage(string: "Clear Text", using: .utf8)
            let encrypted = try! clear.encrypted(with: pub, padding: .PKCS1)

            print("Encrypted AES Key: \(encrypted.base64String)")
            print(separator: "\n")
            print(pem) //Print pem to check public key generated

        }
        return "NO"
    }
}

结果输出:

Encrypted AES Key: /.../

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAvvJwQMvjUI7DDnC2PYwGNGJrkq6acdkjIW1+WznI68FyfVWb15Gz
hiJ7IVVbPo1Rphkbr0Gs8vrkunwBxVIb1wCjiiwqdoR7EUvUHrk5WkNcSoNEu2l0
VnRVuFe+XTKrnQsgfRy2TzyW3eG2kOkQBHWwJCQT6pFOwLXhY4JwSBzdhPIUk7HM
20ntqmamMnKMEmEC2N+qOfBx2hKVv2s7bwGBI8NZoIdt6dbhFXgv5NWN+U9Mx3kd
mXpjz7CaGgxfbBhTy6SfJQzN0Exfv4VGxOHRDkO0Mmu/d2VIeT4Q8lM53YZWuyCm
/pZ4XCgi9Z/2ZmQmCszSOc2/495JQcV9ZQIDAQAB

-----END RSA PUBLIC KEY-----

公钥的实际输出应为:

-----BEGIN PUBLIC KEY-----
**MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A**MIIBCgKCAQEAvvJwQMvjUI7DDnC2PYwG
NGJrkq6acdkjIW1+WznI68FyfVWb15GzhiJ7IVVbPo1Rphkbr0Gs8vrkunwBxVIb
1wCjiiwqdoR7EUvUHrk5WkNcSoNEu2l0VnRVuFe+XTKrnQsgfRy2TzyW3eG2kOkQ
BHWwJCQT6pFOwLXhY4JwSBzdhPIUk7HM20ntqmamMnKMEmEC2N+qOfBx2hKVv2s7
bwGBI8NZoIdt6dbhFXgv5NWN+U9Mx3kdmXpjz7CaGgxfbBhTy6SfJQzN0Exfv4VG
xOHRDkO0Mmu/d2VIeT4Q8lM53YZWuyCm/pZ4XCgi9Z/2ZmQmCszSOc2/495JQcV9
ZQIDAQAB
-----END PUBLIC KEY-----

结果输出中缺少星星之间的字符。

0 个答案:

没有答案