transform CMS (PKCS#7 based) signature into value suitable for xmldsig <ds:SignatureValue> field - x509certificate

I have CMS(PKCS#7 based) signature as input and I want to create equivalent xmldsig out of it. I can extract X509 certificate out of CMS message, but I don't see the way how to extract signature hash (to reuse in xmldsig field). Is there way to extract signature hash out of CMS message?

I have CMS(PKCS#7 based) signature as input and I want to create equivalent xmldsig out of it.
You can't convert a CMS SignedData to an XmlDSig SignedXml, they aren't signing the same thing.
CMS SignedData signs either the raw data (when no signed attributes are present) or the signed attributes (which, when present must contain the correct hash of the raw data as an attribute).
XmlDSig SignedXml uses a signature over the canonicalized SignedInfo element. The SignedInfo element contains the hash (digest) of the original data as part of its payload.
If you have the private key and understand that you need to resign after building the SignedInfo value manually, then we do get to the last part of your question:
Is there way to extract signature hash out of CMS message?
I'm not sure what "signature hash" means. If you mean "the hash of the original data", then in SignedCms that'd be something like
byte[] digest = cms.SignerInfos[0].SignedAttributes.OfType<CryptographicAttributeObject>().
FirstOrDefault(cao => cao.Oid.Value == "1.2.840.113549.1.9.4")?.Values.
OfType<Pkcs9MessageDigest>().FirstOrDefault()?.MessageDigest;
if (digest == null)
{
// Older form document, have to hash the original data again.
throw new NotImplementedException();
}
Perhaps with fewer calls to Linq extension methods and/or more assertions on correctness once the correct OID is found.

Related

How to store and retrieve passwords without being seen in the code using spock table

I am looking for some good approaches on storing passwords within the framework (groovy+geb+spock+selenium). Currently I am using encrypt and decrypt methods using Crypto.Cipher. However I would like to know if others have any good approaches to do it. Such as any other algorithms/techniques/tools?
It looks something like below:
def "test" (){
given:
when
Login(username,password)
then
where:
username | password
"jass" | "testpass123"
//"jass" | decryptPassword("some encrypted value ")
// instead of the actual password we are calling a
// function "decryptPassword" which takes encrypted value and
// returns the actual key to the calling function.
}
You can encrypt the password and store in the spock table. Write a separate method in other class for decrypt. Use the encrypted data. Call the decrypt method in password field instead of plain test.
More secure decrypt method should be converted as jar file and use it. So its difficult to find the decrypt algorithm.

How can I know the type of secret returned from Barbican GET /v1/secrets/ call?

I want to know the type of the key returned i.e, SYMMETRIC/PUBLIC/PRIVATE etc.
I have referred to Barbican API doc and came to know that the type parameter is used to know the secret type. But this parameter is only available in response to GET v1/orders/{order_id} call. Such parameter is not there in GET /v1/secrets/ call.
There is a parameter called secret_type which returns the type of secret returned. Supported values for this parameter are:
symmetric
public
private
passphrase
certificate
opaque
opaque is used as the default, which is used to signal Barbican to just store the information without worrying about format or encoding.
REFERENCE: API

Cache key length in asp.net

I was investigating the MVC3 source and came across the following (in OutputCacheAttribute.cs) which is called when generating a key to use for output caching:
// The key is typically too long to be useful, so we use a cryptographic hash
// as the actual key (better randomization and key distribution, so small vary
// values will generate dramtically different keys).
using (SHA256 sha = SHA256.Create()) {
return Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(uniqueIdBuilder.ToString())));
}
The comment says that the use of a hash is required because "The key is typically too long to be useful". Can anyone shed light on this and recommend a maximum length for cache keys in asp.net?
The length doesn't actually matter as it is converted to a hash.
This applies to MVC and ASP.NET.
Maximum length of cache keys in HttpRuntime.Cache object?

Passing IDs between web applications

We have several web applications that create a shopping cart, save it to a database, then redirect to a centralized web application to process and accept payment for the shopping cart. Right now, we are using GUIDs for the shopping cart IDs and passing those GUIDs in the querystring to the payment application. We are using GUIDs so that a user cannot easily guess the shopping cart ID of another user and simply plug that ID into the URL.
Now, using GUIDs in the database is bad for indexing and using GUIDs in the URL does not truly prevent a user from accessing another cart. However, using passing integers around would make it too easy.
What is the best and most secure way to pass the IDs from the individual applications to the centralized payment application?
I know that some people may say, "Who cares if someone else wants to pay for someone else's shopping cart?" However, we have the same concern when passing IDs to the page that displays the receipt and that page includes the customer's name.
You could pass the ID as an integer along with a "token" which would be a (cryptographically strong) hash of the cart ID and a random secret string. The payment processor would know the secret so it could perform the hash itself and compare to see if it is valid.
For example you can use the following (untested) code to create the token:
public static string GenerateHash(long CartID)
{
string SourceText = CartID.ToString();
//Salt the source text (secret)
SourceText += "5E95C91F7F947BD92ACA2CF81C3ADBD9B563839D85EA69F9DEA5A2DC330D0F50";
//Create an encoding object to ensure the encoding standard for the source text
UnicodeEncoding Ue = new UnicodeEncoding();
//Retrieve a byte array based on the source text
byte[] ByteSourceText = Ue.GetBytes(SourceText);
//Instantiate an MD5 Provider object
System.Security.Cryptography.SHA1CryptoServiceProvider SHA1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
//Compute the hash value from the source
byte[] ByteHash = SHA1.ComputeHash(ByteSourceText);
//And convert it to String format for return, also modify for URL use
return Convert.ToBase64String(ByteHash).Replace("=", "").Replace("+", "-").Replace("/", "_");
}
Pass the result of this function, along with your cart ID, since a hash is a one-way function that cannot be reversed. On the payment processor you would call the same function on the passed in cart ID and compare it to the token.
This will prevent tampering with the query string yet allow you to use integers.
Had you thought of POSTing to the central system and passing the values that way? Then they wouldn't be visible in your query string.
If you have to pass the GUID in the querystring, you could encrypt it to make it a little more secure. It will add a little overhead, also, to your processing.
You could also tie the user's cart to a cookie, then the GUID wouldn't be visible in the querystring and would be a little harder to detect (although using fiddler or some other tool like that would show what's being passed up and down).
I'd stick the identifier in a cookie, some other header or, if you have to POST, as a hidden value (like Lazarus suggested). I'd avoid having it on the querystring.
I would use methods similar to the Anti Forgery Token in ASP.NET MVC.
http://davidhayden.com/blog/dave/archive/2009/04/29/AntiForgeryTokenInMVCFramework.aspx
EG. In addition to your GUID, save a random id in a cookie and in the db tied to a user. Each time the user makes a http request check that the cookie matches with the database. It would be hard to get both the GUID and cookie correct.

Prevent query string manipulation by adding a hash?

To protect a web application from query string manipulation, I was considering adding a query string parameter to every url which stores a SHA1 hash of all the other query string parameters & values, then validating against the hash on every request.
Does this method provide strong protection against user manipulation of query string values? Are there any other downsides/side-effects to doing this?
I am not particularly concerned about the 'ugly' urls for this private web application. Url's will still be 'bookmarkable' as the hash will always be the same for the same query string arguments.
This is an ASP.NET application.
I'm not sure this provides any sort of security. If a man-in-the-middle attacker wants to change the parameters, all they must do is change the query string and recompute the SHA-1 hash and send that request along to the server.
For example, the URL sent by the browser might be:
http://www.example.com/addUser.html?parameterA=foo&hash=SHA1("parameterA=foo")
If an attacker intercepts this, they can edit it in this way:
http://www.example.com/adduser.html?parameterA=bar&hash=SHA1("parameterA=bar")
Really, this boils down to the fact you can trust the hash only as much as the parameters themselves.
One way you could fix this would be if the user has a password that only they and the server knows, then it would be impossible for the attacker to recompute the hash if they change the parameters. For example:
http://www.example.com/addUser.html?parameterA=foo&hash=SHA1("parameterA=foo"+"theuserpassword")
But don't put the password as one of the parameters in the URL :)
It is important to note that this isn't the state of the art for verifying the integrity of messages passed between two parties. What is used today is a form of the Hash-based Message Authentication Code (HMAC) algorithm, which is pretty well described in HMAC, and definitively in RFC2104 and FIPS Pub 198-1.
My solution to prevent query string manipulation with no hash:
In the global.asax file
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// I take the url referer host. (manipulating the query string this value is null or your local address)
string strRefererHost = Request.UrlReferrer == null ? string.Empty : Request.UrlReferrer.Host;
// This is the host name of your application
string strUrlHost = Request.Url.Host;
// I read the query string parameters
string strQSPars = Request.Url.Query ?? string.Empty;
// If the referer is not the application host (... someone manipulated the qs)...
// and there is a query string parameter (be sure of this otherwise nobody can access the default page of your site
// because this page has always a local referer...)
if (strRefererHost != strUrlHost && strQSPars != string.Empty)
Response.Redirect("~/WrongReferer.aspx"); // your error page
}
You might consider using this little open source library:
http://www.codeproject.com/KB/aspnet/Univar.aspx
It uses a unique key for each client computer and comes with many other goodies.
I think is a good idea to add a parameter with a hash of all the other parameters. It prevents radically the querystring manipulation, but you have to think about the problem that means use those URLs in other pages of your application, send those URLs to the public or use them in any printed way. You need to have a very good way to order and to have them at hand speccially if those pages are not dynamically created, or if you just need to add those URLs by hand.
I don't see any other problem about it. Some one may tell you that the hash can be calculated, but you can play with the order of the parameters obtaining different hashes and making very difficult to guess.
One major problem with this is that javascript would have to do client-side SHA calculations just to link to pages, this of course depends on how much you use JS but it shouldn't be unresonable to think that a get argument might include pageNo=1, and to have a 'jump to page' input box, this would be made difficult if you add a hash. You could store in a session (server side) anything that you really don't want manipulated.

Resources