Store keypair in the device in codename one app - codenameone

I'm currently trying the codename one framework and I would like to know if there was a way to store keypair generated by the bouncy castle library by any chance ?
I tried to store keys using Storage and Preferences but always resulting the same Exception
java.io.IOException: Object type not supported: org.bouncycastle.asn1.pkcs.RSAPublicKey value: org.bouncycastle.asn1.pkcs.RSAPublicKey#581c
at com.codename1.io.Util.writeObject(Util.java:481)
at com.codename1.io.Storage.writeObject(Storage.java:227)

You need to save the byte array related to the key and not the key object. E.g.
byte[] b = key.toASN1Primitive().getEncoded();
And to restore:
RSAPublicKey key = RSAPublicKey.getInstance(b);
Haven't tried it but looking at the code I think this should work.

Related

Access Shared Preferences externally / Store a value into a new file and access it externally

I have the two following methods and I am using them to store a special value locally and be able to access it on application restart:
(Store value locally:)
private void SaveSet(string key, string value)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
ISharedPreferencesEditor prefEditor = prefs.Edit();
prefEditor.PutString(key, value);
// editor.Commit(); // applies changes synchronously on older APIs
prefEditor.Apply(); // applies changes asynchronously on newer APIs
}
(Read it again:)
private string RetrieveSet(string key)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
return prefs.GetString(key, null);
}
This works perfectly. Now is it possible to access and edit this Shared Preferences externally? Unfortunately, I cannot find any file when searching in folder
Phone\Android\data\com.<company_name>.<application_name>\files
nor anywhere else. I want / try to edit this value from my computer, after connecting the phone to it. Is this possible?
Alternatively: Can anyone maybe show me how to create a new file in the given path above, write/read it programmatically and how it stays there, even if application is closed / started again? So I can then edit this file with my computer anyhow?
I tried it with the following code, but unfortunately it doesn't work / no file is created or at least i cannot see it in the given path above:
//"This code snippet is one example of writing an integer to a UTF-8 text file to the internal storage directory of an application:"
public void SaveValueIntoNewFile(int value)
{
var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "newFile.txt");
using (var writer = System.IO.File.CreateText(backingFile))
{
writer.WriteLine(value.ToString());
}
}
Would be very happy about every answer, thanks in advance and best regards
What you're looking for is where Android stores the Shared Preference file for applications that make use of it's default PreferenceManager.
I'd refer to this SO post which answers your question pretty well
SharedPreferences are stored in an xml file in the app data folder,
i.e.
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
or the default preferences at:
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
SharedPreferences added during runtime are not stored in the Eclipse
project.
Note: Accessing /data/data/ requires superuser
privileges
A simple method is to use Android Device Monotor,you can open it by clicking Tools--> android-->Android Device Monotor...
For example:
The path in my device is as follows:
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
And we notice three buttons in the upper right corner of the picture.
The first one is used toPull a file from the device,the second one is used to Push a file onto the device,and the last one is used to delete the preferences.xml file.
So we can pull the preferences.xml file from current device to our computer and edit it as we want, and then push the updated preferences.xml to the folder again.Then we will get the value of preferences.xml file .

How to retrieve images from database in an enterprise java bean? (using JPAs and JSP)

My problem is the following: so I have a database that has some customers stored in it. For every customer I added a picture like this:
INSERT INTO ITSO.CUSTOMER (TITLE,FIRST_NAME,LAST_NAME,SSN,IMAGE) VALUES ('Mr','Henry','Cui','111-11-1111', LOAD_FILE('D:/Workspace8/Images/11.jpg'));
How can I retrieve these pictures in an Enterprise java bean? ( I have to mention I am using JPAs). Are the queries a solution?
#NamedQuery(name="getImageForCustomer", query="select image from Customer c where c.ssn=?1")
Do I need to store my picture in a different way?
In the EJB I have this method getCustomer(). Can I add another argument, something like Byte[] image??
public Customer getCustomer(String ssn) throws ITSOBankException {
System.out.println("getCustomer: " + ssn);
try {
return entityMgr.find(Customer.class, ssn);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
throw new ITSOBankException(ssn);
}
My plan is to display the image in a JSP afterwards, using a servlet and an EJB injection.
I would be so grateful if someone can help me!!!
(It's for learning purpose)
First of all, storing image in database is not very good practice. Though it is sufficient for learning purposes, in real application consider storing images in file system or cloud service of your choice and store only path or link to image.
But back to your question.
In your Customer JPA class, you can define field for image annotated with javax.persistence.Lob annotation:
#Lob
private byte[] image;
...and your image data will be loaded into image byte array field by JPA.
To display image on JSP page you have to implement servlet, which will provide image data based on customer id (for example /image?customerId=10). Here is a good example how to implement such a servlet: How to convert byte array to image

CryptoApi: Export a certificate without the private key?

I have generated a self signed certificate using the CertCreateSelfSignCertificate function. This yields a PCCERT_CONTEXT.
How can I export the certificate stored in the PCCERT_CONTEXT variable with only the public key? I want to do this, to send it to other parties in the network, so these are able to encrypt messages using the public key.
I thought this was a straight forward option, but it isnt.
No need for a pfx.
The certificate is present inside the structure CERT_CONTEXT : just save the content of the buffer pointed by the member pbCertEncoded and whose length is the value of the member cbCertEncoded.
Moreover, the public key from this certificate is directly present in the CERT_CONTEXT structure : pCertInfo->SubjectPublicKeyInfo. For example, you can import it using CryptImportPublicKeyInfo and then call CryptEncrypt to encrypt data.
With these two options, you have all what is needed to start encrypting messages. Of course, the private key must be kept safe to be able to decrypt encrypted data.
Looks like you will need to first put the certificate into a certificate store and then export it using PFXExportCertStoreEx passing dwFlags of 0 (i.e. not setting EXPORT_PRIVATE_KEYS).
P.S. nothing is ever straight forward when dealing with cryptography libraries, be it CryptAPI, JSSE, OpenSSL... it's always a nightmare.

Google App Engine Datastore Difficulties

I am using Google App Engine and using Google's datastore interface for a database .
My question is this , I have the following code : I have a network object that I want to either update if it exists on db , or to create if it's the first time. . For this I have to catch an exception and repeat the same code twice - it seems ugly and redundant and makes me think I'm doing something wrong .
The second thing that strikes me as odd is that there is no method I can think of that copies an object to an entity or vice versa . Am I expected to implement this myself ? It is very uncomfrotable to use the setProperty or getProperty for each property and well ...I am just wondering why there is no objectToEntity method or something of the sort.
This is how my code currently looks ...
try {
Entity network=datastore.get(KeyFactory.stringToKey(networks.get(i)._ipDigits));
//If I get here no exception was thrown - entity already exists on db.
Network contextNet= //fetch the network object from servlet context ...
network.setProperty("ip", contextNet._ip); //update the fields using setProperty - no better way??
network.setProperty("offlineUsers",contextNet._offlineUsers);
datastore.put(network);
}
//Entity doesn't exist , create a new entity and save it (while repeating the same code)...
catch (EntityNotFoundException e) {
Entity network=new Entity("network",Long.parseLong(networks.get(i)._ipDigits));
Network contextNet= // ...fetch the network object from servlet context
network.setProperty("ip", contextNet._ip);
network.setProperty("offlineUsers",contextNet._offlineUsers);
datastore.put(network);
}
You don't have to get and put the entity in order to update it. If you know the ID of the entity you can just put it. If it exists it will be updated, if not it will be created.
Use objectify to automatically map your classes to entities.

Windows Phone 7 App Quits when I attempt to deserialize JSON

I'm developing my first windows phone 7 app, and I've hit a snag. basically it's just reading a json string of events and binding that to a list (using the list app starting point)
public void Load()
{
// form the URI
UriBuilder uri = new UriBuilder("http://mysite.com/events.json");
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
proxy.OpenReadAsync(uri.Uri);
}
void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
var serializer = new DataContractJsonSerializer(typeof(EventList));
var events = (EventList)serializer.ReadObject(e.Result);
foreach (var ev in events)
{
Items.Add(ev);
}
}
}
public ObservableCollection<EventDetails> Items { get; private set; }
EventDetails is my class that wraps the json string. this class has to be correct because it is an exact copy of the class used by that website internally from which the json is generated...
I get the json string correctly from the webclient call (I read the memorystream and the json is indeed there) but as soon as I attempt to deserialize the string, the application exits and the debugger stops.
I get no error message or any indication that anything happen, it just stops. This happens if I type the deserialize method into the watch window as well...
I have already tried using JSON.net in fact I thought maybe it was a problem with JSON.net so I converted it to use the native deserializer in the .net framework but the error is the same either way.
why would the application just quit? shouldn't it give me SOME kind of error message?
what could I be doing wrong?
many thanks!
Firstly, the fact that you have some string there that looks like JSON does not mean that you have a valid JSON. Try converting a simple one.
If your JSON is valid, it might be that your JSON implementation does not know how to convert a list to EventList. Give it a try with ArrayList instead and let me know.
The application closes because an unhandled exception happens. If check the App.xaml.cs file you will find the code that closes your app. What you need to do is try catch your deserialization process and handle it locally. So most likely you have some JSON the DataContractJsonSerializer does not like. I have been having issue with it deserializing WCF JSON and have had to go other routes.
You may want to check to ensure your JSON is valid, just because your website likes it does not mean it is actually valid, the code on your site may be helping to correct the issue. Drop a copy of your JSON object (the string) in http://jsonlint.com/ to see if it is valid or not. Crokford (the guy who created JSON) wrote this site to validate JSON, so I would rely on it more than your site ;) This little site has really helped me out of some issues over the past year.
I ran into this same kind of problem when trying to migrate some existing WM code to run on WP7. I believe that the WP7 app crashes whenever it loads an assembly (or class?) that references something that's not available in WP7. In my case, I think it was Assembly.Load or something in the System.IO namespace, related to file access via paths.
While your case might be something completely different, the symptoms were exactly the same.
The only thing I can recommend is to go through the JSON library and see if it's referencing base classes that are not allowed in WP7. Note that it doesn't even have to hit the line of code that's causing the issue - it'll crash as soon as it tries to hit the class that contains the bad reference.
If you can step into the JSON library, you can get a better idea of which class is causing the problem, because as soon as the code references it, the whole app will crash and the debugger will stop.

Resources