Generating PGP keys compatible with PGP Desktop using BouncyCastle

This is just a note to remind myself on how to do this in the future…
Like the title suggested, all I want to do is to generate key pairs (using BouncyCastle library) that can be used for encryption in PGP Desktop. This takes a while to figure out because one very crucial information is being hidden by BouncyCastle. I have to google for 2 days to dig out this info – this very important link that they decided not to put in their FAQ: http://www.bouncycastle.org/wiki/display/JA1/PGP+Questions

Apparently for later version of PGP Desktop, if you generate an RSA key without a subkey, you can only use it for signing, and not for encryption (read this).

So, we start off like usual…

       
// add provider
Security.addProvider(new BouncyCastleProvider());

// get keypair generator
//parameter 1: key type algorithm =  RSA, DSA
//parameter 2: provider = BC (BouncyCastle)
KeyPairGenerator  keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");        \

// specify key size
// encryption key size: 1024-4096
keyPairGen.initialize(2048);

// generate key pair
KeyPair keyPair = keyPairGen.generateKeyPair();

Then comes the tricky bit where you have to generate hashed subpackets…


PGPSignatureSubpacketGenerator    hashedGen = new PGPSignatureSubpacketGenerator();

hashedGen.setKeyFlags(true, KeyFlags.ENCRYPT_STORAGE);
hashedGen.setPreferredCompressionAlgorithms(false, 
    new int[] { CompressionAlgorithmTags.ZLIB, 
                    CompressionAlgorithmTags.ZIP});

hashedGen.setPreferredHashAlgorithms(false,  
    new int[] { HashAlgorithmTags.SHA256,
                    HashAlgorithmTags.SHA384, 
                    HashAlgorithmTags.SHA512} );

hashedGen.setPreferredSymmetricAlgorithms(false, 
    new int[] { SymmetricKeyAlgorithmTags.AES_256, 
                    SymmetricKeyAlgorithmTags.AES_192, 
                    SymmetricKeyAlgorithmTags.AES_128, 
                    SymmetricKeyAlgorithmTags.CAST5, 
                    SymmetricKeyAlgorithmTags.DES});

//add hashed subpacket to secret key 
PGPSecretKey    secretKey = new PGPSecretKey(
	PGPSignature.DEFAULT_CERTIFICATION, 	//certificationLevel
	PublicKeyAlgorithmTags.RSA_GENERAL, 	//algorithm
	publicKey, 		//java.security.PublicKey
	privateKey, 	//java.security.PrivateKey
	new Date(), 	//time
	identity, 		//id
	SymmetricKeyAlgorithmTags.AES_256, 	//encAlgorithm: AES_128, AES_192, AES_256, BLOWFISH, CAST5, DES, IDEA, NULL, SAFER, TRIPLE_DES, TWOFISH         
	passPhrase, 		//passPhrase
	hashedGen.generate(),	//hashedPcks 	PGPSignatureSubpacketVector
	null, 				//unhashedPcks	PGPSignatureSubpacketVector
	new SecureRandom(), 	//java.security.SecureRandom
	"BC");				//provider

This will produce key with selected Hash, Cipher and Compression in PGP Desktop :

From Work Screen Caps

Android – Newbie Gotchas

So I was doing this tutorial to make a simple music player in Android, and came across lots of problems, cause they are using SDK version M3, while I’m using SDK version 1.1. Lots have been changed since then….

1. Signature for Notification has been changed. It used to be:

Notification(Context, int, CharSequence, long, CharSequence, CharSequence, Intent, int, CharSequence, Intent)

and now it’s:

Notification(int, CharSequence, long)

2. There is no “-useaudio” option when u run Android emulator using SDK ver1.1. Your application will still run without this option.

3. “class” has been substitute with “android:name” when you are writting your android.manifest file. It used to be:

<service class=".MDService" android:process=":remote" />

and now it’s:

<service android:name=".MDService" android:process=":remote" />

4. When you write your layout XML, remember that “id” needs to be changed to “android:id”. It used to be:

<ListView id="@id/android:list"/>

and now it’s:

<ListView android:id="@id/android:list" />

5. You need to catch or throw RemoteException when calling a Service object.

6. Whenever you call a Notification object, you always need to .setLatestEventInfo(), otherwise you will get an IllegalArgumentException during runtime.


Notification notification = new Notification(R.drawable.playbackstart, file, System.currentTimeMillis());
ComponentName comp = new ComponentName(this.getPackageName(), getClass().getName());
Intent intent = new Intent().setComponent(comp);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
notification.setLatestEventInfo(this, "Title", "Text", pendingIntent);
nm.notify(NOTIFY_ID, notification);

_________________________________________________________

Related links:
Id on ListView
Notification and setLatestEventInfo

Sun Application Server 8.2 + Hibernate Gotchas!

For Hibernate to work in Sun Application Server 8.2, we need to change Sun App’s server.policy. Here is what we have to add:


grant {
  // Permission for cglib part of Hibernate framework
  permission java.lang.RuntimePermission "getProtectionDomain";
  permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
};

In Sun Application Server 8.2 Platform Edition, this server.policy file is located at [Sun App Install Path]/domains/[domain-name]/config folder. After applying this modification, the server needs to be restarted.

In Sun Application Server 8.2 Enterprise Edition, server.policy files exist in the domain and in each node-agents. Any alterations to configuration files, such as server.policy need to be made in the domain, rather than the node agent. If they are made in the node agent, then they will be overwritten the next time that the server instance is restarted. For making a change to a config file the approach would be:
1. stop the server instances
2. stop the node agent
3. stop the domain
4. change the config file(s) in the domain
5. start the domain
6. start the node agent (The node agent will start the server instances.)

If changes in the domain’s server.policy doesn’ get replicated in the node agents, you can use the ‘touch’ command on the file in the domain and restart the instance. ‘touch’ command updates the timestamp on the file. The node agent uses the timestamp on the file to work out whether it’s newer than in the server instance.

Failing to make changes in the server.policy will cause
java.lang.NoClassDefFoundError (without any detail which library it’s missing)

JCAPS Web Service – Creating Fault Message

1. In your JCD, throw Exception
2. In you BPEL, add “catch all exception” by dragging the icon into your BPEL (see image below)

From Work Screen Caps

3. Click on the “catch”, and then click on “show property sheet” button. Select the appropriate Exception name and output from the select drop down options.

From Work Screen Caps

4. Drag “throw” icon inside your “catch”, and then drag the arrow connecting from your “catch” to your “throw”. Right click on the arrow and select add business rule. (see image below)

From Work Screen Caps

5. Add the appropriate business rule. Below is an example.

From Work Screen Caps

6. Click on “throw” and then click on “show property sheet” button. Select exception name and output from the drop down options.

From Work Screen Caps

7. The important thing is when u check your code, these exist:

From Work Screen Caps

Convert java.util.Date to JCAPS DateTime Object

The only reference that I found for doing this is from here.

My own code to do the reverse:


com.stc.codegen.util.TypeConverter typeConverter = new com.stc.codegen.util.impl.TypeConverterImpl();
java.util.Date now = new java.util.Date();
String textFormatDate = "yyyyMMdd hh:mm";
java.text.SimpleDateFormat defaultDateTimeFormat = new java.text.SimpleDateFormat( textFormatDate );
String nowString = defaultDateTimeFormat.format( now );
com.stc.otd.xsd.datatype.DateTime dateTime = typeConverter.stringToDateTime( nowString, "yyyyMMdd HH:mm", false, "" );
myOtd.setEffectiveDate( dateTime );

Tomahawk datatable disaster

Spent 2 days to figure what went wrong with my t:datatable not displaying the updated list after submitting an action. It keeps on displaying old data (data before any action was performed).

My jsp:

<t:dataTable
preserveDataModel=”false”
preserveRowStates=”false”
binding=”#{oit.dataTable}”
value=”#{oit.tasksInError}”
var=”tie”
styleClass = “resultTable”
cellspacing=”1″ cellpadding=”0″
id=”tieTable”
renderedIfEmpty=”false”>

<t:column headerstyleClass=”resultTableHeader”
styleClass = “resultTablePurpleLight textLeft” >

<h:selectBooleanCheckbox immediate=”true”
rendered=”#{tie.displayCheckbox}”
id=”selectError”
value=”#{tie.checkBoxSelected}”/>

<h:inputHidden id=”errorId” value=”#{tie.errorID}”/>

<f:facet name=”header”>
<h:outputText value=”#{msgs.select}”/>
</f:facet>

</t:column>

</t:dataTable>

After banging my head really hard on the wall (yeah right..), I managed to isolate the bug. It only happens when the list only contain one single item. And after googling around, I found a quick temporary solution!! Hooraaaah~~ I still don’t understand this bug. But the fixed shown in the mailing list is sufficient for now.

The magic part is the 2 lines shown in bold below. Whenever you iterate through a datatable, you need to set row index back to its original value.

My backing bean:

public void errorAction(String action) {
/* Save the current row index. */
int currentRowIndex = dataTable.getRowIndex();

for (int i = 0; i < dataTable.getRowCount(); i++) { dataTable.setRowIndex(i); ... } /* Restore the row index. */ dataTable.setRowIndex(currentRowIndex); }

Note: This application is using Tomahawk 1.1.6, JSF 1.1, running on Sun Application server 8.2.

How to use Oracle XMLType in Hibernate

  • Edit your Hibernate Mapping XML

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd” >

<hibernate-mapping>

<class
name=”mypackage.MyClass”
table=”MYTABLE”
>

<id
name=”myId”
type=”java.lang.Long”
column=”MY_ID”
>

<generator class=”sequence”>
<param name=”sequence”>my_id_seq</param>
</generator>

</id>

<property
name=”myXml”
type=”mypackage.HibernateXMLType”
column=”MY_XML”
/>

</class>

</hibernate-mapping>

  • Edit your Java Persistence Object

public class MyClass implements Serializable {

private Document myXml;

public Document getMyXml() {
return myXml;
}

public void setMyXml(Document messageXml) {
this.myXml = messageXml;
}
}

  • Add required JARS
    You would need xdb.jar, xmlparserv2.jar, and ojdbc14.jar

Continue reading

Eclipse Import Problem

//Lesson learned today..
Apparently it is a known problem that Eclipse messed up with import @_@ So bad that other developer choose to switch IDE (not gonna happen to me). The worst thing is that it can’t recognize class from the same package *insert words to express frustration here*

This happened to me when I am using Eclipse Europa (Eclipse 3.3). I thought they should have fixed this problem by now!!

Quick hack to fix this: http://www.brunningonline.net/simon/blog/archives/001748.html

Eclipse regularly seems to forget that imports exist. I find this happens a lot when I edit and then save a file in my project.
My work-around: remove and then add the JRE library

1. right-click on your project folder
2. click properties
3. click on the Libraries tab
4. click on the JRE
5. click remove
6. click OK
7. repeat 1-3
8. click Add library
9. click JRE ssystem library
10. click finish
11. click OK

This seems to refresh the build path and sort out the problem temporarily. You can be sure though that it will not go away for good. :(