KickJava   Java API By Example, From Geeks To Geeks.

Java > Java SE, EE, ME > java > security > KeyPair

java.security
Class KeyPair

java.lang.Object
  extended by java.security.KeyPair
All Implemented Interfaces:
Serializable
See Also:
Top Examples, Source Code, PublicKey, PrivateKey

public PrivateKey getPrivate()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public PublicKey getPublic()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public KeyPair(PublicKey publicKey,
               PrivateKey privateKey)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1387]Public and private key
By Anonymous on 2005/04/12 09:43:10  Rate
class getByte {  
 public static void main ( String a [  ]  )  {  
  
  
 try  {  
         String algorithm = "DSA"; // or RSA, DH, etc. 
      
         // Generate a 1024-bit Digital Signature Algorithm  ( DSA )  key pair 
         KeyPairGenerator keyGen = KeyPairGenerator.getInstance ( algorithm ) ; 
         keyGen.initialize ( 1024 ) ; 
         KeyPair keypair = keyGen.genKeyPair (  ) ; 
         PrivateKey privateKey = keypair.getPrivate (  ) ; 
         PublicKey publicKey = keypair.getPublic (  ) ; 
      
         // Get the bytes of the public and private keys 
         byte [  ]  privateKeyBytes = privateKey.getEncoded (  ) ; 
         byte [  ]  publicKeyBytes = publicKey.getEncoded (  ) ; 
      
         // Get the formats of the encoded bytes 
         String format = privateKey.getFormat (  ) ; // PKCS#8 
         format = publicKey.getFormat (  ) ; // X.509 
      
      
         // The bytes can be converted back to public and private key objects 
         KeyFactory keyFactory = KeyFactory.getInstance ( algorithm ) ; 
         EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec ( privateKeyBytes ) ; 
         PrivateKey privateKey2 = keyFactory.generatePrivate ( privateKeySpec ) ; 
      
         EncodedKeySpec publicKeySpec = new X509EncodedKeySpec ( publicKeyBytes ) ; 
         PublicKey publicKey2 = keyFactory.generatePublic ( publicKeySpec ) ; 
      
         // The orginal and new keys are the same 
         boolean same = privateKey.equals ( privateKey2 ) ; // true 
         same = publicKey.equals ( publicKey2 ) ; // true 
      }  catch  ( InvalidKeySpecException e )   {  
      }  catch  ( NoSuchAlgorithmException e )   {  
      }  
  }  
 

Popular Tags