简体   繁体   中英

RSA-Encryption and Decryption in Webapp (JavaScript) and iOS-App (Swift)

I am building a webapp (JavaScript) and an iOS-App (Swift). The problem is that the iOS-app and the webapp both should create public and private keys and exchange these.

I tried using JSEncrypt ( https://github.com/travist/jsencrypt ) for the web-part and CryptorRSA for the mobile part.

When creating a public key in JSEncrypt I get something like this:

  -----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC68ROkNzyo01gJCvo94mI/SswF
2FWDk4nvjbkcFeDWUZFd8t/2whnNJv9Nj+Y0VO2LSu5fVm6FIuGiesz1EzaBNkIL
kfphsSJjE8GGRqHYgdUgidv1mgkF+86Uk7hDDYtv4gUTLALXdHwDpsu28ww57ISA
Gxxidh7oyR74+cq46wIDAQAB
-----END PUBLIC KEY-----

Then I try to encrypt it using CryptorRSA:

     let key = try? CryptorRSA.createPublicKey(withPEM: """
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC68ROkNzyo01gJCvo94mI/SswF
2FWDk4nvjbkcFeDWUZFd8t/2whnNJv9Nj+Y0VO2LSu5fVm6FIuGiesz1EzaBNkIL
kfphsSJjE8GGRqHYgdUgidv1mgkF+86Uk7hDDYtv4gUTLALXdHwDpsu28ww57ISA
Gxxidh7oyR74+cq46wIDAQAB
-----END PUBLIC KEY-----
""")



  if let k = key {
        print("1");
        if let text = try? CryptorRSA.createPlaintext(with: "hallo Welt!", using: String.Encoding.utf8) {
            print("2");
            let encryptedData = try? text.encrypted(with: k, algorithm: .sha1)
            print(encryptedData)
            if let d = encryptedData {
                print(try? d.base64String)
            }
        }

    }

Which returns:

chvRmbYpzNFVL5HPW9JP3BrkonSbcmObdfKteXfCr9Yw3Gycr4irqEjxroBFKli+lVF89lWaxTRCy2prn7Athbi7EGdG5y6dITyFWGf/p91NAAbWdQlz+AOsWb6lPs3MfBqHnqG2O1vDrh5yEGImM+40QvZB9yMLGTA1Y2LPRe157ymFOp3C4aW7/+we9a7aQiCw6QavcsUvdhg=

But when I try to decrypt it after that in JSEncrypt it just results in an error.

An indirect solution for the problem is to use a library which is made for "easy" crypto usage across different platforms.

I finally decided to use sodium/libsodium/nacl to do symmetric and asymmetric encryption across many platforms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM