generateCSRInDeskTop method
Generates a CSR (Certificate Signing Request) using the provided private key and CSR configuration properties.
Implementation
Future<String> generateCSRInDeskTop(
String privateKeyPem,
CSRConfigProps csrProps,
String path,
) async {
// Directory supDir = await getApplicationSupportDirectory();
// String dbPath = supDir.path;
// final privateKeyFile = '$dbPath/${Uuid().v4()}.pem';
// final csrConfigFile = '$dbPath/${Uuid().v4()}.cnf';
print("privateKeyPem-$privateKeyPem-");
print("csrProps-${csrProps.toTemplate()}-");
final privateKeyFile = '$path/${Uuid().v4()}.pem';
final csrConfigFile = '$path/${Uuid().v4()}.cnf';
// final privateKeyFile =
// '${Platform.environment['TEMP_FOLDER'] ?? "/tmp/"}${Uuid().v4()}.pem';
// final csrConfigFile =
// '${Platform.environment['TEMP_FOLDER'] ?? "/tmp/"}${Uuid().v4()}.cnf';
print(privateKeyFile);
print(privateKeyFile);
try {
File(privateKeyFile).writeAsStringSync(privateKeyPem);
File(csrConfigFile).writeAsStringSync(csrProps.toTemplate());
final opensslCheckProcess = await Process.run('openssl', ['version']);
if (opensslCheckProcess.exitCode == 0) {
print('OpenSSL is installed: ${opensslCheckProcess.stdout}');
} else {
if (Platform.isWindows) {
await _installAndSetupOpenSSLInWindows();
} else {
throw Exception('Error: no CSR found in OpenSSL output.');
}
}
/// Execute the OpenSSL command
final process = await Process.start('openssl', [
'req',
'-new',
'-sha256',
'-key',
privateKeyFile,
'-config',
csrConfigFile,
]);
/// Capture the output
final output = await process.stdout.transform(utf8.decoder).join();
final errorOutput = await process.stderr.transform(utf8.decoder).join();
/// Check for errors
if (errorOutput.isNotEmpty) {
if (errorOutput.contains('Operation not permitted')) {
throw Exception(
'Permission denied: Unable to execute OpenSSL. Please ensure the application has the necessary permissions to execute external processes.',
);
}
throw Exception('OpenSSL error: $errorOutput');
}
/// Check if the CSR is present in the output
if (!output.contains('-----BEGIN CERTIFICATE REQUEST-----')) {
throw Exception('Error: no CSR found in OpenSSL output.');
}
/// Extract the CSR
final csr =
'-----BEGIN CERTIFICATE REQUEST-----${output.split('-----BEGIN CERTIFICATE REQUEST-----')[1]}'
.trim();
/// Perform cleanup if necessary
File(privateKeyFile).deleteSync();
File(csrConfigFile).deleteSync();
return csr;
} catch (e) {
print("Error during CSR generation: $e");
// Perform cleanup in case of an error
if (File(privateKeyFile).existsSync()) {
File(privateKeyFile).deleteSync();
}
if (File(csrConfigFile).existsSync()) {
File(csrConfigFile).deleteSync();
}
// Rethrow the exception for further handling
rethrow;
}
}