I am trying to decode and extract octet string from the extension of X509Certificate, but I did not get any valid string - x509certificate

I have been trying to decode the octet string as per steps mentioned in
https://developer.apple.com/documentation/devicecheck/validating_apps_that_connect_to_your_server?language=objc
Here is what I have tried:
X509Certificate cert1 = getParentCertificate(new String(decodedCredCert));
System.out.println(cert1);
cert1.checkValidity(); // verify against apple app attest root ca
byte[] ext = cert1.getExtensionValue("1.2.840.113635.100.8.2");
ASN1InputStream bIn = new ASN1InputStream(ext);
ASN1Primitive obj = bIn.readObject();
ASN1OctetString string = (ASN1OctetString) obj;
byte[] octs = string.getOctets();
ASN1InputStream dIn = new ASN1InputStream(octs);
String octetString = ASN1Dump.dumpAsString(dIn.readObject());
I got the output as: "[[1]#8333585e692916d8cbcdce3c6aa2bd71617d54fed758957cfd6b50a2093fd506]"

For Ios AppAttestation, follow as below to get the extension value and it's corresponding octet string. As mentioned in that page,
Obtain the value of the credCert extension with OID
1.2.840.113635.100.8.2, which is a DER-encoded ASN.1 sequence. Decode the sequence and extract the single octet string that it contains.
Here is the sample code:
byte[] oidValue = credCert.getExtensionValue(ooid);
DEROctetString envelope = (DEROctetString) new ASN1InputStream(oidValue).readObject();
DLSequence sequence = (DLSequence) new ASN1InputStream(envelope.getOctetStream()).readObject();
DLTaggedObject taggedObject = (DLTaggedObject) sequence.getObjectAt(0);
DEROctetString taggedObjectOctet = (DEROctetString) taggedObject.getObject();
log.debug("Octet String : {}", taggedObjectOctet.getOctets());

"Octet string" is just a spec phrase that modern languages call "byte array". You've extracted the value as of octs, and should compare that value to whatever nonce you're supposed to compare it against.

Related

How to get Binary data with javascript using FileReader api with correct encoding

I got a mp4 data using FileReader api, but I have a problem at encoding!
With this function,
var reader = new FileReader();
var blob = new Blob([this.response], {type : "video/mp4"});
reader.onload= function (evt) {
mp4text = evt.target.result;
mp4text = mp4text.toString()
//mp4text = mp4text.slice(22);
//mp4text = CryptoJS.AES.encrypt(mp4text, "test");
//mp4text = window.atob(mp4text);
var myBlob = new Blob([evt.target.result], {type : "video/mp4"});//NOT SAME contrast to blob!
var downloadUrl = URL.createObjectURL(myBlob);
document.getElementById('myVideo').src = downloadUrl;
}
reader.readAsBinaryString(blob);
I thought myBlob has same filedata as blob but some data changed! With more detail, Many of character are same but some hex code is different. How can I solve this problem?
Strings in JavaScript cannot represent arbitrary binary data, so doing readAsBinaryString may not be what you think.
What readAsBinaryString does is for each source byte it gives you a destination character(I don't which character encoding it uses off the top of my head).
So if you have a utf-8 character say ✔, then readAsBinaryString will give you â since that character is tree bytes long %E2%9C%94.
If you try to turn this back to binary/blob the string â is treated as utf-8 which is not 3 bytes but 7(%C3%A2%C5%93%E2%80%9D)
My suggestion would be to use readAsArrayBuffer, I'm sure CryptoJS supports arraybuffers.

sending email with utf-8 characters in the subject

I'm using ActionMailer.net to send email.
No matter what I do I can not get the subject in utf-8, it displays just question marks. Body shows in utf-8.
This is my last attempt to solve the issue:
public EmailResult AccountConfirmationEmail(AccountConfirmationModel acm)
{
MailAttributes.MessageEncoding = Encoding.UTF8;
MailAttributes.To.Add(new MailAddress(acm.BizUserId));
MailAttributes.From = new MailAddress("service#abc.co.il");
UTF8Encoding utf8 = new UTF8Encoding();
string unicodeString = "אישור הרשמה לאתר";
byte[] encodedBytes = utf8.GetBytes(unicodeString);
MailAttributes.Subject = Encoding.UTF8.GetString(encodedBytes, 0, encodedBytes.Length);
return Email("Account/AccountConfirmationEmail", acm);
}
to no avail.
Does anyone know how to do this?

Split the string of a row of datatable in asp.net

I am using asp.net. I am trying to split the data which is in datatable. I have a code sample like this:
{ dt=objErrorLoggingDataAccess.GetErrorDetails(errorID);
string[] stringSeparators = new string[] { "Message" };
string error = dt.Rows[0]["Message"].ToString();
string[] test = error.Split(stringSeparators, StringSplitOptions.None);
string PageName = test[0].ToString();
PageNameLabel.Text = PageName;
stringSeparators=new string[] {HttpContext.Current.Request.Url.ToString()};
error = dt.Rows[0]["Message"].ToString();
test = error.Split(stringSeparators, StringSplitOptions.None);
string Message = test[0].ToString();
MessageLabel.Text = Message;}
in the datatable following data is there:
{....ID.......Message.......................................................................................................................
....1........http://localhost:10489/images/CategoryIcon/images Message : File does not exist. UserName: naresh#naresh.com
....2........http://localhost:10489/images/CategoryIcon/images Message : File does not exist. UserName: iswar#iswar.com}
My problem is: how can I split the Message and store in the label? I want
{http://localhost:10489/images/CategoryIcon/images}
separately and UserName separately and the message separately. How can I do that? By executing the above code I am able to split
{ http://localhost:10489/images/CategoryIcon/images
}
only. How can I split the Message column and store in pageLabel, MessageLabel, UserNamelabel?
I would use a regular expression in this case. Because only by splitting this string looks a little bit to inflexible to me.
I tested your data example against this quick and dirty RegEx:
(?<id>\d+)\.*(?<url>\w+:\/\/[\w#][\w.:#]+\/?[\w\.?=%&=\-#/$,]*)\s*Message\s*:\s*(?<message>.*)UserName:\s*(?<username>([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3}))
It supports valid URLs and EMail patterns.
Regex regex = new Regex(
"(?<id>\\d+)\\.*(?<url>\\w+:\\/\\/[\\w#][\\w.:#]+\\/?[\\w\\.?"+
"=%&=\\-#/$,]*)\\s*Message\\s*:\\s*(?<message>.*)UserName:\\s"+
"*(?<username>([a-zA-Z0-9_\\-\\.]+)#((\\[[0-9]{1,3}\\.[0-9]{1"+
",3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|"+
"[0-9]{1,3}))",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
// Capture the first Match, if any, in the InputText
Match m = regex.Match(InputText);
// Capture all Matches in the InputText
MatchCollection ms = regex.Matches(InputText);
// Test to see if there is a match in the InputText
bool IsMatch = regex.IsMatch(InputText);
// Get the names of all the named capture groups
// I included your fields as groups: id, url, message and username
string[] GroupNames = regex.GetGroupNames();
I don't know how often you need to call this code. Maybe you get in performance troubles if you have too much data. This regex is q&d - please adjust it to your needs.

Using as3Crypto to encrypt/decrypt without ampersands

I was using as3Crypto with no probs
http://www.zedia.net/2009/as3crypto-and-php-what-a-fun-ride/
but then I saw some special characters and I realised I could encounter ampersands.
Which is a pain because they will be inserted into a query string.
Is there a way to ensure the as3Crypto encryption does not produce ampersands?
public function encrypt(txt:String = ''):String
{
var data:ByteArray = Hex.toArray(Hex.fromString(txt));
var pad:IPad = new PKCS5;
var mode:ICipher = Crypto.getCipher(type, key, pad);
pad.setBlockSize(mode.getBlockSize());
mode.encrypt(data);
return ''+Base64.encodeByteArray(data);
}
Assuming a standard base64 implementation, Base64.encodeByteArray(data); will not produce ampersands.

What is proper encoding for converting a string to a byte array

I am having some sort of problem with encoding in my ASP.NET HTTPHandler, which uploads a file. The file content is passed in a hidden form variable from a ColdFusion web page which is using something called "ToBase64".
In ColdFusion, the code used to place the file content into a form is as follows:
<cffile action="readBinary" file="#FileName#" variable="objBinaryData">
<cfset b64file = #toBase64(objBinaryData)#>
<form name="sendToHandler"
action="http://myserver/mysite/UploadHandler.ashx" method="post">
<cfoutput>
<input type="hidden" name="objBinaryData" value="#b64file#" />
When my UploadHandler.ashx is posted, I am getting a string out of the form as follows:
string fileContent = context.Request.Form["objBinaryData"];
Next, I am converting the string to a byte array as follows:
byte[] binData = StringToByteArray(fileContent, EncodingType.ASCII);
Here is the function I'm using to convert the string:
public static byte[] StringToByteArray(string str, EncodingType encodingType)
{
System.Text.Encoding encoding = null;
switch (encodingType)
{
case EncodingType.ASCII:
encoding = new System.Text.ASCIIEncoding();
break;
case EncodingType.Unicode:
encoding = new System.Text.UnicodeEncoding();
break;
case EncodingType.UTF7:
encoding = new System.Text.UTF7Encoding();
break;
case EncodingType.UTF8:
encoding = new System.Text.UTF8Encoding();
break;
}
return encoding.GetBytes(str);
}
public enum EncodingType
{
ASCII,
Unicode,
UTF7,
UTF8
}
It's obvious to me that calling the above function with EncodingType.ASCII is wrong but I am very confused about what would be correct? What is the proper "match" between "Base64" sent from ColdFusion and the way the string should be encoded in .Net?
Please note that all the code "works" but the subsequent retrieval of a file shows it to be scrambled and I'm pretty sure I have the wrong encoding here.
EDIT-update:
I added the enum code previously omitted. I've tried all of these Encoding Types; they all result in "garbage". That is: I have tried each of these variations:
byte[] binData = StringToByteArray(fileContent, EncodingType.ASCII);
byte[] binData = StringToByteArray(fileContent, EncodingType.Unicode);
byte[] binData = StringToByteArray(fileContent, EncodingType.UTF7);
byte[] binData = StringToByteArray(fileContent, EncodingType.UTF8);
None of these work properly. As I read your suggested function, it should be Unicode. Note that I want to return a byte array not a converted string. Still very confused.
ANSWER:
I simply eliminated the enum and the function I wrote called StringToByteArray. Instead I coded the following:
byte[] binData = Convert.FromBase64String(fileContent);
Look at the Convert.FromBase64String() function
Base64 is an encoding scheme that enables you to represent binary data as a series of ASCII characters so that it can be included in text files and e-mail messages in which raw binary data is unacceptable. The below examples show encoding and decoding of unicode strings. Let me know if this is what you wanted,if not I can refind this further for you.
//Encoding
public static string StringToBase64 (string src) {
// Get's byte representation unicode string
byte[] b = Encoding.Unicode.GetBytes(src);
// Returns Base64-encoded string
return Convert.ToBase64String(b);
}
//Decoding
public static string Base64ToString (string src) {
// Decodes Base64-encoded string to a byte array
byte[] b = Convert.FromBase64String(src);
// Returns decoded Unicode string
return Encoding.Unicode.GetString(b);
}

Resources