Newer
Older
Meterage_iOS / Meterage / Extensions / String.swift
//
//  String.swift
//  Meterage
//
//  Created by 203 on 2023/2/2.
//

import Foundation
import SwiftyRSA

extension String {
    enum EncryptionError: Error {
        case wrongInputData
        case encryptFailed
    }
    
    // RSA加密
    func encryptByRSA(publicKey: String) throws -> String {
        guard let pubKey = try? PublicKey(base64Encoded: publicKey) else {
            throw (EncryptionError.encryptFailed)
        }
        guard let sourceString = try? ClearMessage(string: self, using: .utf8) else {
            throw (EncryptionError.encryptFailed)
        }

        if let encrypedStr = try? sourceString.encrypted(with: pubKey, padding: .PKCS1) {
            return encrypedStr.base64String
        } else {
            throw (EncryptionError.encryptFailed)
        }
    }
}