PKCS#11 Generate AES key - cryptography

Hei,
The question is not really about Ncryptoki but i didnt know anywhere else to ask.. so if anybody can help please help me.
Im tryng to generate AES key and heres the code what i have right now:
CK_MECHANISM keyGenMech = new CK_MECHANISM(CKM.AES_KEY_GEN);
CK_ATTRIBUTE[] template =
{
new CK_ATTRIBUTE(CKA.CLASS, CKO.SECRET_KEY),
new CK_ATTRIBUTE(CKA.TOKEN, CK_BBOOL.TRUE),
new CK_ATTRIBUTE(CKA.SENSITIVE, CK_BBOOL.TRUE),
new CK_ATTRIBUTE(CKA.VALUE_LEN, 32),
new CK_ATTRIBUTE(CKA.KEY_TYPE, CKK.AES),
new CK_ATTRIBUTE(CKA.LABEL, "testAES".getBytes()),
new CK_ATTRIBUTE(CKA.PRIVATE, new CK_BBOOL(bPrivate))
};
CryptokiEx.C_GenerateKey(session, keyGenMech, template, template.length, wrappingKey);
But this gives me a error:
C_GenerateKey rv=0x62 - key size range
Can anybody give me some idea where to go from here to solve this..
EDIT: Just for info - I have SafeNet HSM and im using java PKCS#11 wrapper called jprov what comes with SafeNet ProtectToolkit.

I found the answere, new CK_ATTRIBUTE(CKA.VALUE_LEN, 32), , the 32 in there has to be CK_ULONG value so when i do this:
LongRef l = new LongRef((long)32);
CK_ATTRIBUTE[] template =
{
new CK_ATTRIBUTE(CKA.CLASS, CKO.SECRET_KEY),
new CK_ATTRIBUTE(CKA.TOKEN, CK_BBOOL.TRUE),
new CK_ATTRIBUTE(CKA.SENSITIVE, CK_BBOOL.TRUE),
new CK_ATTRIBUTE(CKA.VALUE_LEN, l.value),
//new CK_ATTRIBUTE(CKA.VALUE, key),
new CK_ATTRIBUTE(CKA.KEY_TYPE, CKK.AES),
new CK_ATTRIBUTE(CKA.LABEL, "testAES".getBytes()),
new CK_ATTRIBUTE(CKA.PRIVATE, new CK_BBOOL(bPrivate))
};
Where LongRef is:
public class LongRef {
public long value;
public LongRef(long l) {
//compiled code
throw new RuntimeException("Compiled Code");
}
}
Hope this helps someone.

Related

Entity Framework 6 - Save Changes

I am trying to perform an insert with EF 6.
I have verified I have a connection to the database, because I can do a read:
List<Driver> drivers = DataContext.Drivers.ToList();
With a sql profiler, I can see this do a select on the database, and it returns an item I manually inserted.
I am trying to perform an insert like this:
var driver = new Driver();
driver.DriverName = "Blah";
DataContext.Drivers.Add(driver);
DataContext.ChangeTracker.HasChanges(); //false
DataContext.SaveChanges();
except nothing is inserted, and the changetracker seems to show that it has not detected any changes. I also saw suggestions to use .Attach but this had the same results.
Any help on what I am doing wrong?
Cheers
(MyEntities.Context.cs)
public partial class MyEntities : DbContext
{
public MyEntities()
: base("name=MyEntities")
{
}
public partial class MyDataContext : MyEntities
{
public class SqlDataService : DataServiceBase<...Data.MyDataContext>
{
//where I am trying to do the insert with the code above
edit: No not using code first (not that i'm aware of!) not sure if the above code samples help, but show how I have set up my classes
It seems you have AutomaticTrackChanges turned off somewhere in your code.
Try adding this line before the addition:
var driver = new Driver();
driver.DriverName = "Blah";
//Turning Automatic changes tracking on:
DataContext.Configuration.AutoDetectChangesEnabled = true;
DataContext.Drivers.Add(driver);
DataContext.ChangeTracker.HasChanges(); //True
DataContext.SaveChanges();
Note: AutoDetectChangesEnabled is usually turned off for performance considerations

Lucene's WordnetSynonymParser

I am trying to use Lucene's WordnetSynonymParser class to create a synonym filter, but I'm not sure which of the prolog files I'm meant to be passing into the parse() function.
The documentation says:
See http://wordnet.princeton.edu/man/prologdb.5WN.html for a
description of the format.
so I've downloaded the prolog files, but I'm not sure which ones I should be passing in, and how I go about it.
Could someone please point me in the right direction?
Thanks for your help
EDIT:
Thanks to femtoRgon for pointing me in the direction of wn_s.pl. I have now got the following code:
Analyzer tempanalyzer = new SimpleAnalyzer(Version.LUCENE_40);
WordnetSynonymParser synparser = new WordnetSynonymParser(true, true, tempanalyzer);
FileReader doctoread = new FileReader("wn_s.pl");
synparser.parse(doctoread);
SynonymMap synmap = synparser.build();
Analyzer analyzer = new Analyzer() {
#Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
EnglishAnalyzer enganalyzer = new EnglishAnalyzer(Version.LUCENE_40);
CharArraySet engstopset = enganalyzer.getDefaultStopSet();
Tokenizer source = new StandardTokenizer(Version.LUCENE_40, reader);
TokenStream filter = new SynonymFilter(source, synmap, true);
filter = new StandardFilter(Version.LUCENE_40, filter);
filter = new LowerCaseFilter(Version.LUCENE_40, filter);
filter = new StopFilter(Version.LUCENE_40, filter, engstopset);
/*TokenStream filter = new StandardFilter(Version.LUCENE_40, source);
filter = new LowerCaseFilter(Version.LUCENE_40, filter);
filter = new StopFilter(Version.LUCENE_40, filter, engstopset);*/
return new TokenStreamComponents(source, filter);
}
};
which I then plan on passing into IndexWriterConfig, however I get the following compile error:
IndexFilesDB.java:133: cannot find symbol
symbol : method parse(java.io.FileReader)
location: class org.apache.lucene.analysis.synonym.WordnetSynonymParser
synparser.parse(doctoread);
I still don't fully understand WordnetSynonymParser, is it an error to do with the class or it just a simple error where the file is not being passes in correctly?
Thanks for your help.
wn_s.pl contains the synset pointers (that is, it defines groups of synonyms), which is what you need for a synonym filter, to my knowledge. I'd start with that.

Rss20FeedFormatter Ignores TextSyndicationContent type for SyndicationItem.Summary

While using the Rss20FeedFormatter class in a WCF project, I was trying to wrap the content of my description elements with a <![CDATA[ ]]> section. I found that no matter what I did, the HTML content of the description elements was always encoded and the CDATA section was never added. After peering into the source code of Rss20FeedFormatter, I found that when building the Summary node, it basically creates a new TextSyndicationContent instance which wipes out whatever settings were previously specified (I think).
My Code
public class CDataSyndicationContent : TextSyndicationContent
{
public CDataSyndicationContent(TextSyndicationContent content)
: base(content)
{
}
protected override void WriteContentsTo(System.Xml.XmlWriter writer)
{
writer.WriteCData(Text);
}
}
... (The following code should wrap the Summary with a CDATA section)
SyndicationItem item = new SyndicationItem();
item.Title = new TextSyndicationContent(name);
item.Summary = new CDataSyndicationContent(
new TextSyndicationContent(
"<div>This is a test</div>",
TextSyndicationContentKind.Html));
Rss20FeedFormatter Code
(AFAIK, the above code does not work because of this logic)
...
else if (reader.IsStartElement("description", ""))
result.Summary = new TextSyndicationContent(reader.ReadElementString());
...
As a workaround, I've resorted to using the RSS20FeedFormatter to build the RSS, and then patch the RSS manually. For example:
StringBuilder buffer = new StringBuilder();
XmlTextWriter writer = new XmlTextWriter(new StringWriter(buffer));
feedFormatter.WriteTo(writer ); // feedFormatter = RSS20FeedFormatter
PostProcessOutputBuffer(buffer);
WebOperationContext.Current.OutgoingResponse.ContentType =
"application/xml; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(buffer.ToString()));
...
public void PostProcessOutputBuffer(StringBuilder buffer)
{
var xmlDoc = XDocument.Parse(buffer.ToString());
foreach (var element in xmlDoc.Descendants("channel").First()
.Descendants("item")
.Descendants("description"))
{
VerifyCdataHtmlEncoding(buffer, element);
}
foreach (var element in xmlDoc.Descendants("channel").First()
.Descendants("description"))
{
VerifyCdataHtmlEncoding(buffer, element);
}
buffer.Replace(" xmlns:a10=\"http://www.w3.org/2005/Atom\"",
" xmlns:atom=\"http://www.w3.org/2005/Atom\"");
buffer.Replace("a10:", "atom:");
}
private static void VerifyCdataHtmlEncoding(StringBuilder buffer,
XElement element)
{
if (!element.Value.Contains("<") || !element.Value.Contains(">"))
{
return;
}
var cdataValue = string.Format("<{0}><![CDATA[{1}]]></{2}>",
element.Name,
element.Value,
element.Name);
buffer.Replace(element.ToString(), cdataValue);
}
The idea for this workaround came from the following location, I just adapted it to work with WCF instead of MVC. http://localhost:8732/Design_Time_Addresses/SyndicationServiceLibrary1/Feed1/
I'm just wondering if this is simply a bug in Rss20FeedFormatter or is it by design? Also, if anyone has a better solution, I'd love to hear it!
Well #Page Brooks, I see this more as a solution then as a question :). Thanks!!! And to answer your question ( ;) ), yes, I definitely think this is a bug in the Rss20FeedFormatter (though I did not chase it as far), because had encountered precisely the same issue that you described.
You have a 'localhost:8732' referral in your post, but it wasn't available on my localhost ;). I think you meant to credit the 'PostProcessOutputBuffer' workaround to this post:
http://damieng.com/blog/2010/04/26/creating-rss-feeds-in-asp-net-mvc
Or actually it is not in this post, but in a comment to it by David Whitney, which he later put in a seperate gist here:
https://gist.github.com/davidwhitney/1027181
Thank you for providing the adaption of this workaround more to my needs, because I had found the workaround too, but was still struggling to do the adaptation from MVC. Now I only needed to tweak your solution to put the RSS feed to the current Http request in the .ashx handler that I was using it in.
Basically I'm guessing that the fix you mentioned using the CDataSyndicationContent, is from feb 2011, assuming you got it from this post (at least I did):
SyndicationFeed: Content as CDATA?
This fix stopped working in some newer ASP.NET version or something, due to the code of the Rss20FeedFormatter changing to what you put in your post. This code change might as well have been an improvement for other stuff that IS in the MVC framework, but for those using the CDataSyndicationContent fix it definitely causes a bug!
string stylesheet = #"<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform""><xsl:output cdata-section-elements=""description"" method=""xml"" indent=""yes""/></xsl:stylesheet>";
XmlReader reader = XmlReader.Create(new StringReader(stylesheet));
XslCompiledTransform t = new XslCompiledTransform(true);
t.Load(reader);
using (MemoryStream ms = new MemoryStream())
{
XmlWriter writer = XmlWriter.Create(ms, t.OutputSettings);
rssFeed.WriteTo(writer); // rssFeed is Rss20FeedFormatter
writer.Flush();
ms.Position = 0;
string niko = Encoding.UTF8.GetString(ms.ToArray());
}
I'm sure someone pointed this out already but this a stupid workaround I used.
t.OutputSettings is of type XmlWriterSettings with cdataSections being populated with a single XmlQualifiedName "description".
Hope it helps someone else.
I found the code for Cdata elsewhere
public class CDataSyndicationContent : TextSyndicationContent
{
public CDataSyndicationContent(TextSyndicationContent content)
: base(content)
{
}
protected override void WriteContentsTo(System.Xml.XmlWriter writer)
{
writer.WriteCData(Text);
}
}
Code to call it something along the lines:
item.Content = new Helpers.CDataSyndicationContent(new TextSyndicationContent("<span>TEST2</span>", TextSyndicationContentKind.Html));
However the "WriteContentsTo" function wasn't being called.
Instead of Rss20FeedFormatter I tried Atom10FeedFormatter - and it worked!
Obviously this gives Atom feed rather than traditional RSS - but worth mentioning.
Output code is:
//var formatter = new Rss20FeedFormatter(feed);
Atom10FeedFormatter formatter = new Atom10FeedFormatter(feed);
using (var writer = XmlWriter.Create(response.Output, new XmlWriterSettings { Indent = true }))
{
formatter.WriteTo(writer);
}

JavaScriptSerializer and monodevelop

Im reading this book but I JavaScriptSerializer from the System.Web.Script.Serialization namespace because it seems to be unavailable?
I know this a really old post but by chance someone stumbles upon this like I have, System.Web.Script.Serialization is available in System.Web.Extensions.
Download source here and add as existing project.
Then add as reference:
http://www.bloxify.com/post/MonoTouch-Easy-JSON-Library.aspx
Edit:
You may also find that the monotouch linker is pretty aggressive. I would have code work fine in the simulator but crash in the device with method missing exceptions. Add a method somewhere in your app (you dont have to call it) like so:
public void FixMonoTouchErrors()
{
var gc = new System.ComponentModel.GuidConverter();
var sc = new System.ComponentModel.StringConverter();
var dc = new System.ComponentModel.DateTimeConverter();
var cc = new System.ComponentModel.CharConverter();
var sh = new System.ComponentModel.Int16Converter();
var sh1 = new System.ComponentModel.Int32Converter();
var sh2 = new System.ComponentModel.Int64Converter();
var dec = new System.ComponentModel.DecimalConverter();
var nc0 = new System.ComponentModel.NullableConverter(typeof(Int16?));
var nc1 = new System.ComponentModel.NullableConverter(typeof(Int32?));
var nc2 = new System.ComponentModel.NullableConverter(typeof(Int64?));
var nc3 = new System.ComponentModel.NullableConverter(typeof(decimal?));
var nc4 = new System.ComponentModel.NullableConverter(typeof(DateTime?));
}

Serialize an Activity to xaml

I have Googled a bit, and cannot seem to find any examples of Xaml-fying Activities - good, bad, or otherwise!
public static string ToXaml (this Activity activity)
{
// i would use ActivityXamlServices to go from Xaml
// to activity, but how to go other way? documentation
// is slim, and cannot infer proper usage of
// ActivityXamlServices from Xml remarks :S
string xaml = string.Empty;
return xaml;
}
Hints, tips, pointers would be welcome :)
NOTE: so found this. Will work through and update once working. Anyone wanna beat me to the punch, by all means. Better yet, if you can find a way to be rid of WorkflowDesigner, seems odd it is required.
Alright, so worked through this forum posting.
You may Xaml-fy [ie transform an instance to declarative Xaml] a well-known Activity via
public static string ToXaml (this Activity activity)
{
StringBuilder xaml = new StringBuilder ();
using (XmlWriter xmlWriter = XmlWriter.Create (
xaml,
new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true, }))
using (XamlWriter xamlWriter = new XamlXmlWriter (
xmlWriter,
new XamlSchemaContext ()))
using (XamlWriter xamlServicesWriter =
ActivityXamlServices.CreateBuilderWriter (xamlWriter))
{
ActivityBuilder activityBuilder = new ActivityBuilder
{
Implementation = activity
};
XamlServices.Save (xamlServicesWriter, activityBuilder);
}
return xaml.ToString ();
}
Your Xaml may contain certain artifacts, such as references to System.Activities.Presentation namespace appearing as xmlns:sap="...". If this presents an issue in your solution, read the source link above - there is a means to inject directives to ignore unrecognized namespaces.
Will leave this open for a while. If anyone can find a better solution, or improve upon this, please by all means :)
How about XamlServices.Save(filename, activity)?
Based on the other solution (for VS2010B2) and some Reflectoring, I found a solution for VS2010RC. Since XamlWriter is abstract in the RC, the new way to serialize an activity tree is this:
public static string ToXaml (this Activity activity)
{
var xamlBuilder = new StringBuilder();
var xmlWriter = XmlWriter.Create(xamlBuilder,
new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true });
using (xmlWriter)
{
var xamlXmlWriter =
new XamlXmlWriter(xmlWriter, new XamlSchemaContext());
using (xamlXmlWriter)
{
XamlWriter xamlWriter =
ActivityXamlServices.CreateBuilderWriter(xamlXmlWriter);
using (xamlWriter)
{
var activityBuilder =
new ActivityBuilder { Implementation = sequence };
XamlServices.Save(xamlWriter, activityBuilder);
}
}
}
return xamlBuilder.ToString();
}