生成RSA公钥/私钥对 [英] Generate an RSA public / private key pair

查看:220
本文介绍了生成RSA公钥/私钥对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在swift中生成RSA公钥/私钥对的最简单方法.我一直在谈论很多关于iOS不支持OpenSSL的问题.

I'm looking for the simplest way to generate an RSA public / private key pair in swift I've been seeing a lot talk about how iOS doesn't support OpenSSL.

我只需要生成密钥对并将公钥发送到我的服务器,服务器将使用该密钥encrypt一些数据并将其发送回我的私钥到decrypt.这是一次交易,之后我将不再需要密钥.

I simply need to generate the key pair and send the public key over to my server, the server will encrypt some data with the key and send it back over for my private key to decrypt. This is a one time transaction and I wont need the key anymore after that.

最简单,最轻巧的解决方案是什么?

What is the simplest and lightest solution for this?

推荐答案

此Github存储库- Heimdall ,应该可以帮助您生成密钥和加密数据.

This Github repo - Heimdall, should help you with generating keys and encrypting your data.

if let heimdall = Heimdall(tagPrefix: "com.example") {
    let testString = "This is a test string"
// Encryption/Decryption
if let encryptedString = heimdall.encrypt(testString) {
    println(encryptedString) // "cQzaQCQLhAWqkDyPoHnPrpsVh..."

    if let decryptedString = heimdall.decrypt(encryptedString) {
        println(decryptedString) // "This is a test string"
    }
}

// Signatures/Verification
if let signature = heimdall.sign(testString) {
    println(signature) // "fMVOFj6SQ7h+cZTEXZxkpgaDsMrki..."
    var verified = heimdall.verify(testString, signatureBase64: signature)
    println(verified) // True

    // If someone meddles with the message and the signature becomes invalid
    verified = heimdall.verify(testString + "injected false message",
                                signatureBase64: signature)
    println(verified) // False
}

使用自己的公钥加密数据:

Encrypting data with own public key:

The swift-rsautils by btnguyen2k Utils should help you with encrypting your data with your own public key. Its really simple to use.

首先,只需将RSAUtils.swift文件拖放到您的项目中即可.

First just drag and drop the RSAUtils.swift file to your project.

就这样!

let PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJh+/sdLdlVVcM5V5/j/RbwM8SL++Sc3dMqMK1nP73XYKhvO63bxPkWwaY0kwcUU40+QducwjueVOzcPFvHf+fECAwEAAQ=="

let sampleText:String = "WHATS UP"

let encrypted:NSData? = RSAUtils.encryptWithRSAPublicKey(sampleText.dataUsingEncoding(NSUTF8StringEncoding)!, pubkeyBase64: PUBLIC_KEY, keychainTag: "yourdomain.com")

let encryptedDataText = encrypted!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())

print(encryptedDataText)

打印:

ML5S87dfDB6l1uHFcACm2IdkGHpDGPUaYoSNTO+83qcWYxTEddFeKhETIcqF5n67nRDL0lKi5XV9uEI7hGTyKA==

这篇关于生成RSA公钥/私钥对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆