Code sample: Sign data using private key on smart card and verify on the device
import java.util.Enumeration;
import net.rim.device.api.crypto.Crypto;
import net.rim.device.api.crypto.CryptoException;
import net.rim.device.api.crypto.NoSuchAlgorithmException;
import net.rim.device.api.crypto.PrivateKey;
import net.rim.device.api.crypto.RandomSource;
import net.rim.device.api.crypto.certificate.*;
import net.rim.device.api.crypto.keystore.*;
import net.rim.device.api.system.Application;
public class SignDataPrivate extends Application
{
public static void main(String[] args)
{
SignDataPrivate app = new SignDataPrivate();
KeyStore keyStore;
try
{
keyStore = DeviceKeyStore.getInstance();
KeyStoreData ksData = null;
AssociatedDataKeyStoreIndex index = new AssociatedDataKeyStoreIndex(
AssociatedData.SMART_CARD_KEY);
keyStore.addIndex(index);
Enumeration enumeration = keyStore.elements( index.getID() );
while( enumeration.hasMoreElements() )
{
ksData = (KeyStoreData) enumeration.nextElement();
Certificate certificate = ksData.getCertificate();
if( ( certificate == null ) || !ksData.isPrivateKeySet())
{
continue;
}
if( !( certificate.queryKeyUsage(
KeyUsage.DIGITAL_SIGNATURE ) != KeyUsageResult.NOT_ALLOWED ) )
{
continue;
}
}
byte [] randomData = new byte[ 64 ];
RandomSource.getBytes( randomData );
PrivateKey privateKey = ksData.getPrivateKey( null );
byte [] signature = Crypto.sign(randomData,0,randomData.length,
privateKey,null,"X509" );
if(!Crypto.verify(randomData, 0, randomData.length,
keyStoreData.getPublicKey(), "X509", signature, 0 ))
{
return false;
}
}
catch (KeyStoreRegisterException e)
{
}
catch( NoSuchAlgorithmException e )
{
}
catch( CryptoException e )
{
}
catch( IllegalArgumentException e )
{
}
}
}
Previous topic: Code sample: List smart card drivers