Click here to Skip to main content
15,895,781 members
Articles / Programming Languages / Java / Java SE

Porting Java Public Key Hash to C# .NET

Rate me:
Please Sign up or sign in to vote.
4.62/5 (44 votes)
26 Oct 20047 min read 258.5K   4.8K   55  
This tutorial is an effort to overcome problems faced by the developers who want to sign data using Java Key Store and want to verify it on .NET platform. The tutorial demonstrates how to export the Public Key using Java to .NET compatible Public Key (XML format).
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Xml;
namespace RSASecurity
{
	/// <summary>
	/// Summary description for SecuirtyManager.
	/// </summary>
	class SecurityManager
	{
		private RSAParameters RSAKeyInfo;
		private static RSACryptoServiceProvider RSA=null;
		private string modStr="";
		private string expStr="";
		private static string PUBLIC_KEY;
		
		/// <summary>
		/// Reads the Public key file and Loads the RSAParameters with the 
		/// Modulous and Exponent data.
		/// </summary>
		public SecurityManager()
		{
			PUBLIC_KEY="c:\\netpublic.key"; //Generated by Java Program
			RSAKeyInfo = new RSAParameters();
			RSA = new RSACryptoServiceProvider();

			readKey();
		}
		/// <summary>
		/// Reads the key from the XML formatted file.
		/// </summary>
		private void readKey()
		{
			// read the XML formated public key 
			try
			{
			
				XmlTextReader reader = new XmlTextReader(PUBLIC_KEY);
				while(reader.Read())
				{
					if (reader.NodeType == XmlNodeType.Element)
					{
						if(reader.Name=="Modulus")
						{
							reader.Read();
							modStr= reader.Value;
						}
						else if(reader.Name=="Exponent")
						{
							reader.Read();
							expStr= reader.Value;
						}
					}
				}
				if(modStr.Equals("") ||expStr.Equals(""))
				{
					//throw exception
					throw new Exception("Invalid public key");
				}
				RSAKeyInfo.Modulus = Convert.FromBase64String(modStr);
				RSAKeyInfo.Exponent = Convert.FromBase64String(expStr);
				RSA.ImportParameters(RSAKeyInfo);
			}
			catch(Exception e)
			{
				throw new Exception("Invalid Public Key.");
			}
		}
		/// <summary>
		/// Verifies the signature for a given data.
		/// </summary>
		/// <param name="signature">Signature data in Base64</param>
		/// <param name="signedData">Original data in BASE64</param>
		/// <returns>True if signature is valid else False</returns>
		public bool verifySignature(string signature,string signedData)
		{
			byte[] sign = Convert.FromBase64String(signature);
			return verifySignature(sign,signedData);
		}
		/// <summary>
		/// Verifies the signature for a given data.
		/// </summary>
		/// <param name="signature">The signature </param>
		/// <param name="signedData">Original data in Base64</param>
		/// <returns></returns>
		public bool verifySignature(byte[] signature , string signedData)
		{
			
			
			byte[] hash = Convert.FromBase64String(signedData);
			try
			{
				if(RSA.VerifyData(hash,"SHA1",signature))
				{
					//Console.WriteLine("The signature is valid.");
					return true;
				}
				else
				{
					//Console.WriteLine("The signature is not valid.");
					return false;
				}
			}
			catch(Exception e)	
			{
				Console.WriteLine(e.Message);
				return false;
			}
		}
		/// <summary>
		/// Decrypts the data. from Base64 string
		/// </summary>
		/// <param name="encrypted">Base64EncodedData</param>
		/// <returns>Data</returns>
		public static string decryptData(string encrypted)
		{
			return Encoding.GetEncoding("windows-1256").GetString(Convert.FromBase64String(encrypted));
		}

		public string readFile(string file)
		{
			string finalStr="";
			try 
			{
				// Create an instance of StreamReader to read from a file.
				// The using statement also closes the StreamReader.
				using (StreamReader sr = new StreamReader(file)) 
				{
					String line;
					// Read and display lines from the file until the end of 
					// the file is reached.
					while ((line = sr.ReadLine()) != null) 
					{
						//Console.WriteLine(line);	
						finalStr = finalStr+line;
					}
					return finalStr;
				}
			}
			catch (Exception e) 
			{
				// Let the user know what went wrong.
				Console.WriteLine("The file could not be read:");
				Console.WriteLine(e.Message);
			}
			return null;
		}

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{	
			SecurityManager sm = new SecurityManager();
			string endata = sm.readFile("c:\\data.dat");
			string ensignature = sm.readFile("c:\\signature.dat");
			
			bool result = sm.verifySignature(ensignature,endata);

			Console.WriteLine("Data is validate: "+result);
			Console.ReadLine();
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United Arab Emirates United Arab Emirates
Shaheryar specializes in architecture, design, development and deployment of J2EE and .Net enterprise applications. He got hooked with enterprise application development during his Masters and has been devoted to it ever since.

He was born in Lahore-Pakistan and holds a Bachelors degree in Computer Science (Major in Software Engg.) from Mohammed Ali Jinnah University, Islamabad-Pakistan.

Presently he is working as GIS Software Engineer for Client / Server J2EE (Web/Desktop) Applications in Middle East.

His skill set includes Java, JSP, Servlet, Massive EJB component development, J2EE essential design patterns, JDBC, JAAS, JMS, Java Help System, Java XML Parsers, web design, symmetric & asymmetric encryption (AES, DES, RSA), JavaScript, PDF417 2D Barcodes, ASP.Net, C#, Visual C++, AWT/Swing, UML, ArcIMS, ArcXML, ESRI Map Objects Java, Coldfusion, JBoss AS, Oracle 10g AS, Tomcat, IIS and JRun. He has successfully developed and deployed cross platform applications on IRIX, Linux and Windows platforms.

He usually works late hours with some heavy music and prefers to test and prove everything to his own satisfaction before committing himself and likes to finish what he starts without interruptions.

He loves playing guitar, bowling, snooker and cricket.

Comments and Discussions