Friday, February 05, 2010

Android: Trusting SSL certificates

We use a self-signed SSL certificate for the test version of our backend web service. Since our certificate isn't signed by a CA that Android trusts by default, we need to add our server's public certificate to our Android app's trusted store.

These same instructions apply to trusting a custom CA, except you'd get the public certificate directly from the CA instead of from a server.

Required tools:

1. Grab the public certificate from the server you want to trust. Replace ${MY_SERVER} with your server's address.

echo | openssl s_client -connect ${MY_SERVER}:443 2>&1 | \
 sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > mycert.pem

For example, here's the PEM-encoded public certificate from google.com:

-----BEGIN CERTIFICATE-----
MIIDITCCAoqgAwIBAgIQL9+89q6RUm0PmqPfQDQ+mjANBgkqhkiG9w0BAQUFADBM
MQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3RlIENvbnN1bHRpbmcgKFB0eSkg
THRkLjEWMBQGA1UEAxMNVGhhd3RlIFNHQyBDQTAeFw0wOTEyMTgwMDAwMDBaFw0x
MTEyMTgyMzU5NTlaMGgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlh
MRYwFAYDVQQHFA1Nb3VudGFpbiBWaWV3MRMwEQYDVQQKFApHb29nbGUgSW5jMRcw
FQYDVQQDFA53d3cuZ29vZ2xlLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
gYEA6PmGD5D6htffvXImttdEAoN4c9kCKO+IRTn7EOh8rqk41XXGOOsKFQebg+jN
gtXj9xVoRaELGYW84u+E593y17iYwqG7tcFR39SDAqc9BkJb4SLD3muFXxzW2k6L
05vuuWciKh0R73mkszeK9P4Y/bz5RiNQl/Os/CRGK1w7t0UCAwEAAaOB5zCB5DAM
BgNVHRMBAf8EAjAAMDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly9jcmwudGhhd3Rl
LmNvbS9UaGF3dGVTR0NDQS5jcmwwKAYDVR0lBCEwHwYIKwYBBQUHAwEGCCsGAQUF
BwMCBglghkgBhvhCBAEwcgYIKwYBBQUHAQEEZjBkMCIGCCsGAQUFBzABhhZodHRw
Oi8vb2NzcC50aGF3dGUuY29tMD4GCCsGAQUFBzAChjJodHRwOi8vd3d3LnRoYXd0
ZS5jb20vcmVwb3NpdG9yeS9UaGF3dGVfU0dDX0NBLmNydDANBgkqhkiG9w0BAQUF
AAOBgQCfQ89bxFApsb/isJr/aiEdLRLDLE5a+RLizrmCUi3nHX4adpaQedEkUjh5
u2ONgJd8IyAPkU0Wueru9G2Jysa9zCRo1kNbzipYvzwY4OA8Ys+WAi0oR1A04Se6
z5nRUP8pJcA2NhUzUnC+MY+f6H/nEQyNv4SgQhqAibAxWEEHXw==
-----END CERTIFICATE-----

2. Android has built-in support for the Bouncy Castle keystore format (BKS). Put Bouncy Castle's jar in your classpath, and create a keystore containing only your trusted key.

export CLASSPATH=bcprov-jdk16-145.jar
CERTSTORE=res/raw/mystore.bks
if [ -a $CERTSTORE ]; then
    rm $CERTSTORE || exit 1
fi
keytool \
      -import \
      -v \
      -trustcacerts \
      -alias 0 \
      -file <(openssl x509 -in mycert.pem) \
      -keystore $CERTSTORE \
      -storetype BKS \
      -provider org.bouncycastle.jce.provider.BouncyCastleProvider \
      -providerpath /usr/share/java/bcprov.jar \
      -storepass ez24get

3. Create a custom Apache HttpClient that uses your custom store for HTTPS connections.

import android.content.Context;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;

import java.io.InputStream;
import java.security.KeyStore;

public class MyHttpClient extends DefaultHttpClient {

  final Context context;

  public MyHttpClient(Context context) {
    this.context = context;
  }

  @Override protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(
        new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", newSslSocketFactory(), 443));
    return new SingleClientConnManager(getParams(), registry);
  }

  private SSLSocketFactory newSslSocketFactory() {
    try {
      KeyStore trusted = KeyStore.getInstance("BKS");
      InputStream in = context.getResources().openRawResource(R.raw.mystore);
      try {
        trusted.load(in, "ez24get".toCharArray());
      } finally {
        in.close();
      }
      return new SSLSocketFactory(trusted);
    } catch (Exception e) {
      throw new AssertionError(e);
    }
  }
}

That's it! If you think this kind of stuff is fun, Square is hiring.

Friday, August 14, 2009

Tomorrow is the big day.

Friends,

Tomorrow morning, I'll swim 1.5 miles from Alcatraz to SF to benefit the American Liver Foundation. I set my fund raising goal at $10k, and I'm already 30% of the way there. If you've already donated, thank you! If not, please sponsor me.

Thanks,
Bob

Wednesday, May 20, 2009

It's in the JCP's hands now.

This morning, Google and SpringSource submitted an updated version of the aforementioned @Inject proposal to the JCP. In response to popular demand, we expanded the proposal's scope to include a low-level build-time and run-time configuration API. You might think of the new API as a type-safe analogue to JNDI and @Resource. Having a central integration point for DI configuration means you can use multiple configuration approaches in a single application without suffering from the-chicken-or-the-egg problem; anyone who has tried to use more than one DI framework in the same application knows that deciding which framework to initialize first can be problematic to say the least.

Our goals are to enable portable applications and to spark further innovation in the DI configuration space. By making it easier to use multiple configuration approaches with the same tools and in the same application, we lower the barriers to entry and adoption for new approaches.

We've added the following paragraphs to the JSR proposal's introduction:

A programmer configures a dependency injector so it knows what to inject. Different configuration approaches make sense in different contexts. One approach is to search the classpath for dependency implementations, avoiding the need for the programmer to write explicit code. This approach could be useful in quick-and-dirty prototypes. A programmer working on a large, long-lived application might prefer a more explicit, compartmentalized approach. For example, the programmer could write XML that tells the injector to inject an EJB client proxy named "NetworkTimeSource" when a class needs a TimeSource:
  <binding type="TimeSource" ejb="NetworkTimeSource"/>

It often makes sense to use more than one configuration mechanism in the the same application. For example, a quick and dirty prototype might grow into a real application, and the programmer could incrementally migrate to a more maintainable configuration. As another example, a program might configure some resources explicitly, while others are configured automatically based on an external XML file or database.

This JSR will standardize a low-level kernel API that can be used directly by a user or as an integration point for higher level configuration approaches. This approach enables portable Java applications without quashing innovation in dependency injector configuration.

We've rewritten the scope:

This JSR will standardize:
  1. A set of annotations for use on injectable classes
  2. A typesafe, user-friendly injector configuration API that provides an integration point for higher level dependency injection configuration approaches

And we've adjusted the time line and other parameters accordingly. Check out the full proposal.

What will the new API look like? That's for the expert group to decide, and they'll do so in an open and inclusive manner. In addition to Guice and Spring, this proposal already has support from the PicoContainer, Plexus and Tapestry IoC teams, not to mention prominent users like Tim Peierls and James Strachan, and well known API designers like Doug Lea and Josh Bloch. We'll have no shortage of expertise when it comes time to assemble the group.

Guice 2 already provides a great foundation for extensions and tools. The Guice team is excited to start with a clean slate and apply the lessons we've learned over the past few years. This time around, we'll be able to work with the platform instead of around it. As a member of the JSR-294 expert group, I'm eager to align our dependency injection efforts with the module support coming in Java 7. JSR-294 modules will enable sharing types, and this proposed JSR will build on that foundation and enable sharing instances.

Tuesday, May 19, 2009

Guice²

After two years in the making, it's official. We've released Guice 2! Here's Jesse's announcement from the Google Code Blog:

Two years ago, Bob Lee and Kevin Bourrillion open sourced Google Guice 1.0, a lightweight Java dependency injection framework. Guice takes the pain out of writing and maintaining Java applications big and small. Guice has gained a great deal of traction both inside and outside of Google. Almost every Java-based application at Google is also a Guice-based application; the list includes AdWords, Google Docs, Gmail, and even YouTube. Open source users run Guice in everything from file-sharing software to ATMs. They've even written two books about this Jolt-award-winning framework.

Today, we're releasing Guice 2. The minimally-sized API extensions introduced by Guice 2 will have a majorly positive impact on the size and maintainability of your code. We closely scrutinized each addition, carefully balancing maintainability and flexibility. Here are a few of my favorite new features:

  • Provider methods eliminate the boilerplate of manually-constructed dependencies.
  • Module overrides allow you to tweak a production module for a unit test or QA deployment.
  • Private modules enable compartmentalized configuration, simplifying module reuse.
Guice works with Java SE, Java EE, Google App Engine, Android, and even Google Web Toolkit (via GIN).

References
Guice 2.0 Release Notes
Downloads
User's Guide
Javadoc

In addition to the user-facing features mentioned by Jesse, Guice 2 provides an extensive service provider API that enables first class extensions like James Strachan's GuiceyFruit and makes writing tools like Guice Grapher a snap.

Thanks, Jesse, for all of your hard work on this release. Special thanks goes to our users for being patient and building a vibrant community around Guice.

If you're interested in learning more, don't miss Jesse and Dhanji's Guice 2 talks at Google I/O and JavaOne.

Tuesday, May 05, 2009

Announcing @javax.inject.Inject

I'm proud to announce a new dependency injection specification backed by both Google Guice and Spring. You can catch the official announcement over on the Google Code Blog:

Five years ago, Spring 1.0 brought Java dependency injection into the mainstream. Three years later, Google Guice 1.0 introduced annotation-based dependency injection and made Java programming a little easier. Since then, developers have had to choose between a) writing external configuration or b) importing vendor-specific annotations.

Today, we hope to give developers the best of both worlds. Google Guice and SpringSource have partnered to standardize a proven, non-controversial set of annotations that make injectable classes portable across frameworks. At the moment, the set of specified annotations consists of:

  • @Inject - Identifies injectable constructors, methods, and fields
  • @Qualifier - Identifies qualifier annotations
  • @Scope - Identifies scope annotations
  • @Named - String-based qualifier
  • @Singleton - Identifies a type that the injector only instantiates once
One additional interface is specified for use in conjunction with these annotations:
  • Provider - Provides instances of a type T. For any type T that can be injected, you can also inject Provider.
You can check out an early draft of the specification. We deliberately left external dependency configuration out, so as not to quash ongoing innovation. We haven't formally submitted this standard to the JCP yet, but we plan to do so shortly. Standards wonks can read a draft of our JSR proposal.

The expert group will be inclusive and will work in the open. For example, our mailing list is publicly readable, and we host the specification at Google Code. Several industry players have already expressed interest in supporting this effort. Contact us if you'd like to help out.

This specification will address the last shortcoming of annotation-based dependency injection. You no longer have to import vendor-specific annotations.

Our hope is that this specification will not only improve interoperability between existing dependency injection frameworks and unify the Java community, but it will also lower the barrier to entry for new injector implementations and foster even more innovation in this space.

I'd like to thank Paul Hammant, Doug Lea, Tim Peierls, James Strachan, Hani Suleiman, and Jason van Zyl for their early reviews and official support. Special thanks goes to our partner in this endeavor SpringSource, especially Rod Johnson, and my fellow Googlers and Guicers Josh Bloch, Jesse Wilson, Kevin Bourrillion, and Dhanji Prasanna.

Monday, October 13, 2008

How to create simple Amazon affiliate links

In case you didn't know, Amazon will pay you to recommend their products. If you're going to link to a product anyway, why not take credit? Amazon provides all sorts of fancy tools and flashy widgets to help you advertise their products, but creating a basic URL through their web interface isn't straightforward.

In hope of simplifying the process, I followed some 3rd party instructions I found for hacking together your own referral URLs, but they didn't work. I asked Amazon instead, and here are the official instructions:

If you would like to link directly to an item's detail page using a simple text link, use the following format to construct your links:

http://www.amazon.com/dp/ASIN/?tag=your_Associates_ID

To make this link functional, replace "ASIN" with the 10-digit ISBN or ASIN of the product, and replace "your_Associates_ID" with your Associates ID or tracking ID. However, you would not be able to link to a search results page on Amazon.com.

If you would like to link to the Amazon.com homepage, you can use the following format:

http://www.amazon.com/?tag=your_Associates_ID

To make this link functional, replace "your_Associates_ID" with your Associates ID or tracking ID.

An item's ISBN/ASIN is listed on the item's detail page. For example, follow the link below, and then scroll down to the section labeled Product Details to find the ISBN (0439434866) for "Harry Potter Paperback Boxed Set."

http://www.amazon.com/exec/obidos/tg/detail/-/0439434866/

I don't make much money from referrals, but I do enjoy taking my payments in the form of Amazon gift certificates and buying myself a little something from my wish list every now and then.

Monday, September 22, 2008

Taken with my 'gPhone'

I've been playing around with the 3 megapixel camera on my Android-based G1. Like any phone camera, you need a little diligence, a lot of light, and a steady hand.

Walking home

Mask

Stanford

Fountain

Nested

For the best results, tap and release the shutter button, and then hold the phone still until it takes the picture a second or so later. It's not necessary to hold down the button until the picture takes. Holding down the button will contract the muscles in your hand and make it more difficult to keep the phone steady.

Click here for more photos.