Bouncy Castle example for encoding CDR - encoding

I am trying to encode PGWRecord CDR using ASN.1 notation, starting on page 89 in this 3GPP TS Document
I've been looking for awhile for examples how I can do this, but to no avail. Are there any examples that can show me how to do this using Bouncy Castle? Or is there a better alternative than Bouncy Castle to encode this CDR?
Step by step instructions on how I can do this would be very nice!
Any help would be very appreciated. Thanks all!

Ya, just two months back i have worked on Bouncy castle to decode CDRS which of 3GPP stranded encoded file. Currently i am good in decoding and if any issues on decoding i can give more example and i can solve it easily solve it.
But for your question i can suggest some points and if you have any question pleas add comment. It not only help for you it can help for new bees who start with encode / decode process.
a) You did right API choice (Bouncy Castle) for encoding CDRS files
b) You can go for paid version of encode / decode APIs but it is too expansive
c) I have found 3 paid APIs which gives good and expected results, those are
1) [OSS Nokalva][1]
2) Obj-Sys
3) unigone
d) For me Bouncy castle gave 100% result then paid APIs even though they work well and good. If you want to use Bouncy castle then you need to put some more effort to work on encoding, So Bouncy castle is an API which support basic and some advanced parser, to do any encoding / decoding you need to write the java classes as per your ASN.1 syntax specification and so on.. I can write the steps but it will be too long so end of this answer i am giving you a link which explain it better. click on this link and download bcprov-jdk15on-154.tar.gz file.
e) Unzip the package you downloaded and go to bcprov-jdk15on-154\bcprov-jdk15on-154\src\org\bouncycastle\asn1\test you will find N number of examples to encode/decode CDRs according to the ASN.1 syntax specification
f) If you want to understand with very simple example then go through this link you can easily do your job
Still if you find difficult to understand then write a comment i will try to help my best.

Try to look at BinaryNotes. You have ASN.1 definition of what you are trying to encode. BinaryNotes will generate classes for encoding/decoding objects to/from ASN.1.
BinaryNotes works with xlst transformations to generate classes. You could modify the transformations in a way that it will use bouncy classes form encoding/decoding.

I guess that the encoding of GPRSRecord CHOICE would be something like that below.Be careful to tag values and conversion from string view to hex and BCD packing for IMSI and GSNAddress value :
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new BERTaggedObject(true, 0, new ASN1Integer(18))); //e.g. sgsnPDPRecord (18)
v.add(new BERTaggedObject(true, 3, new BEROctetString(Hex.decode("490154203237518")); //IMSI. String to BCD bytes conversion needed
v.add(new BERTaggedObject(true, 4, new BERTaggedObject(true, 0, new DEROctetString(Hex.decode("994507776655"))))); // GSNAddress
v.add(new BERTaggedObject(true, 5, new BEROctetString(Hex.decode("00DB")))); //ChargingID
byte[] encoded = BERTaggedObject.getInstance(new BERTaggedObject(true, 78, new BERSet(v))).getEncoded(); //SGWRecord

Related

Adding signingCertificateV2 attribute to SignedCms

ContentInfo content = new ContentInfo(new Oid("1.2.840.113549.1.7.5"), Encoding.UTF8.GetBytes(str.ToString()));
SignedCms signedCms = new SignedCms(content, true);
CmsSigner cmsSigner = new CmsSigner(cert);
cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly;
cmsSigner.DigestAlgorithm = new Oid("2.16.840.1.101.3.4.2.1");
cmsSigner.SignerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
Pkcs9AttributeObject att = new Pkcs9AttributeObject();
AsnEncodedData data = new AsnEncodedData(new SHA1Managed().ComputeHash(cert.RawData));
cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.UtcNow));
//cmsSigner.SignedAttributes.Add(new Pkcs9ContentType());
//cmsSigner.SignedAttributes.Add(new Pkcs9MessageDigest());
signedCms.ComputeSignature(cmsSigner);
return Convert.ToBase64String(signedCms.Encode());
I have used this code to sign a document and this code is working fine but my problem is that there is another requirement needed to add "SigningCertificateV2" attribute as a signed attribute...
I have already added ContentType, MessageDigest and SigningTime. But i dont know how to add "SigningCertificateV2" attribute.. (1.2.840.113549.1.9.16.2.47)
Can You please help me with this?
(It seems this question's been sitting unanswered for more than a year and a half, so I really hope Asharf managed to comply with the new requirement somehow. There's been more than 300 views though, so hopefully a late answer would still be helpful.)
The types in System.Security.Cryptography.Pkcs do not provide support for the full range of attributes defined by various Cryptographic Message Syntax (CMS) specs like CMS Advanced Electronic Signatures (CAdES) and Enhanced Security Services Update (ESSCertIdUpdate), but only for the most commonly used attribs like Pkcs9ContentType, Pkcs9MessageDigest, Pkcs9SigningTime, etc.
Specifically, there's no "strongly-typed" wrapper around the SigningCertificatev2 attribute, defined by ESSCertIdUpdate (RFC 5035). In that case, one has to use the "generic" CryptographicAttributeObject type and construct the ASN.1 encoded data for the attribute "by hand", that is, concoct a raw byte[], typically by using System.Formats.Asn1.AsnWriter (and thoroughly reading the relevant RFC -- that's always a good idea, btw).
Defining a wrapper for the SigningCertificatev2 attrib requires a fair amount of code as several other related RFC types like ESSCertIDv2 and PolicyInformation need also be defined.
Luckily, there's a well-known open-source software project that already does exactly that -- it can be used for "inspiration" ;-). That's NuGet, and specifically the NuGet client.
(I know link-only answers are frowned upon on SO, but I guess a link-mostly answer is better than no answer, so here goes...).
Here are the links to the relevant parts in the GutHub repo.
CreateSigningCertificateV2() in AttributeUtility
The SigningCertificateV2 type itself.
The EssCertIdV2 type, used by SigningCertificateV2.
The NuGet client's attribute implementation can't be used directly as a library, but it should provide a nice guideline about how to construct the PKCS attribute.

Coldfusion/Lucee Encoding Issue When Using EncodeForHTML

Running into an issue when using EncodeForHTML for certain characters (Emojis in this case)
The text in this case is:
⌛️a😊b👍c😟 💥🍉🍔 💩 🤦🏼‍♀️🤦🏼‍♀️🤦🏼‍♀️ 😘
Now if I just a straight output
<cfoutput>#txt#</cfoutput>
It displays correctly, no issues, but if I use EncodeForHTML first
<cfoutput>#EncodeForHTML(txt)#</cfoutput>
I get this
⌛️a��b��c�� ������ �� ����‍♀️����‍♀️����‍♀️ ��
I tested it with EncodeForXML & esapiEncode as well to be sure; all are giving me the same result.
I've verified the encoding settings in Lucee are UTF-8, and the meta charset tag is also set to UTF-8. I can't find any documenation re: EncodeForHTML saying if it make any changes to the character encoding, if it requires the character encoding to be something specific, or if it has any known issues with emojis or certain code points.
I appreciate any help or clarification anyone can provide.
Edit: Thank you everyone. Wish I could accept multiple answers.
I was required to sanitize emojis in order ensure that third-party content was cross-compatible with external services. Some of the content contained emojis and was causing export/import problems. I wrote a ColdFusion wrapper for the emoji-java library to identify, sanitize and convert emojis.
https://github.com/JamoCA/cf-emoji-java
For example, the parseToAliases() function "replaces all the emoji's unicodes found in a string by their aliases".
emojijava = new emojijava();
emojijava.parseToAliases('I like 🍕'); // I like :pizza:
To "encode" you could use either the parseToHtmlDecimal() or parseToHtmlHexadecimal() functions prior to using EncodeForHTML().
emojijava = new emojijava();
test = emojijava.parseToHtmlDecimal('I like 🍕'); // I ❤️ 🍕
EncodeForHTML(test);
At the time of this writing, ColdFusion's latest version is 2018 update 9
In turn, it uses ESAPI 2.1.1
Recent release notes don't mention Emoji,
https://github.com/ESAPI/esapi-java-legacy/tree/develop/documentation
But they do mention in Pull request 413
"Fixing ESAPI's inability to handle non-BMP codepoints."
This dates from 2017
https://github.com/ESAPI/esapi-java-legacy/pull/413
So based on all this information, I would recommend doing both of the following
Try using ESAPI directly. This is how it was done before ESAPI was added to CF. This issue may or may not still exist in ESAPI
Put in a ticket with Adobe to update this library.
Yes, ESAPI 2.2.0.0 addressed the issue of not correctly encoding non-BMP characters (see https://github.com/ESAPI/esapi-java-legacy/issues/300) as part of PR #413 that James mentioned above.
But I just uploaded release ESAPI 2.2.1.0-RC1 (release candidate 1) to Maven Central early this morning and hope to have an official 2.2.1.0 release out by next weekend, so if you are going to put in a ticket with Adobe for fix this with an updated version of ESAPI, I'd wait another week and then tell them to update to 2.2.1.0.

WebSphere MQ binary fiiles

This might be a question that may not be answered due to the nature of the external tool I am using (lack of documentation).
Basically, I am using a tool that pushes and pulls messages from the queue, more precisely - it pushes and pulls files. It worked perfectly for text files but when I tried pushing and then pulling a binary file - the pulled one was corrupted, it's size increased in comparsion with the original file (1.33 ratio).
For example moving a zip file wouldn't work...
I suppose it has something to do with the tools configuration, the only settings that can be changed regarding the problem are CCSID and encoding (UTF-8, Base16, etc.), I tried playing with both, unfortunately without success.
Tried using the following CCSIDs: 65535, 1208, 819
and encodings : UTF-8, Base16, Base64
In every case the binary file was corrupted after pulling it from the queue, I'm not entirely sure how the tool acomplishes that, it's written in Java, also I'm new to MQ so I tried searching for the correct options in IBM's docs but I haven't found anything that makes more sense than 65535 and Base16, yet it still doesn't work, could anyone with more experience with MQ tell if playing with these options makes sense at all in this case and if so - suggest what CCSID and encoding can I try to accomplish what Ive described above?
More information is really needed, but my suspicion is you are putting the message on the queue as a text message and playing around with encodings and ccsid's to try to get it right. You really need to know how the 'Java' app achieves this - is it using JMS (eg JMSBytesMessage) or base Java (something like setMessageData).
At a high level, there is a header on a message (The MD) which 'describes' the data - the MD format field. If you say the data is a string then MQ can convert between codepages should the getter request it etc. Put a tiny binary file into a message onto a queue, and browse the queue with amqsbcg or the GUI - what are the MD fields for format? What headers are on the payload - anything like RFH2's?
Put the same code in to give us a clue, or at least the amqsbcg output

[Zend]Filtering variables in a huge project

I have huge application written in ZendFramework. Earlier everything was fine.
As for now it was redesigned and received a lot of new functionalities and options, but I have to defend this software from xss.
Variables are taken from a couple sources (webform, Webservices, api, etc.), some of them should be escaped, some not.
What do you think, what will be the best method to defend my website, without editing all (2 000 +) files and escaping all echo's ?
Zend Framework comes with a class called "Zend_Filter". This class has a "StripTags" filter option that will strip all tags from a given string.
http://framework.zend.com/manual/en/zend.filter.set.html#zend.filter.set.striptags
If you note, even the strip tags filter isn't recommended for sanitizing input if you exclude something and it shouldn't be used to defend against XSS attacks. It recommends using Tidy or HTMLPurifier.
http://tidy.sourceforge.net/
http://htmlpurifier.org/
I think HTML Purifier is pretty easy to use. From their docs website:
require_once '/path/to/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault(); $purifier = new
HTMLPurifier($config); $clean_html = $purifier->purify($dirty_html);
I hope that helps!
Cheers!

base64 HmacSHA1 decode in iPhone

I am working on an iPhone application that requires Base64 decoding using HmacSHA1 algorithm. Can anyone help me doing the objective-C equivalent of the given Java code:
SecretKeykey = new SecretKeySpec(com.sinotar.algorithm.Base64.decode(
"vNQKX3C1wD/KprnnOcdRwM80YIn5bo47w9VdTlDpCB8="), "HmacSHA1");
Thanks matthijz, But it has nothing to do with HmacSHA1. The solution I am looking for is something that does the equivalent of the Java code:
SecretKey key = null;
try { key = new SecretKeySpec(com.sinotar.algorithm.Base64.decode("vNQKX3C1wD/KprnnOcdRwM80YIn5bo47w9VdTlDpCB8="),
"HmacSHA1");
}
Any help is appreciated.
Check out Matt Gallagher's article on Base64 encoding - it has downloadable code at the end. http://cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
The code you quote appears to be taking a base64 value, converting it to binary, and using it to set the key for an HMACSHA1 algorithm. The two steps are conceptually separate.
Here is the page for HMAC_SHA1 on Mac -- I haven't found the equivalent for iPhone, but I would assume it exists.