I want to first encrypt some nodes in Umbraco's content editor. The code below is the one I use for encryption. I use MachineKey.Protect for this.
try
{
MailMessage message1 = new MailMessage();
MailMessage message2 = new MailMessage();
SmtpClient client = new SmtpClient();
string AfsenderEmail = model.Email;
string AfsenderNavn = model.Name;
string toAddress = Umbraco.Content(rootNode.Id).mailDerSendesTil;
message1.From = new MailAddress(toAddress);
message2.From = new MailAddress(toAddress);
message1.Subject = $"{Umbraco.Content(rootNode.Id).overskriftPaaDenMailViFaar}";
message1.Subject = message1.Subject.Replace("AfsenderEmail", AfsenderEmail);
message1.Subject = message1.Subject.Replace("AfsenderNavn", AfsenderNavn);
message1.Body = $"{Umbraco.Content(rootNode.Id).beskedViFaarNaarBeskedenSendes}";
message1.Body = message1.Body.Replace("AfsenderEmail", AfsenderEmail);
message1.Body = message1.Body.Replace("AfsenderNavn", AfsenderNavn);
message1.To.Add(new MailAddress(toAddress));
client.Send(message1);
message2.Subject = $"{Umbraco.Content(rootNode.Id).overskriftPaaMeddelelsenAfsenderenFaar}";
message2.Subject = message2.Subject.Replace("AfsenderEmail", AfsenderEmail);
message2.Subject = message2.Subject.Replace("AfsenderNavn", AfsenderNavn);
message2.Body = $"{Umbraco.Content(rootNode.Id).beskedAfsenderenFaarNaarBeskedenSendes}";
message2.Body = message2.Body.Replace("AfsenderEmail", AfsenderEmail);
message2.Body = message2.Body.Replace("AfsenderNavn", AfsenderNavn);
message2.To.Add(new MailAddress(AfsenderEmail));
client.Send(message2);
var beskederNode = Umbraco.TypedContentAtRoot().FirstOrDefault(x => x.ContentType.Alias.Equals("Besked"));
var encryptName = MachineKey.Protect(Encoding.ASCII.GetBytes(model.Name));
var encryptEmail = MachineKey.Protect(Encoding.ASCII.GetBytes(model.Email));
var encryptMessage = MachineKey.Protect(Encoding.ASCII.GetBytes(model.Message));
string nameEncrypted = Encoding.ASCII.GetString(encryptName);
string emailEncrypted = Encoding.ASCII.GetString(encryptEmail);
string messageEncrypted = Encoding.ASCII.GetString(encryptMessage);
var newContent = contentService.CreateContent(nameEncrypted, beskederNode.Id, "mails");
newContent.SetValue("fra", nameEncrypted);
newContent.SetValue("eMail", emailEncrypted);
newContent.SetValue("besked", messageEncrypted);
var result = contentService.SaveAndPublishWithStatus(newContent);
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch (System.Exception ex)
{
Log.Error("Contact Form Error", ex);
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
This is where I Try to decrypt my code again. It throws an exception (System.Security.Cryptography.CryptographicException: 'Error occurred during a cryptographic operation.') when I call MachineKey.Unprotect(nameDecrypted) and I cannnot find my mistake. I think it maybe has somethimg to do with my Encoding and Decoding?
private void EditorModelEventManager_SendingContentModel(System.Web.Http.Filters.HttpActionExecutedContext sender, EditorModelEventArgs<Umbraco.Web.Models.ContentEditing.ContentItemDisplay> e)
{
var node = e.Model.Properties.ToList();
if (e.Model.IsChildOfListView && e.Model.ContentTypeAlias == "mails")
{
string nameDecrypt = node.Where(x => x.Alias.ToLower() == "fra").Select(x => x.Value).First().ToString();
Byte[] nameDecrypted = Encoding.ASCII.GetBytes(nameDecrypt);
var name = e.Model.Properties.FirstOrDefault(x => x.Alias.ToLower() == "fra");
Byte[] decryptName = MachineKey.Unprotect(nameDecrypted);
string nameReady = Encoding.ASCII.GetString(decryptName);
name.Value = $"{nameReady}";
}
}
}
}
I found a solution. Instead of using Encoding.ASCII.GetString(), I used Convert.FromBase64String().
Related
I am getting AmazonRekognitionException as below when trying to run CompareFacesResponse, I am stuck, what should I do or check?
Amazon.Rekognition.AmazonRekognitionException: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details. ---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown
AWS credentials access key and secret are checked and correct
public static async Task<Tuple<bool, string>> Rekognition_Compare_Faces(string _source, string _target, string _bucketName)
{
const string HOSTNAME = "https://rekognition.ap-southeast-1.amazonaws.com/";
const string ACCESS_KEY = "my_access_key";
const string ACCESS_SECRET = "my_secret_key";
float _similarityThreshold = 70F;
bool _ret = false;
string _confidence = string.Empty;
try
{
AmazonRekognitionConfig _config = new AmazonRekognitionConfig();
_config.ServiceURL = HOSTNAME + _bucketName;
AmazonRekognitionClient _rekognitionClient = new AmazonRekognitionClient(ACCESS_KEY, ACCESS_SECRET, _config);
Amazon.Rekognition.Model.Image _imageSource = new Amazon.Rekognition.Model.Image();
Amazon.Rekognition.Model.Image _imageTarget = new Amazon.Rekognition.Model.Image();
Amazon.Rekognition.Model.S3Object _s3_source = new Amazon.Rekognition.Model.S3Object { Bucket = _bucketName, Name = _source };
Amazon.Rekognition.Model.S3Object _s3_target = new Amazon.Rekognition.Model.S3Object { Bucket = _bucketName, Name = _target };
CompareFacesRequest _compareFacesRequest = new CompareFacesRequest()
{
SourceImage = new Amazon.Rekognition.Model.Image
{
S3Object = new Amazon.Rekognition.Model.S3Object
{
Bucket = HOSTNAME + _bucketName,
Name = _source
}
},
TargetImage = new Amazon.Rekognition.Model.Image
{
S3Object = new Amazon.Rekognition.Model.S3Object
{
Bucket = HOSTNAME + _bucketName,
Name = _target
}
},
SimilarityThreshold = _similarityThreshold
};
// IT THROWN HERE!!
CompareFacesResponse _compareFacesResponse = await _rekognitionClient.CompareFacesAsync(_compareFacesRequest);
// Display results
foreach (CompareFacesMatch match in _compareFacesResponse.FaceMatches)
{
ComparedFace face = match.Face;
BoundingBox position = face.BoundingBox;
_confidence = match.Similarity.ToString(AppSettings.Decimal_Number_Format) + "%";
_ret = true;
}
}
catch (Exception ex) { await ClsMain.SaveLog("AWS.Compare_Faces: " + ex.ToString()); }
finally { }
return await Task.FromResult(new Tuple<bool, string>(_ret, _confidence));
}
has anybody experience on this?
thanks a lot in advance
Regards
Don
I had the same error.
I tried adding RegionEndpoint = RegionEndpoint.EUWest1 to my AmazonRekognitionConfig so it now looks like this:
var config = new AmazonRekognitionConfig
{
ServiceURL = $"https://rekognition.ap-southeast-1.amazonaws.com/{_awsSettings.BucketName}",
RegionEndpoint = RegionEndpoint.EUWest1
};
var client = new AmazonRekognitionClient(_awsSettings.AccessKey, _awsSettings.Secret, config);
This fixed the problem for me.
I'm working on an application where I will have to sign data (a string) which would then be used later in the application. The problem is, each time I try it, the output comes out as an empty string. the code that does the signing is written below...
private string SignData(string dataToSign)
{
log.Info("About to sign data");
string certPath = BankWebUtil.CertPath;
string certPassword = BankWebUtil.CertPassword;
string result = "";
this.log.InfoFormat("The certificate path is : {0}", certPath);
this.log.InfoFormat("The certificate password is : {0}", certPassword);
X509Certificate2 x509Certificate2 = null;
try
{
this.log.Info("Trying to get the certificate object with password");
x509Certificate2 = new X509Certificate2(certPath, certPassword, X509KeyStorageFlags.Exportable);
if (x509Certificate2 == null)
{
throw new Exception("Trying to get the certificate object with password returned null");
}
}
catch
{
this.log.Info("Trying to get the certificate object with only filename");
x509Certificate2 = new X509Certificate2(certPath);
}
finally
{
try
{
if (x509Certificate2 != null)
{
byte[] hash = new SHA256Managed().ComputeHash(new ASCIIEncoding().GetBytes(dataToSign));
byte[] rgbHash = hash;
string str = CryptoConfig.MapNameToOID("SHA256");
if (x509Certificate2.PrivateKey == null)
{
throw new Exception("Certificate PrivateKey is null");
}
var certifiedRSACryptoServiceProvider = x509Certificate2.PrivateKey as RSACryptoServiceProvider;
RSACryptoServiceProvider defaultRSACryptoServiceProvider = new RSACryptoServiceProvider();
defaultRSACryptoServiceProvider.ImportParameters(certifiedRSACryptoServiceProvider.ExportParameters(true));
byte[] inArray = defaultRSACryptoServiceProvider.SignHash(rgbHash, str);
result = Convert.ToBase64String(inArray);
}
else
{
throw new Exception("Certificate object is null");
}
}
catch (Exception ex)
{
this.log.Error(ex.Message,ex);
}
}
return result;
}
This is how I intend to test the code.
var customerRef = "200937943";
var customerName = "KAWEESI MARTIN";
var customerTel = "256774018257";
var customerType = "POSTPAID";
var vendorTranId = "UMEME280918200001";
var VendorCode = "Vendor Code";
var pPassword = "ECO-TEST";
var paymentDate = "28/09/2018";
var paymentType = "2";
var teller = "899";
var tranAmount = "48445.51";
var tranNarration = "BC|UMEME280918200001|200937943|0001";
var tranType = "Cash";
var digitalSignature = SignData(customerRef + customerName + customerTel + customerType + vendorTranId + VendorCode +
pPassword + paymentDate + paymentType + teller + tranAmount + tranNarration + tranType);
the variable "digitalSignature" comes out as an empty string... please help me!
I am using PushSharp 4.0.10.0 library to send the notification on iOS devices but it's not working. I have debugged it and found there is some ApnsConfiguration connection problem.
I am using this code to send the notificaiton:
public IHttpActionResult Notify()
{
HttpResponseMessage response = new HttpResponseMessage();
HttpContent requestContent = Request.Content;
string errorMessage = "Some error occured.please try again later";
HttpStatusCode responseCode = HttpStatusCode.Unauthorized;
string requestParameter = requestContent.ReadAsStringAsync().Result;
string tokan = "";
var r = Request;
var header = r.Headers;
try
{
if (requestParameter != null)
{
PushNotificationModel complaintModel = JsonConvert.DeserializeObject<PushNotificationModel>(requestParameter);
JsonConvert.DeserializeObject<PushNotificationModel>(requestParameter);
var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/User/xyz.pem"));
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
appleCert, "xyz");
// Create a new broker
var push = new ApnsServiceBroker(config);
int DeviceType = 1;
string deviceId = Convert.ToString(complaintModel.deviceToken);
string message = "New notification!!";
Guid complaintId = complaintModel.ComplaintId;
string detail = complaintModel.detail;
try
{
//System.Web.Hosting.HostingEnvironment.MapPath("~/Images/User/")
// var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/User/CTPwd.pem"));
push.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
message = ex.Message;
}
else
{
message = "Not an APNSException";
}
// Mark it as handled
return true;
});
};
try
{
push.OnNotificationSucceeded += (notification) =>
{
message = "New Notification";
};
push.Start();
string appleJsonFormat = "{\"aps\": {\"alert\":" + '"' + message + '"' + ",\"sound\": \"default\"}}";
//string appleJsonFormat = "{\"aps\": {\"alert\": " + "Hello World" + ",\"sound\": \"default\"}}";
push.QueueNotification(new ApnsNotification
{
DeviceToken = deviceId,
Payload = JObject.Parse(appleJsonFormat)
});
push.Stop();
}
catch(Exception ex)
{
}
I have searched on google, but did not find any relevant answer. Is there any syntax problem ?
Thanks in advance.
Please use .P12 file format for push notification happy coding:)
I am trying to create and send an email request in crm2011. I have the email, but when I try to send it I get an exception:
email With Id = 00000000-0000-0000-0000-000000000000 Does Not Exist.
Here's my code:
OrganizationServiceProxy p = new OrganizationServiceProxy(
new Uri(""), null, ccr, null);
WhoAmIRequest systemUserRequest = new WhoAmIRequest();
WhoAmIResponse systemUserResponse = (WhoAmIResponse)p.Execute(systemUserRequest);
Guid _userId = systemUserResponse.UserId;
Entity email = new Entity("email");
email.Attributes.Add("subject", "test");
Entity[] To = new Entity[1];
To[0] = new Entity("activityparty");
To[0]["partyid"] = new EntityReference("contact", new Guid("some guidid"));
email.Attributes.Add("to", To);
Entity[] From = new Entity[1];
From[0] = new Entity("activityparty");
From[0]["partyid"] = new EntityReference("systemuser", _userId);
email.Attributes.Add("from", From);
try
{
Guid emailGuid = p.Create(email);
}
catch (Exception e)
{
Console.WriteLine("error " + e.Message);
Console.ReadLine();
}
OrganizationRequest request = new OrganizationRequest() { RequestName = "SendEmail" };
request["EmailId"] = email.Id;
request["TrackingToken"] = "";
request["IssueSend"] = true;
// THE CODE FAILS HERE:
OrganizationResponse rsp = p.Execute(request);
The main error is in this line:
request["EmailId"] = email.Id;
when you create the email, the Id property is not filled inside the record but the Guid is inside the variable emailGuid
I suggest to change the code in this way :
try
{
Guid emailGuid = p.Create(email);
OrganizationRequest request = new OrganizationRequest() { RequestName = "SendEmail" };
request["EmailId"] = emailGuid; // now is the right variable
request["TrackingToken"] = "";
request["IssueSend"] = true;
OrganizationResponse rsp = p.Execute(request);
}
catch (Exception e)
{
Console.WriteLine("error " + e.Message);
Console.ReadLine();
}
I'm trying to send HTML e-mails with attached Excel filenames. It all worked well until I neded to send messages whose attachment name contains accented letters :-( Every workaround I've tried failed miserably.
Original code:
var attachment = new Attachment(
new MemoryStream(excelFileContents),
"simplefilename.xls");
This one works fine.
However if I replace "simplefilename.xls" by "échec.xls", the attachment is garbaged (name and contents).
I tried these, to no avail:
var attachment = new Attachment(
new MemoryStream(excelFileContents),
new System.Net.Mime.ContentType("application/vnd.ms-excel"));
attachment.Name = "échec.xls";
The last one is even worse: SmtpClient.Send() throws an exception, complaining about the é in the filename:
var attachment = new Attachment(
new MemoryStream(excelFileContents),
new System.Net.Mime.ContentType("application/vnd.ms-excel"));
attachment.ContentDisposition.FileName = "échec.xls";
I've been banging my head on this one for way too long. Any lights warmly welcomed!
I finally came across an answer that worked.
http://social.msdn.microsoft.com/Forums/en-US/dotnetframeworkde/thread/b6c764f7-4697-4394-b45f-128a24306d55
The content is in German except for the post by Marcel Roma. I put in his code into my application. I was able to send out pdf with accents and we were to see the attachment instead of garbage.
So here it is:
public class AttachmentHelper
{
public static System.Net.Mail.Attachment CreateAttachment(string attachmentFile, string displayName, TransferEncoding transferEncoding)
{
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(attachmentFile);
attachment.TransferEncoding = transferEncoding;
string tranferEncodingMarker = String.Empty;
string encodingMarker = String.Empty;
int maxChunkLength = 0;
switch (transferEncoding)
{
case TransferEncoding.Base64:
tranferEncodingMarker = "B";
encodingMarker = "UTF-8";
maxChunkLength = 30;
break;
case TransferEncoding.QuotedPrintable:
tranferEncodingMarker = "Q";
encodingMarker = "ISO-8859-1";
maxChunkLength = 76;
break;
default:
throw (new ArgumentException(String.Format("The specified TransferEncoding is not supported: {0}", transferEncoding, "transferEncoding")));
}
attachment.NameEncoding = Encoding.GetEncoding(encodingMarker);
string encodingtoken = String.Format("=?{0}?{1}?", encodingMarker, tranferEncodingMarker);
string softbreak = "?=";
string encodedAttachmentName = encodingtoken;
if (attachment.TransferEncoding == TransferEncoding.QuotedPrintable)
encodedAttachmentName = HttpUtility.UrlEncode(displayName, Encoding.Default).Replace("+", " ").Replace("%", "=");
else
encodedAttachmentName = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(displayName));
encodedAttachmentName = SplitEncodedAttachmentName(encodingtoken, softbreak, maxChunkLength, encodedAttachmentName);
attachment.Name = encodedAttachmentName;
return attachment;
}
private static string SplitEncodedAttachmentName(string encodingtoken, string softbreak, int maxChunkLength, string encoded)
{
int splitLength = maxChunkLength - encodingtoken.Length - (softbreak.Length * 2);
var parts = SplitByLength(encoded, splitLength);
string encodedAttachmentName = encodingtoken;
foreach (var part in parts)
encodedAttachmentName += part + softbreak + encodingtoken;
encodedAttachmentName = encodedAttachmentName.Remove(encodedAttachmentName.Length - encodingtoken.Length, encodingtoken.Length);
return encodedAttachmentName;
}
private static IEnumerable<string> SplitByLength(string stringToSplit, int length)
{
while (stringToSplit.Length > length)
{
yield return stringToSplit.Substring(0, length);
stringToSplit = stringToSplit.Substring(length);
}
if (stringToSplit.Length > 0) yield return stringToSplit;
}
}
Use it in the following way:
static void Main(string[] args)
{
string smtpServer = String.Empty;
string userName = String.Empty;
string password = String.Empty;
string attachmentFilePath = String.Empty;
string displayName = String.Empty;
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpServer);
client.Credentials = new System.Net.NetworkCredential(userName, password);
var msg = new System.Net.Mail.MailMessage(fromAddress, toAddress, "Subject", "Body");
System.Net.Mail.Attachment attachment =
AttachmentHelper.CreateAttachment(attachmentFilePath, displayName, TransferEncoding.Base64);
msg.Attachments.Add(attachment);
client.Send(msg);
}
You need to use the Quoted-Printable format for the attachment name:
C#: Class for decoding Quoted-Printable encoding?
http://www.codeproject.com/KB/security/TextCoDec.aspx