Sample code for 30+ languages & platforms
Android™

Duplicate Java Secure Token Creation

See more RSA Examples

Demonstrates how to duplicate some Java code that creates an RSA signature to create a base64 token.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    // This requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // This example duplicates the following Java code:

    // public X509Certificate2 cert = new X509Certificate2(@"Some path to p12/p12file_name.p12","Password_for_p12"); 
    // 
    // public string GenerateSignToken(double timeValidityMin){ 
    //   string equalsSign = ":="; 
    //   string timeCreated = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz"); 
    //   string tokenTimeInfo = "validityTimeMinutes" + equalsSign + timeValidityMin + ";"+"timeCreated" + equalsSign + timeCreated; 
    //   string signature = SignData(tokenTimeInfo); 
    //   string secureToken = tokenTimeInfo + ";" + "signature" + equalsSign + signature; 
    //   return Base64UrlEncode(secureToken); 
    // } 
    //  
    // public string SignData(string stringToSign){ 
    //   byte[] dataToSign = Encoding.UTF8.GetBytes(stringToSign); 
    //   RSACryptoServiceProvider privKey = (RSACryptoServiceProvider)cert.PrivateKey; 
    //   CspKeyContainerInfo containerInfo = new RSACryptoServiceProvider().CspKeyContainerInfo; 
    //   CspParameters cspparams = new CspParameters(containerInfo.ProviderType, containerInfo.ProviderName, privKey.CspKeyContainerInfo.KeyContainerName); 
    //   privKey = new RSACryptoServiceProvider(cspparams); 
    //   string id = CryptoConfig.MapNameToOID("SHA256"); 
    //   byte[] sign = privKey.SignData(dataToSign, id); 
    //   bool res = privKey.VerifyData(dataToSign, id, sign); 
    //   return Convert.ToBase64String(sign).Replace('+', '-').Replace('/', '_').Replace("=", ""); 
    // } 
    //  
    // private static string Base64UrlEncode(string input){ 
    //   var inputBytes = Encoding.UTF8.GetBytes(input); 
    //   return Convert.ToBase64String(inputBytes).Replace('+', '-').Replace('/', '_').Replace("=", ""); 
    // } 

    CkDateTime dt = new CkDateTime();
    dt.SetFromCurrentSystemTime();
    String timeCreated = dt.getAsTimestamp(true);

    // Such as 2019-04-01T19:35:44-05:00
    Log.i(TAG, timeCreated);

    CkStringBuilder sbToken = new CkStringBuilder();
    sbToken.Append("validityTimeMinutes:=10.0;timeCreated:=");
    sbToken.Append(timeCreated);

    CkCert cert = new CkCert();
    success = cert.LoadPfxFile("Some path to p12/p12file_name.p12","Password_for_p12");
    if (success != true) {
        Log.i(TAG, cert.lastErrorText());
        return;
        }

    CkRsa rsa = new CkRsa();
    success = rsa.SetX509Cert(cert,true);
    if (success != true) {
        Log.i(TAG, rsa.lastErrorText());
        return;
        }

    rsa.put_EncodingMode("base64url");

    String signature = rsa.signStringENC(sbToken.getAsString(),"sha256");
    if (rsa.get_LastMethodSuccess() == false) {
        Log.i(TAG, rsa.lastErrorText());
        return;
        }

    sbToken.Append(";signature:=");
    sbToken.Append(signature);

    // Base64URL encode the result
    sbToken.Encode("base64url","utf-8");
    String token = sbToken.getAsString();

    Log.i(TAG, token);

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}