Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

flutter encrypt [RSA/ECB/OAEPWithSHA-256AndMGF1Padding] #299

Open
shree-krishna-gapi opened this issue Apr 25, 2023 · 0 comments
Open

flutter encrypt [RSA/ECB/OAEPWithSHA-256AndMGF1Padding] #299

shree-krishna-gapi opened this issue Apr 25, 2023 · 0 comments

Comments

@shree-krishna-gapi
Copy link

have any one have a sample code please share guyz
I try with using this https://pub.dev/packages/encrypt package it worked encrypted but while post string encryptedData on postman shown me
decrypt error while public key and private key is exactly same and it's working on angular but not working on flutter
please guide me guys i'have been stuck from ma more days. i shown my code is below

import 'dart:convert';
import 'package:encrypt/encrypt.dart';
import 'package:flutter/services.dart';
import "package:pointycastle/export.dart";

Future encryptData(String payload) async{
final key = Key.fromSecureRandom(32);
final iv = IV.fromSecureRandom(16);
final encrypter = Encrypter(AES(key, mode: AESMode.cbc, padding: "PKCS7"));
final encrypted = encrypter.encrypt(payload, iv: iv);
String encryptedString = base64.encode(encrypted.bytes);
final parser = RSAKeyParser();
final publicPem = await rootBundle.loadString('assets/public.pem');
final RSAPublicKey publicKey = parser.parse(publicPem) as RSAPublicKey;
var keyValue = rsaEncrypt(RSAPublicKey(publicKey.modulus!, publicKey.exponent!),key.bytes);
String encryptedData = '${base64.encode(keyValue)}.${base64.encode(iv.bytes)}.$encryptedString';
return encryptedData;
}

Uint8List rsaEncrypt(RSAPublicKey myPublic, Uint8List dataToEncrypt) {
final encryptor = OAEPEncoding.withSHA256(RSAEngine())
..init(true, PublicKeyParameter(myPublic)); // true=encrypt
return _processInBlocks(encryptor, dataToEncrypt);
}

Uint8List _processInBlocks(AsymmetricBlockCipher engine, Uint8List input) {
final numBlocks = input.length ~/ engine.inputBlockSize +
((input.length % engine.inputBlockSize != 0) ? 1 : 0);
final output = Uint8List(numBlocks * engine.outputBlockSize);
var inputOffset = 0;
var outputOffset = 0;
while (inputOffset < input.length) {
final chunkSize = (inputOffset + engine.inputBlockSize <= input.length)
? engine.inputBlockSize
: input.length - inputOffset;
outputOffset += engine.processBlock(
input, inputOffset, chunkSize, output, outputOffset);
inputOffset += chunkSize;
}
return (output.length == outputOffset)
? output
: output.sublist(0, outputOffset);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant