Decrypt message with private key RSA - c#

I have a problem how i can find the private key from windows 2008 server.
first i encrypt a data with public key that i extracted it from url HTTPS
like this:
public static string Encrypt(string Data)
{
try
{
var Crypto = new RSACryptoServiceProvider(2048);
var RsaKeyInfo = Crypto.ExportParameters(false);
RsaKeyInfo.Modulus = PublicKeyByte();
Crypto.ImportParameters(RsaKeyInfo);
var bytesData = Encoding.Unicode.GetBytes(Data);
var bytesCypherText = Crypto.Encrypt(bytesData, false);
var cypherText = Convert.ToBase64String(bytesCypherText);
return cypherText;
}
catch (Exception ex)
{
return null;
}
}
private static byte[] PublicKeyByte()
{
Uri u = new Uri("https:\\domain.com");
ServicePoint sp = ServicePointManager.FindServicePoint(u);
string groupName = Guid.NewGuid().ToString();
HttpWebRequest req = HttpWebRequest.Create(u) as HttpWebRequest;
req.ConnectionGroupName = groupName;
using (WebResponse resp = req.GetResponse())
{
}
sp.CloseConnectionGroup(groupName);
return sp.Certificate.GetPublicKey(); ;
}
Now i dont know how extract private key in C# for decrypting message?
and i want to know more informations about this
thanks,

i resolved this by extracting the certificate file .PFX and im using System.Security.Cryptography.X509Certificates for encrypting and decrypting:
public static string Encrypt(string data)
{
try
{
var path = #"certificate.pfx";
var password = "test";
var collection = new X509Certificate2Collection();
collection.Import(path, password, X509KeyStorageFlags.PersistKeySet);
var certificate = collection[0];
var publicKey = certificate.PublicKey.Key as RSACryptoServiceProvider;
var bytesData = Convert.FromBase64String(data);
var encryptedData = publicKey.Encrypt(bytesData, false);
var cypherText = Convert.ToBase64String(encryptedData);
return cypherText;
}
catch (Exception ex)
{
return null;
}
}
public static string Decrypt(string data)
{
try
{
var path = #"certificate.pfx";
var password = "test";
var collection = new X509Certificate2Collection();
collection.Import(path, password, X509KeyStorageFlags.PersistKeySet);
var certificate = collection[0];
var privateKey = certificate.PrivateKey as RSACryptoServiceProvider;
var bytesData = Convert.FromBase64String(data);
var dataByte = privateKey.Decrypt(bytesData, false);
return Convert.ToBase64String(dataByte);
}
catch (Exception ex)
{
return "";
}
}

Related

Teams Outgoing WebHook HMAC problem not matching

I created an outgoing Teams webhook.
The callback URL points to a controller on my API, and I would like to use the HMAC provided by the webhook in the request header.
However, when I compute the HMAC with the secret key, I don't obtain the same key as the one in the header.
I tried this code :
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
try
{
if (!this.Request.Headers.TryGetValue("Authorization", out var headerValue))
{
return AuthenticateResult.Fail("Authorization header not found.");
}
var sentKey = headerValue.ToString().Replace("HMAC ", null);
string requestBody = null;
using (var reader = new StreamReader(this.Request.Body, Encoding.UTF8))
{
requestBody = await reader.ReadToEndAsync();
}
if (string.IsNullOrWhiteSpace(requestBody))
{
return AuthenticateResult.Fail("No content to authenticate.");
}
var secretKeyBytes = Encoding.UTF8.GetBytes(this.Options.SecretKey);
using (var hmac = new HMACSHA256(secretKeyBytes))
{
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(requestBody));
var expectedSignature = WebEncoders.Base64UrlEncode(hash);
if (!string.Equals(sentKey, expectedSignature, StringComparison.Ordinal))
{
return AuthenticateResult.Fail("Invalid HMAC signature.");
}
}
var claimsIdentity = new ClaimsIdentity();
var ticket = new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), this.Scheme.Name);
return AuthenticateResult.Success(ticket);
}
catch (Exception ex)
{
return AuthenticateResult.Fail($"{ex.HResult}, {ex.Message}");
}
}

"The SSL connection could not be established, see inner exception." For POST Request(.net 6)

First of all the title of the question may seem like a duplicate. But I tried all possible solutions at SO and nothing works. Most interestingly the same code is working for .net framework-4.x.
The certificate and the key is valid as the same code with same .crt and .key is working.
var certPath = _fileProvider.Combine(_fileProvider.MapPath("~/Plugins/Payments.CityBankApi/"), "othoba.crt");
var keyPath = _fileProvider.Combine(_fileProvider.MapPath("~/Plugins/Payments.CityBankApi/"), "othoba.key");
string certificateText = File.ReadAllText(certPath);
string privateKeyText = File.ReadAllText(keyPath);
ICertificateProvider provider = new CertificateFromFileProvider(certificateText, privateKeyText, true);
var certificate = provider.Certificate;
string accessTokenUrl = string.Empty;
accessTokenUrl = "https://sandbox.thecitybank.com:7788/transaction/token";
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);
handler.ServerCertificateCustomValidationCallback +=(sender, certificate, chain, errors) => {
return true;
};
string json = JsonConvert.SerializeObject(new
{
userName = _cityBankPaymentSettings.UserName,
password = _cityBankPaymentSettings.Password
});
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var client = new HttpClient(handler);
var result = client.PostAsync(accessTokenUrl, httpContent).GetAwaiter().GetResult();
try
{
var pfxPath = _fileProvider.Combine(_fileProvider.MapPath("~/Plugins/Payments.CityBankApi/"), "othoba.pfx");
var certPath = _fileProvider.Combine(_fileProvider.MapPath("~/Plugins/Payments.CityBankApi/SandBoxCrt/"), "othoba.crt");
var keyPath = _fileProvider.Combine(_fileProvider.MapPath("~/Plugins/Payments.CityBankApi/SandBoxCrt/"), "othoba.key");
string tokenUrl = "https://ecomm-webservice.thecitybank.com:7788/transaction/token";
string crtPassword = _cityBankPaymentSettings.CrtPasswordProduction;
if (!_cityBankPaymentSettings.ProductionMode)
{
tokenUrl = "https://sandbox.thecitybank.com:7788/transaction/token";
crtPassword = _cityBankPaymentSettings.CrtPasswordSandBox;
pfxPath = _fileProvider.Combine(_fileProvider.MapPath("~/Plugins/Payments.CityBankApi/SandBoxCrt/"), "createorder.pfx");
certPath = _fileProvider.Combine(_fileProvider.MapPath("~/Plugins/Payments.CityBankApi/SandBoxCrt/"), "createorder.crt");
keyPath = _fileProvider.Combine(_fileProvider.MapPath("~/Plugins/Payments.CityBankApi/SandBoxCrt/"), "createorder.key");
}
var certificate = await LoadPemCertificate(certPath, keyPath);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);
handler.ServerCertificateCustomValidationCallback = (e, r, c, n) => true;
string json = JsonConvert.SerializeObject(new
{
userName = _cityBankPaymentSettings.UserName,
password = _cityBankPaymentSettings.Password
});
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var client = new HttpClient(handler);
var result = await client.PostAsync(tokenUrl, httpContent);
var jsonString = await result.Content.ReadAsStringAsync();
cityBankAccessToken = JsonConvert.DeserializeObject<CityBankAccessTokenResponeModel>(jsonString);
await _logger.InformationAsync("cityBankAccessToken:" + cityBankAccessToken);
}
catch (Exception ex)
{
await _logger.ErrorAsync("CityResponseAccessTokenExc:" + ex.Message, ex);
}
Load Certificate method.
public async Task<X509Certificate2> LoadPemCertificate(string certificatePath, string privateKeyPath)
{
using var publicKey = new X509Certificate2(certificatePath);
var privateKeyText = await File.ReadAllTextAsync(privateKeyPath);
var privateKeyBlocks = privateKeyText.Split("-", StringSplitOptions.RemoveEmptyEntries);
var privateKeyBytes = Convert.FromBase64String(privateKeyBlocks[1]);
using var rsa = RSA.Create();
if (privateKeyBlocks[0] == "BEGIN PRIVATE KEY")
{
rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);
}
else if (privateKeyBlocks[0] == "BEGIN RSA PRIVATE KEY")
{
rsa.ImportRSAPrivateKey(privateKeyBytes, out _);
}
var keyPair = publicKey.CopyWithPrivateKey(rsa);
var Certificate = new X509Certificate2(keyPair.Export(X509ContentType.Pfx));
return Certificate;
}
For Linux(Ubuntu 20.04)
Adding this to the top of /etc/ssl/openssl.cnf:
openssl_conf = default_conf
and this to the bottom of it:
[default_conf]
ssl_conf = ssl_sect
[ssl_sect]
system_default = system_default_sect
[system_default_sect]
MinProtocol = TLSv1.2
CipherString = DEFAULT:#SECLEVEL=1
helpful link

ASP.NET Core ASW S3 - The request signature we calculated does not match the signature you provided

I am getting this error when I try to upload a file to the bucket.
This is my code.
public async Task UploadFileAsync(IFormFile file, string userId)
{
var filePath = Path.GetFullPath(file.FileName);
var bucketName = this.configuration.GetSection("Amazon")["BucketName"];
var accessKey = this.configuration.GetSection("Amazon")["AWSAccessKey"];
var secretKey = this.configuration.GetSection("Amazon")["AWSSecretKey"];
var bucketRegion = RegionEndpoint.EUWest1;
var s3Client = new AmazonS3Client(accessKey, secretKey, bucketRegion);
try
{
var fileTransferUtility =
new TransferUtility(s3Client);
using (var newMemoryStream = new MemoryStream())
{
file.CopyTo(newMemoryStream);
var uploadRequest = new TransferUtilityUploadRequest
{
InputStream = newMemoryStream,
Key = file.FileName,
BucketName = bucketName,
CannedACL = S3CannedACL.PublicRead,
};
await fileTransferUtility.UploadAsync(uploadRequest);
}
await this.filesRepository.AddAsync(new FileBlob
{
Name = file.FileName,
Extension = file.FileName.Split('.')[1],
Size = file.Length,
UserId = userId,
UploadedOn = DateTime.UtcNow,
});
await this.filesRepository.SaveChangesAsync();
}
catch (AmazonS3Exception e)
{
Console.WriteLine(e.Message);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Razor: here
It always says "The request signature we calculated does not match the signature you provided. Check your key and signing method."
Any ideas?
The problem was the mistaken accessKey and secretKey. After I got them right all I had to do is change the CannedACL = S3CannedACL.BucketOwnerFullControl. That solved it for me

How to add a time stamp on digital signature using cmsSigner

I trying to set the time stamp on my signature using SignedCms, I succeeded in returning the timestamptoken of castle bouncy but I need to implement time stamp of the authorization server on my signature.
I've tried adding UnsignedAttributes but to no avail.
This is my signature code:
static public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert, bool detached, Arquivo arquivo)
{
ContentInfo contentInfo = new ContentInfo(msg);
SignedCms signedCms = new SignedCms(contentInfo, detached);
CmsSigner cmsSigner = new CmsSigner(signerCert);
cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly;
NetworkCredential myCred = new NetworkCredential(
"user", "pass");
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri("http://tsatest2.digistamp.com/tsa"), "Basic", myCred);
UserCredentials user = new UserCredentials(myCred);
var d = RequestTimeStampToken("http://tsatest2.digistamp.com/tsa", arquivo.arquivo,null, user);
var x = d.Time;
var chain = new X509Chain();
System.Security.Cryptography.AsnEncodedData timeData = new Pkcs9AttributeObject(Oid.SHA256.OID, d.EncodedToken);
cmsSigner.UnsignedAttributes.Add(timeData);
signedCms.ComputeSignature(cmsSigner, false);
return signedCms.Encode();
}
This is my response from request:
public static TimeStampToken RequestTimeStampToken(string tsaUri, string pathToFile)
{
return RequestTimeStampToken(tsaUri, pathToFile, null, null);
}
public static TimeStampToken RequestTimeStampToken(string tsaUri, string pathToFileToTimestamp, Oid digestType, UserCredentials credentials)
{
if (null == pathToFileToTimestamp)
{
throw new ArgumentNullException("pathToFileToTimestamp");
}
using (FileStream fs = new FileStream(pathToFileToTimestamp, FileMode.Open, FileAccess.Read))
{
return RequestTimeStampToken(tsaUri, fs, digestType, credentials);
}
}
public static TimeStampToken RequestTimeStampToken(string tsaUri, Stream dataToTimestamp, Oid digestType, UserCredentials credentials)
{
if (null == tsaUri)
{
throw new ArgumentNullException("tsaUri");
}
if (null == dataToTimestamp)
{
throw new ArgumentNullException("dataToTimestamp");
}
if (null == digestType)
{
digestType = Oid.SHA512;
}
byte[] digest = DigestUtils.ComputeDigest(dataToTimestamp, digestType);
Request request = new Request(digest, digestType.OID);
return RequestTST(tsaUri, request, credentials);
}
private static TimeStampToken RequestTST(string tsaUri, Request request, UserCredentials credentials = null)
{
byte[] responseBytes = null;
UriBuilder urib = new UriBuilder(tsaUri);
switch (urib.Uri.Scheme)
{
case "http":
case "https":
responseBytes = GetHttpResponse(tsaUri, request.ToByteArray(), credentials);
break;
case "tcp":
responseBytes = GetTcpResponse(tsaUri, request.ToByteArray());
break;
default:
throw new TimeStampException("Unknown protocol.");
}
Response response = new Response(responseBytes);
ValidateResponse(request, response);
return response.TST;
}
public Response(byte[] response)
{
if (null == response)
{
throw new ArgumentNullException("response");
}
this.response = new TimeStampResponse(response);
if (null != this.response.TimeStampToken)
{
Org.BouncyCastle.Asn1.Tsp.TimeStampResp asn1Response = Org.BouncyCastle.Asn1.Tsp.TimeStampResp.GetInstance(Org.BouncyCastle.Asn1.Asn1Sequence.FromByteArray(response));
var derTst = asn1Response.TimeStampToken.GetDerEncoded();
this.TST = new TimeStampToken(derTst);
}
}
I want to include the time stamp in the digital signature and information that it has been validated by an authorization server.
This works for me.
cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.Now));

How to upload memory file to amazon S3?

I want to upload a file from my memoryStream to amazon S3 server.
Here is the code:
public static bool memUploadFile(AmazonS3 client, MemoryStream memFile, string toPath)
{
try
{
Amazon.S3.Transfer.TransferUtility tranUtility = new Amazon.S3.Transfer.TransferUtility(client);
tranUtility.Upload(filePath, toPath.Replace("\\", "/"));
return true;
}
catch (Exception ex)
{
return false;
}
}
Then the error says,
"the best overload method match for 'Amazon.S3.Transfer.TransferUtility.Uplaod(string,string)' has some invalid arguments"
Look at the Upload Method (stream, bucketName, key)
public static bool memUploadFile(AmazonS3 client, MemoryStream memFile, string toPath)
{
try
{
using(Amazon.S3.Transfer.TransferUtility tranUtility =
new Amazon.S3.Transfer.TransferUtility(client))
{
tranUtility.Upload(memFile, toPath.Replace("\\", "/"), <The key under which the Amazon S3 object is stored.>);
return true;
}
}
catch (Exception ex)
{
return false;
}
}
Hamlet is right. This is an example TransferUtilityUploadRequest
[Test]
public void UploadMemoryFile()
{
var config = CloudConfigStorage.GetAdminConfig();
string bucketName = config.BucketName;
string clientAccessKey = config.ClientAccessKey;
string clientSecretKey = config.ClientSecretKey;
string path = Path.GetFullPath(#"dummy.txt");
File.WriteAllText(path, DateTime.Now.ToLongTimeString());
using (var client = AWSClientFactory.CreateAmazonS3Client(clientAccessKey, clientSecretKey))
using (var transferUtility = new TransferUtility(client))
{
var request = new TransferUtilityUploadRequest
{
BucketName = bucketName,
Key = "memory.txt",
InputStream = new MemoryStream(File.ReadAllBytes(path))
};
transferUtility.Upload(request);
}
}

Categories