Connecting to LDAP pgp key servers in Android

As of version 1.1.2 DidiSoft OpenPGP Library for Android provides functionality to retrieve OpenPGP keys from LDAP servers that support the pgp directory schema.

Keys can be retrieved by hexadecimal Key Id, or by part or the whole User Id.

System requirements

This functionality relies on the UnboundId LDAP SDK as there is no JNDI support in the Android Java SDK.

You will have to include theĀ unboundid-ldapsdk-se.jar file with your Android application as well.

LDAP connection Example

Below is an example that shows how to get a key from an LDAP server and import it afterwards into com.didisoft.KeyStore object.

import android.app.Activity;
import android.widget.TextView;
import com.didisoft.pgp.net.LDAPClient;
 
public class LDAPDemo extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  TextView tv = new TextView(this);
 
  // connect to LDAP server that supports pgp schema
  LDAPClient ldap = new LDAPClient("keyserver.pgp.com");
 
  // search by part or the whole User Id
  byte[] keyBytes = {};
  try {
     keyBytes = ldap.getKeyByUserId("myemail@mysite.com");
  } catch (IOException e){
     tv.append("Network connection error: " + e.getMessage());
  };
 
  try {
     tv.append(new String(keyBytes, "ASCII"));
  } catch (UnsupportedEncodingException e){
     tv.append("ASCII encoding is not supported?");
  };
 
  setContentView(tv);
 }
}

Timeouts

Connection timeouts can be set in order to limit the execution time of the network operation perfomed by the LDAPClient class. The value is measured in milliseconds. Here is an example how to set the timeout to 5 seconds:

LDAPClient ldap = new LDAPClient("10.0.2.2");
ldap.setTimeout(5*1000); // 5 seconds.

Exception handling

The methods of the class com.didisoft.pgp.net.LDAPClient throw java.io.Exception in case of a network connection problem.

Summary

This article illustrated how to retrieve an OpenPGP key from an LDAP pgp key server. You may also be interested in checking the Java tutorialĀ https://www.didisoft.com/java-openpgp/examples/exchange-keys-with-pgp-ldap-servers/

List of methods:

LDAPClient.getKeyByUserId Retrieves a key from an LDAP server searching by User Id
LDAPClient.getKeyByKeyIdHex Retrieves a key from an LDAP server searching by hexadecimal Key Id
LDAPClient.getKeyByKeyId Retrieve a key from an LDAP server searching by Key Id