"JAVA Core technology" cryptographic public key __java

Source: Internet
Author: User
Tags crypt decrypt

The AES password is a symmetric cipher that uses the same key for both encryption and decryption. The fatal disadvantage of symmetric passwords is in the distribution with passwords. If a sends a cryptographic method to B, then B needs to use the same key as a. If a modifies the key then he must send a message to B while also sending a new key through a secure channel, but perhaps he does not have a secure channel to B, which is why he must first encrypt the information he sent to B.


Public key cryptography solves this problem. In a public key password, B has a key pair, including a public key and a matching private key. B can publish a public key anywhere, but he must strictly keep his private key. A only need to encrypt the information he sends to B using a public key.


The problem of combining a common password with a symmetric cipher can be solved:

1 A generates a random symmetric encryption key that he uses to encrypt the plaintext.

2) A is used to encrypt the symmetric key with B's public key.

3 The encrypted symmetric key and the encrypted plaintext are sent to B at the same time

4) b Decrypts the symmetric key with his private key.

5) b Decrypts the information with the decrypted symmetric key.

The most common public key algorithm is RSA. The listing code is as follows:

Import java.io.*;
Import java.security.*;

Import javax.crypto.*; /** * This program tests the RSA cipher. Usage:<br> * java rsatest-genkey public private<br> * Java rsatest-encrypt plaintext encrypted public<b 
 R> * Java rsatest-decrypt encrypted decrypted private<br> * @author Cay Horstmann * @version 1.0 2004-09-14 */public class Rsatest {public static void main (string[] args) {try {if (args[0].equals) ("-
            Genkey ")) {Keypairgenerator Pairgen = keypairgenerator.getinstance (" RSA ");
            SecureRandom random = new SecureRandom ();
            Pairgen.initialize (keysize, Random);
            KeyPair KeyPair = Pairgen.generatekeypair ();
            ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream (args[1));
            Out.writeobject (Keypair.getpublic ());
            Out.close ();
            out = new ObjectOutputStream (new FileOutputStream (args[2)); Out.writeobject (kEypair.getprivate ());
         Out.close (); else if (args[0].equals ("-encrypt")) {keygenerator keygen = keygenerator.getinstance ("AES
            ");
            SecureRandom random = new SecureRandom ();
            Keygen.init (random);

            Secretkey key = Keygen.generatekey ();
            Wrap with RSA public key ObjectInputStream keyin = new ObjectInputStream (new FileInputStream (args[3));
            Key PublicKey = (key) keyin.readobject ();

            Keyin.close ();
            Cipher Cipher = cipher.getinstance ("RSA");
            Cipher.init (Cipher.wrap_mode, PublicKey);
            byte[] Wrappedkey = Cipher.wrap (key);
            DataOutputStream out = new DataOutputStream (new FileOutputStream (args[2));
            Out.writeint (wrappedkey.length);

            Out.write (Wrappedkey);
            InputStream in = new FileInputStream (args[1]);
            cipher = Cipher.getinstance ("AES"); Cipher.init (CIPHER.ENcrypt_mode, key);
            Crypt (in, out, cipher);
            In.close ();
         Out.close ();
            else {DataInputStream in = new DataInputStream (new FileInputStream (args[1));
            int length = In.readint ();
            byte[] Wrappedkey = new Byte[length];

            In.read (wrappedkey, 0, length);
            Unwrap with RSA private key objectinputstream keyin = new ObjectInputStream (new FileInputStream (args[3));
            Key Privatekey = (key) keyin.readobject ();

            Keyin.close ();
            Cipher Cipher = cipher.getinstance ("RSA");
            Cipher.init (Cipher.unwrap_mode, Privatekey);

            Key key = Cipher.unwrap (Wrappedkey, "AES", Cipher.secret_key);
            OutputStream out = new FileOutputStream (args[2]);
            cipher = Cipher.getinstance ("AES");

            Cipher.init (Cipher.decrypt_mode, key);
            Crypt (in, out, cipher);
            In.close (); Out. Close ();
      } catch (IOException e) {e.printstacktrace ();
      catch (Generalsecurityexception e) {e.printstacktrace ();
      catch (ClassNotFoundException e) {e.printstacktrace (); }/** * Uses a cipher to transform the bytes in an input stream and sends the transformed bytes to a * o
    Utput Stream.
    * @param in the input stream * @param out of the output stream * @param cipher The cipher that transforms the bytes */public static void crypt (InputStream in, outputstream out, Cipher Cipher) throws IOException, Generalsec
      urityexception {int blockSize = Cipher.getblocksize ();
      int outputsize = cipher.getoutputsize (blockSize);
      byte[] inbytes = new Byte[blocksize];

      byte[] outbytes = new Byte[outputsize];
      int inlength = 0;
      ;
      Boolean more = true;
       while (more) {inlength = In.read (inbytes);  if (inlength = = blockSize) {int outlength = cipher.update (inbytes, 0, BlockSize, outbytes);
         Out.write (outbytes, 0, outlength);
      else more = false;
      if (Inlength > 0) outbytes = cipher.dofinal (inbytes, 0, inlength);
      else Outbytes = cipher.dofinal ();
   Out.write (outbytes);
private static final int keysize = 512;
 }

Test:

1:java Rsatest-genkey Public.key Private.key first generates a key pair (public key and private key)


2:f:\javacode>java rsatest-encrypt F:\javacode\a.html F:\javacode\b.html Public.key

The-encrypt option is used to generate the AES symmetric key and is packaged with a public key. In this case, the plaintext a.html is encrypted with Public.key, which is encrypted b.html

3:f:\javacode>java rsatest-decrypt F:\javacode\b.html F:\javacode\c.html Private.key

The-decrypt option is used to decrypt the file and verify that the decrypted file matches the plaintext. Here use Private.key to decrypt b.html, decrypt into c.html. So a.html is the same as c.html.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.