'Convert Swift RSA encryption to Flutter Dart
I'm trying to port our ios mobile app to Flutter. It was written in swift. However, there is this part where I need to encrypt the login credential and card details with RSA encryption before posting to the server which I've not been able to get right.
I've tried several flutter packages which don't work. According to the iOS developer, there is a public key that is base64 encoded that needs to be used in encrypting the password.
Here is the Swift code
static func encrypt(string: String) -> String? {
guard let data = Data(base64Encoded: getPublicKey()) else { return nil }
print(data)
var attributes: CFDictionary {
return [kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecAttrKeyClass : kSecAttrKeyClassPublic,
kSecAttrKeySizeInBits : 2048,
kSecReturnPersistentRef : kCFBooleanTrue!] as CFDictionary
}
var error: Unmanaged<CFError>? = nil
guard let secKey = SecKeyCreateWithData(data as CFData, attributes, &error) else {
print(error.debugDescription)
return nil
}
print(attributes)
print(secKey)
return encryptSecKey(string: string, publicKey: secKey)
}
static func encryptSecKey(string: String, publicKey: SecKey) -> String? {
let buffer = [UInt8](string.utf8)
var keySize = SecKeyGetBlockSize(publicKey)
var keyBuffer = [UInt8](repeating: 0, count: keySize)
// Encrypto should less than key length
guard SecKeyEncrypt(publicKey, SecPadding.PKCS1, buffer, buffer.count, &keyBuffer, &keySize) == errSecSuccess else { return nil }
print(Data(bytes: keyBuffer, count: keySize).base64EncodedString())
return Data(bytes: keyBuffer, count: keySize).base64EncodedString()
}
I'll appreciate it if I can get any help to convert this to dart so I can use it in the flutter code.
I tried pointycastle encryption but it won't work.
String encrypt(String plaintext, String publicKey) {
var pem =
'-----BEGIN RSA PUBLIC KEY-----\n$publickey\n-----END RSA PUBLIC KEY-----';
var public = CryptoUtils.rsaPublicKeyFromPem(pem);
/// Initalizing Cipher
var cipher = PKCS1Encoding(RSAEngine());
cipher.init(true, PublicKeyParameter<RSAPublicKey>(public));
/// Converting into a [Unit8List] from List<int>
/// Then Encoding into Base64
Uint8List output =
cipher.process(Uint8List.fromList(utf8.encode(plaintext)));
var base64EncodedText = base64Encode(output);
return base64EncodedText;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
