RSA encryption and decryption and signing endorsement test

RSA encryption and decryption and signing endorsement test

  RSA public key encryption algorithm is 1977 Nian by the Ronald Rivest ( Ron Rivest ), Adi Shamir ( Adi Shamir ) and Leonard Adleman ( Leonard Adleman ) presented together. 1987 Nian 7 Yue for the first time in the United States announced when the three of them are working at MIT internship. RSA is the three of them last names beginning with the letter composed pieces together.

 

  RSA is the most influential and the most commonly used public-key encryption algorithm that can resist so far known to the vast majority of password attacks, has been ISO recommended as public key encryption standard.

 

  RSA public-key cryptosystem. The so-called public key cryptography is the use of a different encryption key and decryption key, a "is derived from the known encryption key decryption key is computationally infeasible" cryptosystems.

 

  In public-key cryptosystem, the encryption key (that is, the public key) PK is public information, and the decryption key (ie secret key) SK is confidential. Encryption algorithm E and the decryption algorithm D are also disclosed. Although the decryption key SK is a public key PK decision, but not according to PK calculate SK .

 

  Based on this theory, 1978 appeared the famous RSA algorithm, it is usually Mr. into a pair of RSA keys, one of which is a secret key stored by the user; the other is the public key can be made public, even in network server registration. In order to improve the strength of confidentiality, the RSA keys is at least 500 bits long, is generally recommended to use 1024 bits. This allows a large amount of computation encryption.

 

  RSA algorithm is a first algorithm for both encryption and digital signatures, but also easy to understand and operate. RSA is the most widely studied public key algorithm, presented to thirty years from today's, have withstood the test of various attacks, gradually accepted, as of 2017 years was widely considered the best program of public One.

 

  SET (Secure Electronic Transaction) protocol requirements CA employed 2048bits long keys, other entities using 1024 -bit keys. RSA key length increase as the level of privacy, increased rapidly.

 

  RSA algorithm is an asymmetric cryptographic algorithm, so-called asymmetric, meaning that the algorithm requires a pair of keys, using one of the encryption, decryption needs to another.

 

Next we look at Java how to implement RSA encryption and decryption and signing endorsement test. Let's look at RSA encryption and decryption. 

 

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import java.security.*;

java.util.Base64 import;

/**

 * RSA encryption and decryption steps

 */

public class Test1 {

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

        // first be given an encrypted string

        String data = " green Zijin, but Youyouwoxin King and so far pondered.. ";

        // 1. Construction of public and private key pair

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // 2. get the key to the public key

        PublicKey publicKey = keyPair.getPublic();

        // 3. obtain key private key pair

        PrivateKey privateKey = keyPair.getPrivate();

        // 4. Treat encrypted data encryption

        Cipher cipher = Cipher.getInstance("RSA");

        cipher.init(Cipher.ENCRYPT_MODE,publicKey);

        byte [] bytesEncrypt = cipher.doFinal (data.getBytes ()); // generated distortion , we need Base64 transcoding

        //5.Base64 coding

        byte[] encodeBase64 = Base64.getEncoder().encode(bytesEncrypt);

        System.out.println ( " encrypted data :" + new String (encodeBase64) );

        // 6. For decryption , before use of Base64 encoded information is decoded

        byte[] bytesDecode = Base64.getDecoder().decode(encodeBase64);

        // 7. Decryption

        Cipher cipher2=Cipher.getInstance("RSA");

        cipher2.init(Cipher.DECRYPT_MODE,privateKey);

        byte [] = bytesDecrypt cipher2.doFinal (bytesDecode);

        System.out.println ( " decrypted data :" + new String (bytesDecrypt) );

    }

}

 

 

  Private and public key information itself is stored in the distortion, in actual use, we can also Base64 the garbled coded as recognizable ASCII code, then the public and private key information into the persistent storage file, after when the need to use public and private key can read information from the file. To this end, we can write a RSA tools from a public and private key file storing the information read in public and private key information, and then define methods to obtain public and private keys, and encryption and decryption of data method. First, we provide information on public and private key pair is assumed that the public key information is stored in a name for the rsa_public_key.pem file, the information is as follows:

 

-----BEGIN RSA PUBLIC KEY-----

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDY90KtriCa4KjNe3mgrGGbDB95

8A2byBKf+wOmPmOopP3gGeg7+DFAPNYCC+tL8h2bpUI3IPKOm2Hon8kM/p628i1J

Z7JjopYVZW6JKqA2ImyneeUEK748FXwXTRAAMCTqQG / 7a178BGawTdHi6hk + M6UF

lT0EhL6JA8ULKFoiHwIDAQAB

-----BEGIN RSA PUBLIC KEY-----

  Assuming that private information is stored in a name for the rsa_private_key.pem file, the information is as follows ::

 

 

-----BEGIN RSA PRIVATE KEY-----

MIICXQIBAAKBgQDY90KtriCa4KjNe3mgrGGbDB958A2byBKf+wOmPmOopP3gGeg7

+DFAPNYCC+tL8h2bpUI3IPKOm2Hon8kM/p628i1JZ7JjopYVZW6JKqA2ImyneeUE

K748FXwXTRAAMCTqQG / 7a178BGawTdHi6hk + M6UFlT0EhL6JA8ULKFoiHwIDAQAB

AoGBAIJFhF2wLZeQyQoH13Gnzzs/Pi8C+cjNipFQMFLDJyd9WYoTRCOt1DST0pOM

AI2rJCfuRCHBwKHrnhAE0LzirPxkmvyHTIBXIoz3fHiSkIKkUVG04BcgTYpNKWPB

ISlzdhSaw7CnmJjTthTrD5LLPtpqUl350lUYFEHVNR6Ys9JRAkEA9JUEVxzSvQkV

V6hxhbvlxl0mATbPfiNKDBTPdr48dyYdgluAoGfAPf9rmgoCpdEd2hZBIfdy7xdL

LvP7ztb/rQJBAOMYNC/lZLz9A9cDJ5bibrJnmyRG0SAGAzu4ffYdBoGb0kRRKzTe

5jxfRnbiUPQU4GQXhADfikGn2ogRqbtDsnsCQQCJdp+D3n1LJanLJK75PQv9myjb

EdU4zdi2RZP85xrQ1KlNNORsQyO3NLFjWDD4xTmD83IUByGf43WsJBDoxcnZAkA3

i84IARX42/I6fz0JvOzSmmDqKKAyMwZLbz7wGf1jalet+iSVVAgAsFUt8wFWEl0o

XlAdXpAUqxfavGdFtLNNAkABS576xgLcLmyw51f9hoM9RiamLn+WNzoA5TLOZjGI

dZZnX / A8SoFYGoJoN1O0hp5DxDdl gjW + / + mH51 gliEIB

-----END RSA PRIVATE KEY-----

 

 

  Next, we write a RSAUtil tools, code is as follows:  

 

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.security.*;

import java.security.spec.InvalidKeySpecException;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

java.util.Base64 import;

/**

 * Tools

 */

public class RSAUtil {

    /*

        Reads the secret key data

     */

    public static byte[] readKeyDatas(String keyFilePath){

        BufferedReader bufferedReader=null;

        try{

            bufferedReader = new BufferedReader(new FileReader(keyFilePath));

            String str=null;

            StringBuilder stringBuilder=new StringBuilder();

            while ((str=bufferedReader.readLine())!=null){

                if(str.contains("---")){

                    continue;

                }

                stringBuilder.append(str);

            }

            return stringBuilder.toString().getBytes();

        }catch (IOException e) {

            e.printStackTrace ();

        }finally {

            try {

                bufferedReader.close();

            } catch (IOException e) {

                e.printStackTrace ();

            }

        }

        return null;

    }

    /*

        Generate a public key

     */

    public static PublicKey getPublicKey(String publicKeyPath){

        // 1 reading public key file , obtain the public key data

        byte[] bytesPublicBase64 = readKeyDatas(publicKeyPath);

        // 2 to read the data is Base64 decoding

        byte[] bytesPublic = Base64.getDecoder().decode(bytesPublicBase64);

        // 3. The data is decoded , re-packaged into a PublicKey objects

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytesPublic);

        KeyFactory keyFactory=null;

        try {

            keyFactory = KeyFactory.getInstance("RSA");

            PublicKey publicKey = keyFactory.generatePublic(keySpec);

            return publicKey;

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace ();

        } catch (InvalidKeySpecException e) {

            e.printStackTrace ();

        }

        return null;

    }

    /*

        Generating a private key

     */

    public static PrivateKey getPrivateKey(String privateKeyPath){

        // 1. read the private key file , obtain private data

        byte[] bytesPrivateBase64 = readKeyDatas(privateKeyPath);

        // 2 to read the data is Base64 decoding

        byte[] bytesPrivate = Base64.getDecoder().decode(bytesPrivateBase64);

        // 3. The data is decoded , re-packaged into a PrivateKey objects

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytesPrivate);

        KeyFactory keyFactory=null;

        try {

            keyFactory = KeyFactory.getInstance("RSA");

            PrivateKey privateKey = keyFactory.generatePrivate (keySpec);

            return privateKey;

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace ();

        } catch (InvalidKeySpecException e) {

            e.printStackTrace ();

        }

        return null;

    }

    /*

        Encrypted data

     */

    public static String encodeData(PublicKey publicKey,String originData){

        try {

            Cipher cipher = Cipher.getInstance("RSA");

            cipher.init(Cipher.ENCRYPT_MODE,publicKey);

            byte[] bytesEncrypt = cipher.doFinal(originData.getBytes());

            // Base64 encoding

            byte[] bytesEncryptBase64 = Base64.getEncoder().encode(bytesEncrypt);

            return new String(bytesEncryptBase64);            

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace ();

        } catch (NoSuchPaddingException e) {

            e.printStackTrace ();

        } catch (InvalidKeyException e) {

            e.printStackTrace ();

        } catch (BadPaddingException e) {

            e.printStackTrace ();

        } catch (IllegalBlockSizeException e) {

            e.printStackTrace ();

        }

        return null;

    }

    /*

        Decrypting data

     */

    public static String decodeData(PrivateKey privateKey,String encodeData){

        try {

            // Base64 decoding

            byte[] bytesEncrypt = Base64.getDecoder().decode(encodeData);

            // encryption

            Cipher cipher = Cipher.getInstance("RSA");

            cipher.init(Cipher.DECRYPT_MODE,privateKey);

            byte [] = bytesDecrypt cipher.doFinal (bytesEncrypt);

            return new String(bytesDecrypt);

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace ();

        } catch (NoSuchPaddingException e) {

            e.printStackTrace ();

        } catch (InvalidKeyException e) {

            e.printStackTrace ();

        } catch (BadPaddingException e) {

            e.printStackTrace ();

        } catch (IllegalBlockSizeException e) {

            e.printStackTrace ();

        }

        return null;

    }   

}

 

  In this case, after the need to use public and private keys, encryption and decryption methods corresponding to the class of the tool calls.

  Finally, we will look at using RSA how the data is signed endorsement test, the specific code as follows:

 

 

 

import java.io.UnsupportedEncodingException;

import java.security.*;

/**

 * Endorsement test-signed signature verification: VLO data that is legality verification data sources

 * Endorsement: private

 * Inspection sign: Public Key

 */

public class Test2 {

    private static String privateKeyPath = " file path stored private key information ";

    private static String publicKeyPath = " file path stored public key information ";

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, SignatureException {

        String data = " verify that the legitimate server for the data transmission ";

        /**

         * Endorsement process

         */

        PrivateKey privateKey = RSAUtil.getPrivateKey(privateKeyPath);

        Signature signature = Signature.getInstance("Sha1WithRSA");

        signature.initSign(privateKey);

        signature.update(data.getBytes("UTF-8"));

        byte[] signed = signature.sign();

        /**

         * Inspection process to sign

         */

        PublicKey publicKey = RSAUtil.getPublicKey(publicKeyPath);

        Signature signature2 = Signature.getInstance("Sha1WithRSA");

        signature2.initVerify(publicKey);

        signature2.update(data.getBytes("UTF-8"));

        boolean verify = signature2.verify(signed);

        System.out.println ( " test ballot results :" + verify);

    }    

}

Guess you like

Origin www.cnblogs.com/yhxb/p/11513135.html