Example encryption and decryption

using System; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using Landingpage.Models.XML; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Encodings; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.OpenSsl; namespace Landingpage.Models { public class ExampleUseage { public bool ReiceverRole_JustReceivedAPayload_NowCheckEncryption_Valid( string payloadFileXml, // should contain contents like https://edi4steel-eu.atlassian.net/wiki/spaces/EDI4STEEL/pages/884762/Standardized+order string payloadMetadata // should contain contents like https://edi4steel-eu.atlassian.net/wiki/spaces/EDI4STEEL/pages/950303/Example+payload+metadata+API ) { // convert payloadMetadata (xml) to an object, change below object to actual type SubmitMessage payloadMetadataObject = payloadMetadata; var algorithm = payloadMetadataObject.Payloads.Payload.PayloadProperties.FirstOrDefault(x => x.Name == "HashAlgorithm"); var hash = payloadMetadataObject.Payloads.Payload.PayloadProperties.FirstOrDefault(x => x.Name == "Hash"); var isencrypted = payloadMetadataObject.Payloads.Payload.PayloadProperties.FirstOrDefault(x => x.Name == "HashIsEncrypted"); if (isencrypted.Value == "True") { // url parameter is edi4steel.eu when sender uses edi4steel API, if they use // their own accesspoint or saas accesspoint the other end must have provided the url // to you and you must have stored it somewhere.. var decryptedHash = AccesspointEncryptionHelper.Descrypt("https://edi4steel.eu", hash.Value); string hashToCheck = AccesspointEncryptionHelper.Sha256_hash(payloadFileXml); if (decryptedHash == hashToCheck) return true; return false; // hashes not equal } return true; // not hashed, fine } public string SenderRole_HashWithPrivateKey_BeforeSend( string payloadXml // should contain contents like https://edi4steel-eu.atlassian.net/wiki/spaces/EDI4STEEL/pages/884762/Standardized+order ) { // this method is only required if you have your own accesspoint or saas accesspoint // the api version does this for you! // this is a private key generated by Lets Encrypt (auto generated) // and is done so (and others must also do so) with an RSA algorithm, not Eliptic cure etc! string privateKey = File.ReadAllText(@"D:\Certificates\domain-key.pem"); // the returned value should be stored value of hash in DeliverMessage return AccesspointEncryptionHelper.Encrypt(privateKey, AccesspointEncryptionHelper.Sha256_hash(payloadXml)); } } /// <summary> /// Helper method for encryption /// </summary> public static class AccesspointEncryptionHelper { /// <summary> /// The default algorithm to use /// </summary> public static string DefaultHashAlgorithm = "SHA256"; /// <summary> /// Encrypt some plain text /// </summary> /// <param name="privateKeyPemFormat"></param> /// <param name="plaingTextInput"></param> /// <returns></returns> public static string Encrypt(string privateKeyPemFormat, string plaingTextInput) { return RsaEncryptWithPrivate(plaingTextInput, privateKeyPemFormat); } /// <summary> /// Decrypt some encrypted text /// </summary> /// <param name="urlForCertificatePublicKey"></param> /// <param name="encryptedText"></param> /// <returns></returns> public static string Descrypt(string urlForCertificatePublicKey, string encryptedText) { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlForCertificatePublicKey); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); response.Close(); System.Security.Cryptography.X509Certificates.X509Certificate cert = request.ServicePoint.Certificate; Org.BouncyCastle.X509.X509Certificate convertedCert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(cert.GetRawCertData()); AsymmetricKeyParameter key = convertedCert.GetPublicKey(); return RsaDecryptWithPublic(encryptedText, key); } /// <summary> /// Has some vlaue /// </summary> /// <param name="value"></param> /// <returns></returns> public static string Sha256_hash(string value) { StringBuilder Sb = new StringBuilder(); using (SHA256 hash = SHA256Managed.Create()) { Encoding enc = Encoding.UTF8; byte[] result = hash.ComputeHash(enc.GetBytes(value)); foreach (byte b in result) Sb.Append(b.ToString("x2")); } return Sb.ToString(); } private static string RsaEncryptWithPrivate(string clearText, string privateKey) { var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText); var encryptEngine = new Pkcs1Encoding(new RsaEngine()); using (var txtreader = new StringReader(privateKey)) { var keyPair = (AsymmetricCipherKeyPair)new PemReader(txtreader).ReadObject(); encryptEngine.Init(true, keyPair.Private); } var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length)); return encrypted; } private static string RsaDecryptWithPublic(string base64Input, AsymmetricKeyParameter publicKey) { var bytesToDecrypt = Convert.FromBase64String(base64Input); var decryptEngine = new Pkcs1Encoding(new RsaEngine()); var keyParameter = publicKey; decryptEngine.Init(false, keyParameter); var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length)); return decrypted; } } }

 

© 2020 - EDI4STEEL