//********************************************** // // RSAPVK8 // PKCS #8 PrivateKeyInfo dumper // // Copyright (C) 2004 Michel I. Gallant // //********************************************** import java.io.*; import java.math.BigInteger; import java.security.*; import java.security.spec.*; import java.security.cert.*; import java.security.interfaces.*; class RSAPVK8 { public static void main(String[] args) { if (args.length != 1) System.out.println("Usage: RSAPVK8 "); else try { byte[] encodedPriKey = getFileBytes(args[0]); System.out.println("RSA PrivateKeyInfo: " + encodedPriKey.length + " bytes\n") ; PKCS8EncodedKeySpec pvkKeySpec = new PKCS8EncodedKeySpec(encodedPriKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); //---- First, display private key components using default hex display of Crt toString() -- RSAPrivateKey mypvkKey = (RSAPrivateKey)keyFactory.generatePrivate(pvkKeySpec); System.out.println(mypvkKey.toString()) ; //---- Second, manually display private key components in BigInteger decimal format -- RSAPrivateCrtKey pvkKey = (RSAPrivateCrtKey)keyFactory.generatePrivate(pvkKeySpec); BigInteger mod = pvkKey.getModulus(); byte[] modbytes = mod.toByteArray() ; if(modbytes[0] == 0) //if high-order byte is zero, it's for sign bit; don't count in bit-size calculation System.out.println("\nKeySize: " + 8*(modbytes.length-1) + " bits"); else System.out.println("\nKeySize: " + 8*modbytes.length + " bits"); System.out.println("\nModulus:\n" + pvkKey.getModulus().toString()); System.out.println("\nPublic Exponent:\n" + pvkKey.getPublicExponent().toString()); System.out.println("\nPrivate Exponent:\n" + pvkKey.getPrivateExponent().toString()); System.out.println("\nPrime Exponent P:\n" + pvkKey.getPrimeExponentP().toString()); System.out.println("\nPrime Exponent Q:\n" + pvkKey.getPrimeExponentQ().toString()); System.out.println("\nPrime P:\n" + pvkKey.getPrimeP().toString()); System.out.println("\nPrime Q:\n" + pvkKey.getPrimeQ().toString()); System.out.println("\nCrtCoeff:\n" + pvkKey.getCrtCoefficient().toString()); } catch(Exception ioe) { System.out.println(ioe.toString()); } } private static void displayData(byte[] data) { int bytecon = 0; //to get unsigned byte representation for(int i=1; i<=data.length ; i++){ bytecon = data[i-1] & 0xFF ; // byte-wise AND converts signed byte to unsigned. if(bytecon<16) System.out.print("0" + Integer.toHexString(bytecon).toUpperCase() + " "); // pad on left if single hex digit. else System.out.print(Integer.toHexString(bytecon).toUpperCase() + " "); // pad on left if single hex digit. if(i%16==0) System.out.println(); } } private static byte[] getFileBytes(String infile){ File f = new File(infile) ; int sizecontent = ((int) f.length()); byte[] data = new byte[sizecontent]; try { FileInputStream freader = new FileInputStream(f); freader.read(data, 0, sizecontent) ; freader.close(); return data; } catch(IOException ioe) { System.out.println(ioe.toString()); return null; } } }