Skip to content
Snippets Groups Projects
Commit 889ad40f authored by Klaus Fischer's avatar Klaus Fischer
Browse files

Cleaned encryption project

parent d961f1ad
No related branches found
No related tags found
1 merge request!3Feature/440 mvp net sdk part 1
...@@ -5,37 +5,32 @@ using IdentityModel.Jwk; ...@@ -5,37 +5,32 @@ using IdentityModel.Jwk;
namespace FitConnect.Encryption; namespace FitConnect.Encryption;
public class AspNetCoreEncryptor : IEncryptor { public class AspNetCoreEncryptor : IEncryptor {
public string Encrypt(string plain, string key, out object? passOver) { private readonly RSAEncryptionPadding _rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA256;
var encryptionKey = new JsonWebKey(key);
var rsa = encryptionKey.ToRsaPublicKey();
public string Encrypt(string plain, string key, out object? passOver) {
var rsa = new JsonWebKey(key).ToRsaKey();
passOver = rsa; passOver = rsa;
var cipher = rsa.Encrypt(Encoding.UTF8.GetBytes(plain), RSAEncryptionPadding.OaepSHA512); var cipher = rsa.Encrypt(Encoding.UTF8.GetBytes(plain), _rsaEncryptionPadding);
return Convert.ToBase64String(cipher); return Convert.ToBase64String(cipher);
} }
public string Decrypt(string cipher, string key, object? passOver = null) { public string Decrypt(string cipher, string key, object? passOver = null) {
var encryptionKey = new JsonWebKey(key); var rsa = new JsonWebKey(key).ToRsaKey();
var rsa = encryptionKey.ToRsaPrivateKey();
var plain = rsa.Decrypt(Convert.FromBase64String(cipher), RSAEncryptionPadding.OaepSHA512); var plain = rsa.Decrypt(Convert.FromBase64String(cipher), _rsaEncryptionPadding);
return Encoding.UTF8.GetString(plain); return Encoding.UTF8.GetString(plain);
} }
public byte[] Encrypt(byte[] plain, string key, out object? passOver) { public byte[] Encrypt(byte[] plain, string key, out object? passOver) {
var encryptionKey = new JsonWebKey(key); var rsa = new JsonWebKey(key).ToRsaKey();
var rsa = encryptionKey.ToRsaPublicKey();
passOver = rsa; passOver = rsa;
return rsa.Encrypt(plain, RSAEncryptionPadding.OaepSHA512); return rsa.Encrypt(plain, _rsaEncryptionPadding);
} }
public byte[] Decrypt(byte[] cipher, string key, object? passOver = null) { public byte[] Decrypt(byte[] cipher, string key, object? passOver = null) {
var encryptionKey = new JsonWebKey(key); var rsa = new JsonWebKey(key).ToRsaKey();
var rsa = encryptionKey.ToRsaPrivateKey(); return rsa.Decrypt(cipher, _rsaEncryptionPadding);
return rsa.Decrypt(cipher, RSAEncryptionPadding.OaepSHA512);
} }
} }
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace FitConnect.Encryption; namespace FitConnect.Encryption;
...@@ -63,6 +60,7 @@ public class FitEncryption { ...@@ -63,6 +60,7 @@ public class FitEncryption {
return _encryptor.Encrypt(plain, PrivateKeyDecryption, out var _); return _encryptor.Encrypt(plain, PrivateKeyDecryption, out var _);
} }
public byte[] Encrypt(byte[] plain) { public byte[] Encrypt(byte[] plain) {
if (PrivateKeyDecryption == null) { if (PrivateKeyDecryption == null) {
throw new InvalidOperationException("PrivateKey is not provided"); throw new InvalidOperationException("PrivateKey is not provided");
......
...@@ -14,7 +14,6 @@ public interface IEncryption { ...@@ -14,7 +14,6 @@ public interface IEncryption {
/// <exception cref="Exception"></exception> /// <exception cref="Exception"></exception>
void ImportCertificate(string certificatePath, string password); void ImportCertificate(string certificatePath, string password);
byte[] DecryptData(byte[] data);
string DecryptData(string data); string DecryptData(string data);
byte[] ExportPublicKey(); byte[] ExportPublicKey();
......
...@@ -6,16 +6,7 @@ using IdentityModel.Jwk; ...@@ -6,16 +6,7 @@ using IdentityModel.Jwk;
namespace FitConnect.Encryption; namespace FitConnect.Encryption;
public static class JsonWebKeyExtension { public static class JsonWebKeyExtension {
public static RSA ToRsaPublicKey(this JsonWebKey jsonWebKey) { public static RSA ToRsaKey(this JsonWebKey jsonWebKey) {
var rsa = RSA.Create();
rsa.ImportParameters(new RSAParameters {
Modulus = Base64Url.Decode(jsonWebKey.N),
Exponent = Base64Url.Decode(jsonWebKey.E)
});
return rsa;
}
public static RSA ToRsaPrivateKey(this JsonWebKey jsonWebKey) {
var rsa = RSA.Create(); var rsa = RSA.Create();
rsa.ImportParameters(new RSAParameters { rsa.ImportParameters(new RSAParameters {
Modulus = Base64Url.Decode(jsonWebKey.N), Modulus = Base64Url.Decode(jsonWebKey.N),
...@@ -25,8 +16,9 @@ public static class JsonWebKeyExtension { ...@@ -25,8 +16,9 @@ public static class JsonWebKeyExtension {
Q = Base64Url.Decode(jsonWebKey.Q), Q = Base64Url.Decode(jsonWebKey.Q),
DP = Base64Url.Decode(jsonWebKey.DP), DP = Base64Url.Decode(jsonWebKey.DP),
DQ = Base64Url.Decode(jsonWebKey.DQ), DQ = Base64Url.Decode(jsonWebKey.DQ),
InverseQ = Base64Url.Decode(jsonWebKey.QI) InverseQ = Base64Url.Decode(jsonWebKey.QI),
}); });
// = "RSA-OAEP-256";
return rsa; return rsa;
} }
} }
...@@ -26,7 +26,6 @@ public class SenderEncryptionWithSelfSignedCertificateTest { ...@@ -26,7 +26,6 @@ public class SenderEncryptionWithSelfSignedCertificateTest {
[OneTimeSetUp] [OneTimeSetUp]
public void OneTimeSetup() { public void OneTimeSetup() {
} }
[OneTimeTearDown] [OneTimeTearDown]
...@@ -45,16 +44,13 @@ public class SenderEncryptionWithSelfSignedCertificateTest { ...@@ -45,16 +44,13 @@ public class SenderEncryptionWithSelfSignedCertificateTest {
_sender = Sender.Create( _sender = Sender.Create(
FitConnectEndpoints.Create(FitConnectEndpoints.EndpointType.Development), FitConnectEndpoints.Create(FitConnectEndpoints.EndpointType.Development),
_logger); _logger);
var certificate = new X509Certificate2("./certificate.pfx");
_sender.Encryption.ImportCertificate(certificate);
} }
[Test] [Test]
[Order(10)] [Order(10)]
public void CryptWithOutPublicKeyImport() { public void CryptWithOutPublicKeyImport() {
cypher = _sender.Encryption.EncryptData(Encoding.UTF8.GetBytes(ToEncrypt)); cypher = _sender.Encryption.Encrypt(Encoding.UTF8.GetBytes(ToEncrypt));
_logger.LogInformation("Cypher: {}", Convert.ToBase64String(cypher)); _logger.LogInformation("Cypher: {}", Convert.ToBase64String(cypher));
} }
...@@ -62,14 +58,10 @@ public class SenderEncryptionWithSelfSignedCertificateTest { ...@@ -62,14 +58,10 @@ public class SenderEncryptionWithSelfSignedCertificateTest {
[Test] [Test]
[Order(20)] [Order(20)]
public void Decrypt_ResultShouldMatchToEncrypt() { public void Decrypt_ResultShouldMatchToEncrypt() {
var result = _sender.Encryption.DecryptData(cypher!); var result = _sender.Encryption.Decrypt(cypher!);
Encoding.UTF8.GetString(result).Should().Be(ToEncrypt); Encoding.UTF8.GetString(result).Should().Be(ToEncrypt);
} }
[Test]
public void ExportPrivateKey() {
var privateKey = _sender.Encryption.ExportPrivateKey();
_logger.LogInformation("Private key: {}", Convert.ToBase64String(privateKey));
}
} }
...@@ -32,7 +32,7 @@ public class SenderEncryptionWithoutCertificateTest { ...@@ -32,7 +32,7 @@ public class SenderEncryptionWithoutCertificateTest {
[Test] [Test]
[Order(10)] [Order(10)]
public void EncryptData_ShouldNotThrowAnyException() { public void EncryptData_ShouldNotThrowAnyException() {
var cypher = _sender.Encryption.EncryptData(Encoding.UTF8.GetBytes(ToEncrypt)); var cypher = _sender.Encryption.Encrypt(Encoding.UTF8.GetBytes(ToEncrypt));
_cypherText = Convert.ToBase64String(cypher); _cypherText = Convert.ToBase64String(cypher);
_logger.LogInformation("Cypher: {}", _cypherText); _logger.LogInformation("Cypher: {}", _cypherText);
...@@ -43,14 +43,9 @@ public class SenderEncryptionWithoutCertificateTest { ...@@ -43,14 +43,9 @@ public class SenderEncryptionWithoutCertificateTest {
[Order(20)] [Order(20)]
public void DecryptData_ShouldMatchToEncrypt() { public void DecryptData_ShouldMatchToEncrypt() {
var cypher = Convert.FromBase64String(_cypherText); var cypher = Convert.FromBase64String(_cypherText);
var plain = _sender.Encryption.DecryptData(cypher); var plain = _sender.Encryption.Decrypt(cypher);
Encoding.UTF8.GetString(plain).Should().Be(ToEncrypt); Encoding.UTF8.GetString(plain).Should().Be(ToEncrypt);
} }
[Test]
public void ExportPrivateKey_ShouldNotThrowAnyException() {
var privateKey = _sender.Encryption.ExportPrivateKey();
_logger.LogInformation("Private key: {}", Convert.ToBase64String(privateKey));
}
} }
...@@ -8,7 +8,7 @@ using Microsoft.Extensions.Logging; ...@@ -8,7 +8,7 @@ using Microsoft.Extensions.Logging;
namespace FitConnect.BaseClasses; namespace FitConnect.BaseClasses;
public abstract class FunctionalBaseClass { public abstract class FunctionalBaseClass {
public readonly IEncryption Encryption; public readonly FitEncryption Encryption;
protected readonly ILogger? Logger; protected readonly ILogger? Logger;
// protected readonly FitConnectApiService ApiService; // protected readonly FitConnectApiService ApiService;
...@@ -41,7 +41,6 @@ public abstract class FunctionalBaseClass { ...@@ -41,7 +41,6 @@ public abstract class FunctionalBaseClass {
RouteService = routeService; RouteService = routeService;
} }
public X509Certificate2 Certificate { get; }
internal Client Owner { get; set; } internal Client Owner { get; set; }
......
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using FitConnect.Encryption;
using FitConnect.Interfaces; using FitConnect.Interfaces;
using FitConnect.Models; using FitConnect.Models;
using FitConnect.Services; using FitConnect.Services;
...@@ -17,6 +18,7 @@ public class FluentSubscriber : Subscriber, ...@@ -17,6 +18,7 @@ public class FluentSubscriber : Subscriber,
IFluentSubscriberWithSubmission { IFluentSubscriberWithSubmission {
private readonly string _privateKeyDecryption; private readonly string _privateKeyDecryption;
private OAuthAccessToken? _token; private OAuthAccessToken? _token;
private FitEncryption _encryption;
public FluentSubscriber(FitConnectEndpoints endpoints, public FluentSubscriber(FitConnectEndpoints endpoints,
...@@ -59,12 +61,12 @@ public class FluentSubscriber : Subscriber, ...@@ -59,12 +61,12 @@ public class FluentSubscriber : Subscriber,
Authenticate(Owner.ClientId, Owner.ClientSecret); Authenticate(Owner.ClientId, Owner.ClientSecret);
var submission = (Submission)SubmissionService.GetSubmission(submissionId); var submission = (Submission)SubmissionService.GetSubmission(submissionId);
var metaDataString = Encryption.DecryptData(submission.EncryptedMetadata); var metaDataString = Encryption.Decrypt(submission.EncryptedMetadata);
if (metaDataString != null) if (metaDataString != null)
submission.Metadata = submission.Metadata =
JsonConvert.DeserializeObject<Metadata>(metaDataString); JsonConvert.DeserializeObject<Metadata>(metaDataString);
var dataString = Encryption.DecryptData(submission.EncryptedData); var dataString = Encryption.Decrypt(submission.EncryptedData);
if (dataString != null) if (dataString != null)
submission.Data = submission.Data =
JsonConvert.DeserializeObject<Data>(dataString); JsonConvert.DeserializeObject<Data>(dataString);
...@@ -88,7 +90,7 @@ public class FluentSubscriber : Subscriber, ...@@ -88,7 +90,7 @@ public class FluentSubscriber : Subscriber,
foreach (var id in Submission!.Attachments.Select(a => a.Id)) { foreach (var id in Submission!.Attachments.Select(a => a.Id)) {
var encryptedAttachment = SubmissionService.GetAttachment(Submission.Id, id); var encryptedAttachment = SubmissionService.GetAttachment(Submission.Id, id);
var content = Encryption.DecryptData(Convert.FromBase64String(encryptedAttachment)); var content = _encryption.Decrypt(Convert.FromBase64String(encryptedAttachment));
// TODO where do I get the hash from the server to verify the attachment? // TODO where do I get the hash from the server to verify the attachment?
var hash = MD5.Create(HashAlgorithmName.SHA512.ToString())?.ComputeHash(content) ?? var hash = MD5.Create(HashAlgorithmName.SHA512.ToString())?.ComputeHash(content) ??
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment