Mainly used for digital signatures:
Storage key pair
First use the keypairGeneration to generate a key pair:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance ( "RSA"); keyGen.initialize (1024); KeyPair keyPair = keyGen.genKeyPair (); privateKey = keyPair.getPrivate (); publicKey = keyPair.getPublic ();
Method for storing the key as a file:
FileOutputStream Fs = New FileOutputStream (FiLename); fs.write ()); fs.close ();
2. Load key pair
Suppose the public key file is public.dat, private.dat
First read public key files:
// read public key FileInputStream fsPublicKey = new FileInputStream (publicKeyFile); BufferedInputStream bfsPublicKey = new BufferedInputStream (fsPublicKey); byte [] bytePublicKey = new byte [bfsPublicKey.available ()]; bfsPublicKey.read (bytePublicKey); bfsPublicKey.close () ;
Use KeyFactory to produce public keys
// build public key X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec (byteEncodedPublicKey); KeyFactory keyFactory = KeyFactory.getInstance ( "RSA"); PublicKey pubKey = keyFactory.generatePublic (pubKeySpec);
The idea, the processing of the private key is the same, the only difference is the keySpec of the private key. PKCS8ENCODEDKEYSPEC