Author name: EkAdmin

Encrypt server (asp.net core7) api result to client (flutter)

o encrypt the server API result on the ASP.NET Core side and decrypt it on the Flutter side, you can use a symmetric encryption algorithm, such as AES. Here’s a high-level overview of the process:

On the ASP.NET Core side, you’ll need to generate an AES key and initialize a cipher in encryption mode. Use this cipher to encrypt the API result before sending it to the client.

using System;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc;

namespace EncryptedApiExample.Controllers
{
public class ApiController : Controller
{
[HttpGet]
public IActionResult GetData()
{
// The API result you want to send to the client
string apiResult = “secret data”;

// Generate a random AES key
byte[] key = GenerateAesKey();

// Initialize a cipher in encryption mode
Aes aes = Aes.Create();
aes.Key = key;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aes.CreateEncryptor();

// Encrypt the API result
byte[] encryptedResult = encryptor.TransformFinalBlock(Encoding.UTF8.GetBytes(apiResult), 0, apiResult.Length);

// Return the encrypted result and the AES key to the client
return Ok(new { encryptedResult, key });
}

private byte[] GenerateAesKey()
{
// Your implementation for generating a random AES key goes here
// For this example, let’s generate a random key of 128 bits (16 bytes)
byte[] key = new byte[16];
using (var rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(key);
}
return key;
}
}
}

On the Flutter side, you’ll need to receive the encrypted result and the AES key, then initialize a cipher in decryption mode to decrypt the result.

import ‘dart:convert’;
import ‘dart:typed_data’;

import ‘package:flutter/widgets.dart’;
import ‘package:pointycastle/pointycastle.dart’;

class DecryptedData with ChangeNotifier {
String _apiResult;

String get apiResult => _apiResult;

set apiResult(String apiResult) {
_apiResult = apiResult;
notifyListeners();
}
}

class DecryptApiResult with ChangeNotifier {
Future decryptResult(Uint8List encryptedResult, Uint8List key) async {
// Initialize a cipher in decryption mode
var aesParams = new KeyParameter(key);
var cipher = new StreamCipher(“AES/ECB/PKCS7”);
cipher.init(false, aesParams);

// Decrypt the API result
Uint8List decryptedResult = cipher.process(encryptedResult);

// Convert the decrypted result to a string
String apiResult = utf8.decode(decryptedResult);

// Update the decrypted data

Sending the encryption key over the network like this is not secure, as it can be intercepted by attackers. To securely encrypt the data, you should use a combination of asymmetric encryption and symmetric encryption.

Here’s a high-level overview of how it could be done:

On the server side, generate a public-private key pair using a secure asymmetric encryption algorithm such as RSA. Share the public key with the client.

On the client side, generate a random symmetric encryption key, such as an AES key, and use the public key to encrypt it.

On the server side, use the private key to decrypt the symmetric encryption key.

Use the symmetric encryption key to encrypt the API result on the server side and send it to the client.

On the client side, use the symmetric encryption key to decrypt the API result.

By using a combination of asymmetric and symmetric encryption, you can ensure that the encryption key is securely transmitted from the client to the server and that the data is encrypted and decrypted using a secure key. This makes it much more difficult for attackers to intercept the key and access the encrypted data.

For More Secureway

using System;
using System.Security.Cryptography;

namespace EncryptionExample
{
public static class RSAKeyGenerator
{
public static void GenerateKeys(out string publicKey, out string privateKey)
{
using (var rsa = RSA.Create())
{
publicKey = Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo());
privateKey = Convert.ToBase64String(rsa.ExportPkcs8PrivateKey());
}
}
}
}

using System;
using System.IO;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc;

namespace EncryptionExample.Controllers
{
[Route(“api/[controller]”)]
[ApiController]
public class DataController : ControllerBase
{
private static readonly byte[] _symmetricKey = new byte[32];
private static readonly byte[] _iv = new byte[16];

[HttpPost]
public IActionResult GetEncryptedData([FromBody] byte[] encryptedSymmetricKey)
{
using (var rsa = RSA.Create())
{
var privateKey = Convert.FromBase64String(““);
rsa.ImportPkcs8PrivateKey(privateKey, out _);

encryptedSymmetricKey = rsa.Decrypt(encryptedSymmetricKey, RSAEncryptionPadding.OaepSHA256);
}

using (var aes = Aes.Create())
{
aes.Key = encryptedSymmetricKey;
aes.IV = _iv;

using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
using (var streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(““);
}

return Ok(memoryStream.ToArray());
}
}
}
}
}

In Flutter

import ‘dart:convert’;
import ‘dart:io’;

import ‘package:flutter/material.dart’;
import ‘package:pointycastle/asymmetric/api.dart’;
import ‘package:pointycastle/asymmetric/rsa.dart’;
import ‘package:pointycastle/block/aes_fast.dart’;
import ‘package:pointycastle/key_generators/api.dart’;
import ‘package:pointycastle/random/fortuna_random.dart’;
import ‘package:http/http.dart’ as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: RaisedButton(
onPressed: () async {
// Generate a random symmetric encryption key
var keyGenerator = KeyGenerator(“AES”);
keyGenerator.init(KeyParameter(“Fortuna”));
var key = keyGenerator.generateKey();

// Encrypt the symmetric encryption key using the public key
var rsa = RSAEngine();
rsa.init(true, PublicKeyParameter(PublicKey(““)));
var encryptedSymmetricKey = rsa.process(key.keyData);

// Send the encrypted symmetric encryption key to the server
var response = await http.post(““, body: encryptedSymmetricKey);

// Decrypt the API result
var aes = AESFastEngine();
aes.init(false, KeyParameter(key.keyData));
var decryptedData = aes.process(response.bodyBytes);

// Print the decrypted data
print(utf8.decode(decryptedData));
},
child: Text(“Get Encrypted Data”),
),
),
),
);
}
}

If Client is JAVA

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class Main {
public static void main(String[] args) throws Exception {
// Generate a random symmetric encryption key
KeyGenerator keyGenerator = KeyGenerator.getInstance(“AES”);
SecretKey secretKey = keyGenerator.generateKey();

// Encrypt the symmetric encryption key using the public key
byte[] publicKeyBytes = Base64.decodeBase64(““);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(“RSA”);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance(“RSA/ECB/OAEPWithSHA-1AndMGF1Padding”);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedSymmetricKey = cipher.doFinal(secretKey.getEncoded());

// Send the encrypted symmetric encryption key to the server
// …

// Decrypt the API result
cipher = Cipher.getInstance(“AES”);
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), “AES”);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedData = cipher.doFinal();

// Print the decrypted data
System.out.println(new String(decryptedData));
}
}

VB.NET

Imports System.Security.Cryptography
Imports System.Text

Module Main
Sub Main()
Dim publicKey As String = “
Dim encryptedSymmetricKey As Byte() = EncryptSymmetricKey(publicKey)
Dim apiResult As Byte() =
Dim decryptedData As Byte() = DecryptApiResult(encryptedSymmetricKey, apiResult)
Console.WriteLine(Encoding.UTF8.GetString(decryptedData))
End Sub

Private Function EncryptSymmetricKey(publicKey As String) As Byte()
Dim symmetricKey As New RijndaelManaged
symmetricKey.KeySize = 256
symmetricKey.GenerateKey()

Dim publicKeyBytes As Byte() = Convert.FromBase64String(publicKey)
Dim publicKeyObject As New RSACryptoServiceProvider
publicKeyObject.ImportCspBlob(publicKeyBytes)

Return publicKeyObject.Encrypt(symmetricKey.Key, False)
End Function

Private Function DecryptApiResult(encryptedSymmetricKey As Byte(), apiResult As Byte()) As Byte()
Dim symmetricKey As New RijndaelManaged
symmetricKey.Key = encryptedSymmetricKey

Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(symmetricKey.Key, symmetricKey.IV)
Return decryptor.TransformFinalBlock(apiResult, 0, apiResult.Length)
End Function
End Module

Create an encrypted download link for a file in ASP.NET Core:

In your controller, you can generate a unique, encrypted identifier for the file:

using System;
using System.IO;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc;

namespace DownloadFileExample.Controllers
{
public class DownloadController : Controller
{
[HttpGet]
public IActionResult Download(string id)
{
// Decrypt the identifier to get the file path
string filePath = DecryptFileIdentifier(id);

// Check if the file exists
if (!System.IO.File.Exists(filePath))
{
return NotFound();
}

// Return the file as a FileResult
return File(System.IO.File.OpenRead(filePath), “application/pdf”, Path.GetFileName(filePath));
}

private string DecryptFileIdentifier(string encryptedIdentifier)
{
// Your implementation for decrypting the encrypted identifier goes here

// For this example, let’s assume the encrypted identifier is just a base64-encoded string of the file path
return System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(encryptedIdentifier));
}
}
}

To create an encrypted download link, you could generate an encrypted identifier for the file and include it in the link:

Download

@functions {
private string EncryptFileIdentifier(string filePath)
{
// Your implementation for encrypting the file path goes here

// For this example, let’s assume the encrypted identifier is just a base64-encoded string of the file path
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(filePath));
}
}

This is just one way to create an encrypted download link for a file in ASP.NET Core. You can use other encryption techniques to encrypt the identifier, such as AES encryption, if needed. The specific encryption technique you choose will depend on the level of security you require for your application.

The client/user will not know the actual web path or file name as the information is encrypted and can only be decrypted by the server. By encoding the file path in the download link, you are effectively obscuring the actual file location from the client/user. This can help to prevent unauthorized access to the file and protect sensitive information.

In the example I provided earlier, the file path is encrypted using a base64 encoding and included in the download link. When the user clicks the link, the encrypted identifier is passed to the Download action in the controller. The controller then uses the DecryptFileIdentifier method to decrypt the identifier and retrieve the actual file path. Finally, the file is returned to the client/user as a FileResult.

C# : Calculate Document Hash

using System;
using System.IO;
using System.Security.Cryptography;

namespace ReadDocumentHashExample
{
class Program
{
static void Main(string[] args)
{
string documentPath = “document.txt”;
string documentHash = CalculateDocumentHash(documentPath);
Console.WriteLine(“The hash of the document is: ” + documentHash);
}

static string CalculateDocumentHash(string documentPath)
{
using (SHA256 sha256 = SHA256.Create())
{
using (FileStream stream = File.OpenRead(documentPath))
{
byte[] hash = sha256.ComputeHash(stream);
return BitConverter.ToString(hash).Replace(“-“, “”).ToLowerInvariant();
}
}
}
}
}

Generic Handler: Response Immediately And Run DB Operation in Background

To respond to a request immediately and run code in the background without a callback, you can use asynchronous programming in ASP.NET. The basic idea is to return a response to the client as soon as possible, while allowing the code inside the API endpoint to run asynchronously on a background thread.

Here’s an example of how you can modify your code to achieve this:

Public Class updMsg : Inherits HttpTaskAsyncHandler

Private PhysicalPathOfThisFolder$
Private Const LogTitle$ = “updMsg”
Private ThisContext As HttpContext
Private IsDevEnv As Boolean = True
Dim EkConnStr$ = “”

Public Overrides Async Function ProcessRequestAsync(ByVal context As HttpContext) As Task
ThisContext = context
context.SkipAuthorization = True
context.Response.ContentType = “text/plain”
PhysicalPathOfThisFolder = context.Server.MapPath(“.”)
EkConnStr = ConfigurationManager.ConnectionStrings(“EkConnStrWA”).ConnectionString
Dim jsn$ = “”, Rtn$ = “done”
Dim err$ = “”
Dim Rdr As New StreamReader(ThisContext.Request.InputStream)
jsn = Rdr.ReadToEnd ‘jsn = File.ReadAllText(“d:\ekmailjson.txt”)
Await AddToLogAsync(jsn)

context.Response.ContentType = “text/json”
context.Response.Write(Rtn)

Try
Await Task.Run(Async Function()
Using con As New SqlConnection(EkConnStr)
Dim Qry$ = “insMsg”
Using cmd As New SqlCommand(Qry, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue(“@JSON”, jsn)
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
Await Task.Run(Function() sda.Fill(dt))
If dt.Rows.Count > 0 Then
Dim sts = dt.Rows(0).Item(“sts”)
err = dt.Rows(0).Item(“errMsg”)
If sts = “done” Then
Dim MsgTo$ = dt.Rows(0).Item(“MsgTo”)
‘Rtn = GetMsgReturn(MsgTo)
Rtn = dt.Rows(0).Item(“jsn”)
Await AddToLogAsync(Rtn)
End If
Else
err = “No Rec Found”
End If
End Using
End Using
End Using
End Using
End Function)
Catch ex As Exception
Err = ex.Message.ToString + vbCrLf + ex.StackTrace.ToString
Finally

End Try

If err <> “” Then
Await AddToLogAsync(err)
End If
End Function
End Class

In this example, the response is immediately returned to the client using context.Response.Write(Rtn). The code inside the Try block is then executed asynchronously on a background thread

Generic Handler (ASHX) : Add To Log Function Async

Private Async Function AddToLogAsync(ByVal LogData$) As Task
Dim retryCount As Integer = 0
While retryCount < 5 Try Using writer As StreamWriter = File.AppendText(PhysicalPathOfThisFolder & "/updMsg.log") Await writer.WriteLineAsync(LogData) End Using ' If no exception was thrown, break the loop Exit While Catch ex As Exception If TypeOf ex Is IOException AndAlso ex.Message.Contains("being used by another process") Then ' File is locked, wait and retry Await Task.Delay(100) retryCount += 1 Else ' Log the exception Await AddToLogAsync("Error: " & ex.Message & vbCrLf & ex.StackTrace) ' If this is not a file locking exception, break the loop Exit While End If End Try End While End Function

TSQL : Set Line Breake on String

In TSQL, you can add line breaks to a string by using the CHAR(13) or CHAR(10) character.

For example, the following code will create a string with line breaks:

DECLARE @text AS VARCHAR(MAX) = ‘Line 1’ + CHAR(13) + ‘Line 2’ + CHAR(10) + ‘Line 3′
SELECT @text

The CHAR(13) character represents a Carriage Return (CR) and the CHAR(10) character represents a Line Feed (LF). When used together, they create a line break.

Alternatively, you can use the NCHAR function to add Unicode characters, for example:

DECLARE @text AS NVARCHAR(MAX) = N’Line 1′ + NCHAR(13) + N’Line 2′ + NCHAR(10) + N’Line 3’
SELECT @text

Scroll to Top