1 Packagetest;2 3 ImportJava.io.FileInputStream;4 ImportJava.io.FileOutputStream;5 ImportJava.io.ObjectInputStream;6 ImportJava.io.ObjectOutputStream;7 ImportJava.security.Key;8 ImportJava.security.KeyPair;9 ImportJava.security.KeyPairGenerator;Ten One ImportJavax.crypto.Cipher; A - Public classTestCase { - the Public Static voidMain (string[] args)throwsException { - Publicenrypt (); - Privatedecrypt (); - + } - //Encrypt + Public Static voidPublicenrypt ()throwsexception{ A //instantiate cryptographic tools using the RSA algorithm atCipher cipher=cipher.getinstance ("RSA"); - //Instantiate key -Keypairgenerator keypairgenerator=keypairgenerator.getinstance ("RSA"); - //get a pair of keys -KeyPair keypair=Keypairgenerator.generatekeypair (); - //Get public key inKey publickey=keypair.getpublic (); - //Get private key toKey privatekey=keypair.getprivate (); + //encrypt with public key - Cipher.init (Cipher.encrypt_mode, publickey); the byte[]result =cipher.dofinal ("Data Content". GetBytes ("UTF-8"))); * //write the private key to the file $Savekey (Privatekey, "Zxx_private.key");Panax Notoginseng //data storage after encryption -SaveData (Result, "Public_encryt.dat"); theSystem.out.println (NewString (Result, "UTF-8")); + } A //decryption the Public Static voidPrivatedecrypt ()throwsexception{ + //Instantiating cryptographic Tools -Cipher cipher=cipher.getinstance ("RSA"); $ //Get private key $Key Privatekey=readkey ("Zxx_private.key"); - //get the encrypted information - byte[] Src=readdata ("Public_encryt.dat"); the //decrypt with private key - Cipher.init (Cipher.decrypt_mode, privatekey);Wuyi byte[] result=cipher.dofinal (SRC); theSystem.out.println (NewString (Result, "UTF-8")); - } Wu //Save Data - Public Static voidSaveData (byte[] result,string FileName)throwsexception{ AboutFileOutputStream fosdata=NewFileOutputStream (fileName); $ fosdata.write (result); - fosdata.close (); - } - //Save Key A Public Static voidSavekey (Key key,string fileName)throwsexception{ +FileOutputStream foskey=NewFileOutputStream (fileName); theObjectOutputStream oossecretkey=NewObjectOutputStream (foskey); - Oossecretkey.writeobject (key); $ oossecretkey.close (); the Foskey.close (); the } the //Read Key the Public StaticKey ReadKey (String fileName)throwsexception{ -FileInputStream fiskey=NewFileInputStream (fileName); inObjectInputStream oiskey=NewObjectInputStream (fiskey); theKey key=(Key) oiskey.readobject (); the oiskey.close (); About fiskey.close (); the returnkey; the } the //reading Data + Public Static byte[] ReadData (String fileName)throwsexception{ -FileInputStream fisdat=NewFileInputStream (fileName); the byte[] src=New byte[Fisdat.available ()];Bayi intlen=fisdat.read (SRC); the intTotal=0; the while(total<src.length) { -total+=Len; -Len=fisdat.read (SRC, total, src.length-Total ); the } the fisdat.close (); the returnsrc; the } - the}
Java Asymmetric Encryption