How to read Data Object with IAIK wrapper 1.6.2 - pkcs#11

my issue is I was using following versions of IAIK with Tokens
Provider : 1.5
Wrapper :1.4
JCE : 5.25
Safenet PKCS11 drivers : 10.2
Now I wpould like to use latest version :
Provider : 1.6.2
Wrapper :1.7
JCE : 5.62
Safenet PKCS11 drivers : 10.8 R2
The big issue is I can no longer read data object even with
session.findObjectsInit(null);
With old versions, using following template I can get Data Object:
private static GenericTemplate getTokenObjectTemplate3(String label) {
Preconditions.checkArgument(label != null);
GenericTemplate template = new GenericTemplate();
LongAttribute objectClassAttribute = new LongAttribute(PKCS11Constants.CKA_CLASS);
objectClassAttribute.setLongValue(new Long(PKCS11Constants.CKO_DATA));
template.addAttribute(objectClassAttribute);
CharArrayAttribute labelAttribute = new CharArrayAttribute(PKCS11Constants.CKA_LABEL);
labelAttribute.setCharArrayValue("oostatus".toCharArray());
template.addAttribute(labelAttribute);
BooleanAttribute tokenAttribute = new BooleanAttribute(PKCS11Constants.CKA_TOKEN);
tokenAttribute.setBooleanValue(Boolean.TRUE);
template.addAttribute(tokenAttribute);
BooleanAttribute privateAttribute = new BooleanAttribute(PKCS11Constants.CKA_PRIVATE);
privateAttribute.setBooleanValue(Boolean.FALSE);
template.addAttribute(privateAttribute);
CharArrayAttribute applicationAttribute = new CharArrayAttribute(PKCS11Constants.CKA_APPLICATION);
applicationAttribute.setCharArrayValue(TOKEN_APPLICATION.toCharArray());
template.addAttribute(applicationAttribute);
return template;
}
Now I'm using the following but in vain :
private static Data getTokenObjectTemplate4() {
Data dataObjectTemplate = new Data();
dataObjectTemplate.getLabel().setCharArrayValue(TOKEN_STATUS_LABEL.toCharArray());
return dataObjectTemplate;
}
Any help or peace of runing code please ?

Related

What is the equivalent method of ExecuteQuerySegmentedAsync in Azure.Data.Tables?

What is the equivalent method of ExecuteQuerySegmentedAsync in Azure.Data.Tables?
Recently Microsoft azure sdk deprecated Microsoft.Azure.Cosmos.Table package and recommended to use Azure.Data.Tables package.
But, I couldn't find equivalent ExecuteQuerySegmentedAsync method in Azure.Data.Tables package.
Current code using Microsoft.Azure.Cosmos.Table package below:
var srcTableName = "TestTable";
var tableBatchResults = new List<TableBatchResult>();
CloudTable srcCloudTable = tableClient.GetTableReference(srcTableName);
var tableContinuationToken = new TableContinuationToken();
do
{
var entities = new List<T>();
var segment = await srcCloudTable.ExecuteQuerySegmentedAsync<T>(tableQuery, tableContinuationToken);
entities.AddRange(segment.Results);
}while (tableContinuationToken != null);
How to convert this code with Azure.Data.Tables package.

iText 7: Certificate-encrypted PDF returns no permissions

When I use iText 7 for .NET to read a PDF file encrypted using a certificate and inspect the permissions, the GetPermissions() method returns 0.
Package version: 7.2.1
Operating system: Windows 10
Here is the code that I use to encrypt an existing PDF file:
using var inputPdfReader = PdfReaderFactory.CreatePdfReader("plain.pdf");
using var outputStream = new FileStream("encrypted.pdf", FileMode.Create);
var certificate = new X509Certificate2("mycert.pfx", "secret", X509KeyStorageFlags.Exportable);
var writerProperties = new WriterProperties()
.SetPublicKeyEncryption(
new[] { DotNetUtilities.FromX509Certificate(certificate) },
new[] { EncryptionConstants.ALLOW_COPY | EncryptionConstants.ALLOW_DEGRADED_PRINTING },
Encryption);
using var pdfWriter = new PdfWriter(outputStream, writerProperties);
using var outputPdfDocument = new PdfDocument(inputPdfReader, pdfWriter);
As long as the certificate is installed in my certificate store I can open the PDF using Acrobat Reader, and it displays the expected permissions:
However, when I read this PDF using iText 7, the permissions come back as 0:
var certificate = new X509Certificate2("mycert.pfx", "secret", X509KeyStorageFlags.Exportable);
if (!certificate.HasPrivateKey)
{
throw new NotSupportedException("Certificate must have a private key.");
}
var bouncyCertificate = DotNetUtilities.FromX509Certificate(certificate);
var keyPair = DotNetUtilities.GetKeyPair(certificate.GetRSAPrivateKey());
var readerProperties = new ReaderProperties()
.SetPublicKeySecurityParams(bouncyCertificate, keyPair.Private);
using var pdfReader = new PdfReader("encrypted.pdf", readerProperties);
using var pdfDocument = new PdfDocument(pdfReader);
int permissions = (int)pdfReader.GetPermissions();
// permissions == 0
This looks like a bug in iText 7. Am I missing something?

Wixsharp upgrade is not retaining previous settings like DB data and other configurations

I'm using wixsharp to build my installer. Everytime I give a new build I want to update all my exe, dlls and other binaries but I want to retain manually changed settings like we have an option to store some keys in database that will create some folders inside application folder in program files. I want to retain this data and to replace binaries but when I upgrade it is deleting this data as well.
I'm using below wixsharp code to implement upgrade.
project.UpgradeCode= new Guid("some GUID here, keeping it same in all builds");
project.ProductId = new Guid("GUID here, changing it in all incremental build");
project.Version = new Version(6, 1, 1, 1); // upgrading it in incremental builds
project.MajorUpgrade = new MajorUpgrade
{
Schedule = UpgradeSchedule.afterInstallValidate,
AllowSameVersionUpgrades = true,
MigrateFeatures =true,
IgnoreRemoveFailure=true,
DowngradeErrorMessage="A new version of this product is already installed."
};
One more issue with this I'm facing is when we are installing 2nd build it is not showing the upgrade option but showing install option only (like fresh installation) and at last it is asking user's permission to uninstall the product, that is uninstalling old product it seems but it doesn't look user friendly as user might feel why he/she is uninstalling the product.
I just want an upgrade option that can do the upgrade without showing user what is going in backend.
Question 1:
If you want to have some static files which ones adds if not exist but not update them with new one installation. You need to mark them with Permanent="yes" NeverOverwrite="yes" attributes.
For more information link here: Wix Component Element
How to make it with WixSharp?
Here is my code how to make index.html and web.config immutable:
var immutableFiles =
{
#"index.html",
#"web.config"
};
// ....
var wixObjects = new WixObject[]
{
new Dir(
#"%ProgramFiles%\YourProductFolderName\",
WixFilesBuilderUtils.BuildDirectoryInfo(BinariesRoot, immutableFiles)),
// Properties etc...
}.ToArray();
var project = new ManagedProject("name", wixObjects);
Builder code:
public class WixFilesBuilderUtils
{
public static WixEntity[] BuildDirectoryInfo(string currentRoot, IEnumerable<string> immutableFiles)
{
var result = new List<WixEntity>();
var currentRootDictionaryInfo = new DirectoryInfo(currentRoot);
var localImmutableFiles = immutableFiles.Select(fileName => fileName.ToLower()).ToArray();
var currentRootDirList = currentRootDictionaryInfo
.GetDirectories()
.Select(dirInfoSub => dirInfoSub.FullName).ToArray();
result.AddRange(
Directory.GetFiles(currentRootDictionaryInfo.FullName)
.Select(
filePath => new WixSharp.File(filePath)
{
Attributes = MarkFileAsPersonal(filePath, localImmutableFiles)
})
.Cast<WixEntity>());
if (currentRootDirList.Any())
{
var subDirs = currentRootDirList
.Select(dirPath => new DirectoryInfo(dirPath))
.Select(
rootSubDirInfo =>
new Dir(rootSubDirInfo.Name,
BuildDirectoryInfo(rootSubDirInfo.FullName, localImmutableFiles)))
.Cast<WixEntity>();
result.AddRange(subDirs);
}
return result.ToArray();
}
private static Dictionary<string, string> MarkFileAsPersonal(string path, IEnumerable<string> immutableFiles)
{
return immutableFiles.Any(path.ToLower().EndsWith)
? new Dictionary<string, string>
{
{ "Component:Permanent", "yes" },
{ "Component:NeverOverwrite", "yes" }
}
: new Dictionary<string, string>();
}
}
Question 2:
Please try to have same UpdateCode and ProductCode GUIDs each one build and this one strategy:
MajorUpgradeStrategy = new MajorUpgradeStrategy
{
RemoveExistingProductAfter = Step.InstallInitialize,
UpgradeVersions = VersionRange.OlderThanThis,
PreventDowngradingVersions = VersionRange.NewerThanThis,
NewerProductInstalledErrorMessage = "."
};

How to tokenize a text in lucene 3.0.3

I need to translate this code from lucene.net 2.3.2 to 3.0.3.
This code works fine in 2.3.2 but in 3.0.3 the method tokenStream.Next() does not return a token but a boolean. What I need to understand is where to read the token object when next() returns true.
Analyzer analyzer = new StandardAnalyzer();
StringReader stringReader = new StringReader("the house id red");
TokenStream tokenStream = analyzer.TokenStream("", stringReader);
Token token = tokenStream.Next();
while (token != null)
{
System.Diagnostics.Debug.Write(token.TermText());
token = tokenStream.Next();
}
The TokenStreams in Lucene 3+ can now represent a whole set of values (called attributes) for each position in the stream. So you need to modify your example to be attribute aware...
var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
var stringReader = new StringReader("the house id red");
var tokenStream = analyzer.TokenStream(string.Empty, stringReader);
var termAtt = tokenStream.GetAttribute<ITermAttribute>();
while (tokenStream.IncrementToken())
{
Console.WriteLine(termAtt.Term);
}

Hide template visibility depending on VS version?

I have created a VSIX with 2 templates, one is for VS2012 and another is for VS2013.
But if I use the VSIX, both templates are visible for both VS versions in "New Project" window. I want to restrict it. Is there any way?
This is not a great solution, but only one I've found for this problem.
You can register your package to initialize early on in the Visual Studio startup with the following attribute.
[ProvideAutoLoad(UIContextGuids80.NoSolution)]
public sealed YourPackage : Package
Then in your override void Initialize() method you'll want to register a new DTEEvent.
DTEEvents dte_events;
private void RegisterStartupEvents()
{
if(dte == null)
dte = (DTE)GetService(typeof(DTE));
if (dte != null)
{
dte_events = dte.Events.DTEEvents;
dte_events.OnStartupComplete += OnStartupComplete;
}
}
The OnStartupComplete will fire on startup before any templates have been initialized. To remove them from the list for the current VS version, the bundled zip template files that are copied when your VSIX package is installed will have to be deleted. This method could probably be nicer, but you get the idea.
private void OnStartupComplete()
{
dte_events.OnStartupComplete -= OnStartupComplete;
dte_events = null;
var cleanupList = TemplateCleanupByVsVersion[MajorVisualStudioVersion];
foreach (var deleteTemplate in cleanupList)
{
DirectoryInfo localVsDir = new DirectoryInfo(UserLocalDataPath);
// Locate root path of your extension installation directory.
var packageDllFileInfo = localVsDir.GetFiles("MyVsPackage.dll", SearchOption.AllDirectories)[0];
DirectoryInfo extensionDirInfo = packageDllFileInfo.Directory;
if (extensionDirInfo == null)
{
// Failed to locate extension install directory, bail.
return;
}
var files = extensionDirInfo.GetFiles(deleteTemplate + ".zip", SearchOption.AllDirectories);
if (files.Length > 0)
{
File.Delete(files[0].FullName);
}
}
ServiceProvider.GetWritableSettingsStore().SetPackageReady(true);
}
TemplateCleanupByVsVersion is a Dictionart<int,List<string>> that maps Visual Studio Major version with a list of zip file names (without extension) that you don't want showing up in the mapped Visual Studio version. Eg,
public readonly Dictionary<int, List<string>> TemplateCleanupByVsVersion = new Dictionary<int, List<string>>
{
{11,new List<string> { "MyTemplate1.csharp", "MyTemplate2.csharp", "MyTemplate3.csharp" } },
{12,new List<string> { "MyTemplate1.csharp" }},
{14,new List<string>()}
};
MajorVisualStudioVersion comes from parsing dte.Version. eg,
public int MajorVisualStudioVersion => int.Parse(dte.Version.Substring(0, 2));
The result being specific Visual Studio versions can remove any templates from your VSIX that don't work well. Hope that helps.