how to load an rsa asymmetric key pair with obj-c on the iphone? - iphone

I have the raw bytes of public and private key in a buffer and want to use that information to encrypt / decrypt data.
I do know that I could generate a keypair using SecKeyGeneratePair and then save it to the keychain, but i don't want that...
essentially, i need the Objective-C equivalent of the following Java Code (using Bouncycastle)
BigInteger modulus = ....
BigInteger publicExponent = ....
BigInteger privateExponent = ....
RSAKeyParameters pubKey = new RSAKeyParameters(false, modulus, publicExponent);
RSAKeyParameters privKey = new RSAKeyParameters(true, modulus, privateExponent);
return new AsymmetricCipherKeyPair(pubKey, privKey);
Any ideas? I'm really stuck on that problem....

Well, I know that OpenSSL allows you to do this, so you might want to investigate compiling OpenSSL into your project...
This link looks like it has decent instructions on how to do that.

Related

Can we add ByteArrayInputStream in JobManager?

AEM6.2
I have a Osgi Service where in org.apache.sling.event.jobs.JobManager referenced and job is added to it.
The code is something like:
Map dataSourceMap = new HashMap<String, DataSource>
dataSourceMap.put(fileName, new ByteArrayDataSource(byte[], mimeTypeOfFile))
final Map<String, Object> props = new HashMap<String, Object>();
props.put("item1", "/something");
props.put("count", 5);
props.put("files", dataSourceMap)
jobManager.addJob("my/special/jobtopic", props);
When this job gets executed it shows some error
org.apache.sling.api.resource.PersistenceException: Value can't be stored in the repository: {<<filename>>=org.apache.commons.mail.ByteArrayDataSource#3f0f234c}
Question: Is there any solution to this exception? Or am I doing something wrong? can we add a ByteArrayInputStream to the jobmanager?
Thank you !
Just a info, If I remove the line props.put("files", dataSourceMap), it works fine.
Please let me know if you need more info on it.
Sling will store the job as a node in the repository and it looks like it only supports the "standard" types like String, Boolean, Integer etc. and not files/blobs.
I can not think of a way to add a file to the job, but what you could do is to create temporary node in the repository yourself, which contains the files/blobs.
Sling stores jobs here:
/var/eventing/jobs
You might do something similar:
/var/<project-name>/jobs
And the payload of the Sling job then contains the path to this job node.
Further to Jens' comment, the job will indeed store data as node properties in the JCR. You could likely explore the possibility of storing data as Binary to the jcr:data property, but I have not tested this myself.
As a quick and likely not very optimized workaround, why not serialize your byte[] to a String or even encode it to a Base64 string?
Sample: Base64 Java encode and decode a string [duplicate]

CKR_USER_NOT_LOGGED_IN when generating key pair using sunPKCS11 provider

When trying to generate rsa key pair with sun PKCS11 provider, method generateKeyPair() throws ProviderException: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_USER_NOT_LOGGED_IN
My code looks like this:
Provider prov = ... // initialize provider
KeyStore ks = KeyStore.getInstance("PKCS11", prov);
ks.load(null, "pass".toCharArray());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", prov);
keyGen.initialize(2048);
KeyPair kp = keyGen.generateKeyPair(); // exception thrown here
I tried using AuthProvider right after provider initialization like so:
AuthProvider aprov = (AuthProvider) prov;
aprov.login(null, callbacks -> {
log.error("### Inside callbacks {}", callbacks.length);
});
aprov.setCallbackHandler(callbacks -> {
log.error("### Inside setCallBackHandler {}", callbacks.length);
});
But I don't see any logging output, so that means lambdas are not executed.
The ultimate goal is to generate RSA key pair and store it in keystore (HSM) via PKCS11.
I tried openjdk 8 and oracle jdk 8. Also when listing aliases from keystore, I get an empty list, but I know there is one entry. Adding -Djava.security.debug=sunpkcs11 changed nothing.
The problem in my case was wrong slot number in provider configuration. The selected slot was labeled as "accelerator" which does not support the creation of "private objects" - from HSM documentation.
After switching to a different slot, key generation and storage into keystore works.

Attempted to read or write protected memory. PKCS11Interop

I am getting Access violation exception in the highlighed line.
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I have the certificate on the hsm and the label . I am building my application as x64
public void getCertificateFromHSM(string certLabel) {
List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, certLabel));
**session.FindObjectsInit(objectAttributes);** --Exception from here
// Get search results
List<ObjectHandle> foundObjects = session.FindObjects(2);
// Terminate searching
session.FindObjectsFinal();
// Prepare list of empty attributes we want to read
List<CKA> attributes = new List<CKA>();
attributes.Add(CKA.CKA_LABEL);
attributes.Add(CKA.CKA_VALUE);
}
I am getting exception from this line session.FindObjectsInit();. I am new to pkcs11.
Any help in this regard is appreciated.
I also tried to build the application as 32 bit by passing the 32bit crypto.dll ,but in that case i am getting exception from this line in PKCS11Interop Net.Pkcs11Interop.LowLevelAPI81.Delegates.InitializeWithGetF‌​unctionList(IntPtr libraryHandle) and the exception is
Value was either too large or too small for a UInt32. OverflowExcepiton was unhandled.
You seem to be using wrong set of HighLevelAPIs. You need to use classes from Net.Pkcs11Interop.HighLevelAPI namespace without any numbers at the end.
In other words you need to use following line
using Net.Pkcs11Interop.HighLevelAPI;
in your code instead of
using Net.Pkcs11Interop.HighLevelAPI81;
See Pkcs11Interop library architecture for more info and you can also take a look at official code samples which are using Net.Pkcs11Interop.HighLevelAPI too.

GreenDAO really simple query

I want to create a very simple query to look up a sqlite db using greendao. 2 fields, one is the ID and the other 'affirmation'.
i am sorry to be such a beginner, but i am not sure how to use greendao including what to import etc.. All i have been able to do so far is add the greendao libraries but i cant find a good tutorial to just do a query. Basically i want it to be a random ID that calls up a random affirmation and return it to my main activity.. Once again i am sorry but i am really trying and getting nowhere..
Greendao is a ORM-framework. If you don't know what this means you should look up this first.
Greendao generally works as follows:
You create a java-project that generates your sourcecode for your real app. You have to include DaoCore and DaoGenerator in this project.
You add the generated sourcecode to your android-project and include DaoCore in it. DaoGemerator is not neccessary.
For examples how to generate the code and define your entities the greendao-website is a good place to go.
According to your description you need an entity with id-property and a string-property (affirmation).
In your android-project you then use the DevOpenHelper to get a session and from the session you can get the dao (Data Access Object) for your entity. The dao includes the very basic query to load data by id (load ()).
Please notice that the DevOpenHelper is only meant for development process. For your final release you should extend OpenHelper and costumize your actions to be taken on DB-schema update.
Here is some example code I have in my application.
DaoHelper.getInstance().getDaoSession().clear();
OperationDao dao = DaoHelper.getInstance().getDaoSession().getOperationDao();
String userId = "some id"
WhereCondition wc1 = new WhereCondition.PropertyCondition(OperationDao.Properties.UserId,
" = " + userId);
WhereCondition wc2 = new WhereCondition.PropertyCondition(OperationDao.Properties.Priority,
" > " + 4);
// Uncached is important if your data may have changed recently.
List<Operation> answer = dao.queryBuilder().where(wc1, wc2).listLazyUncached();
This is a decent tutorial on how to learn greendao. Make sure you follow the links to the further parts.
You can use:
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
yourDao = daoSession.getYourDao();
Random() random = new Random();
List<YourObject> objects = yourDao.loadAll();
YourObject yourObject = objects.get(random.nextInt(objects.size());

How can l use Entity Framework without App.config

I want to use Entity Framework without app.config file.
I want to define a string variable Connection String in my code and use that to connect to the database.
Please show me the way if it is possible.
You're not mentioning what approach you're using (database-first, model-first, code-first) - but basically, in the end, you need to define a string variable and assign it a valid EF connection string
string myConnectionString = "...(define a valid EF connection string here)......";
Example for database-first approach:
string myConnectionString = #"metadata=.\Model1.csdl|.\Model1.ssdl|.\Model1.msl;provider=System.Data.SqlClient;provider connection string="";data source=.;initial catalog=test;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""";
and then use that to create your ObjectContext (database- and model-first) or DbContext (code-first)
using(ObjectContext ctx = new ObjectContext(myConnectionString))
{
// do your EF magic here.....
}
But quite honestly - I think this is a really bad idea since this makes it impossible for you to move your application to another machine - no one else can install and run this, since the connection string is hard-coded into your C# code..... the whole point of having config files is so that you can change / adapt things like connection strings so that they are not tied to a single machine/location but can be adapted to the particular needs of a given user / customer....