Java code for retrieve Public key from Certificate
==================================================
KeyStore inputKeyStore = KeyStore.getInstance(Constents.PFX_TYPE);
FileInputStream fis = new FileInputStream(keyStoreFile);
char[] nPassword = password.toCharArray();
inputKeyStore.load(fis, nPassword);
Enumeration enumeration = inputKeyStore.aliases();
String keyAlias = null;
while (enumeration.hasMoreElements()) {
keyAlias = (String) enumeration.nextElement();
}
X509Certificate certificate = (X509Certificate) inputKeyStore
.getCertificate(keyAlias);
publicKey = certificate.getPublicKey();
And Encrypt Code using Public Key of certificate.
=================================================
Cipher cipher = Cipher.getInstance(xform); //xform:RSA/ECB/PKCS1Padding
cipher.init(Cipher.ENCRYPT_MODE, publicKey );
return cipher.doFinal(Data.getEncoded());
C# compatible Code
===================
Include Namespace of Bouncy Castle Dll.
This DLL is freely available from this link http://www.bouncycastle.org/csharp/
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
//Create file stream object to read certificate
FileStream keyStream = new FileStream(strCertificatePath, FileMode.Open, FileAccess.Read);
//Read certificate using BouncyCastle component
Pkcs12Store inputKeyStore = new Pkcs12Store(keyStream, strCertificatePassword.ToCharArray());
//Close File stream
keyStream.Close();
string keyAlias = null;
//Read Key from Alieases
foreach (string n in inputKeyStore.Aliases)
{
if (inputKeyStore.IsKeyEntry(n))
{
keyAlias = n;
break;
}
}
if (keyAlias == null)
throw new NotImplementedException("Alias");
//Read certificate into 509 format
X509Certificate certificate = (X509Certificate)inputKeyStore.GetCertificate(keyAlias).Certificate;
//Retrieve public key of certificate
AsymmetricKeyParameter publicKey = certificate.GetPublicKey();
#endregion
//Encrypting (aesKey is a byte array containing an AES key): RSA/ECB/PKCS1Padding
IAsymmetricBlockCipher cipher = new Pkcs1Encoding(new RsaEngine());
cipher.Init(true, publicKey);
byte[] encodedKey = cipher.ProcessBlock(SecretKey, 0, SecretKey.Length);