zoukankan      html  css  js  c++  java
  • RSA加密解密

    参考:

    1,http://blog.csdn.net/MJM_49/article/details/77429883

    2,http://blog.csdn.net/defonds/article/details/42775183

    3,http://blog.csdn.net/centralperk/article/details/8538697

    4,http://blog.csdn.net/wang8978/article/details/52279661(涉及加密之后的byte[]转String,String转byte[]不一致的问题)

    5,http://blog.csdn.net/qq_27760433/article/details/78327328

    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.security.InvalidKeyException;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    
    public class EncrypRSAUtil {
    
        /**
         * 加密
         *
         * @param publicKey
         * @param srcBytes
         * @return
         * @throws NoSuchAlgorithmException
         * @throws NoSuchPaddingException
         * @throws InvalidKeyException
         * @throws IllegalBlockSizeException
         * @throws BadPaddingException
         */
        protected byte[] encrypt(RSAPublicKey publicKey, byte[] srcBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
            if (publicKey != null) {
                //Cipher负责完成加密或解密工作,基于RSA
                Cipher cipher = Cipher.getInstance("RSA");
                //根据公钥,对Cipher对象进行初始化
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                return cipher.doFinal(srcBytes);
            }
            return null;
        }
    
        /**
         * 解密
         *
         * @param privateKey
         * @param srcBytes
         * @return
         * @throws NoSuchAlgorithmException
         * @throws NoSuchPaddingException
         * @throws InvalidKeyException
         * @throws IllegalBlockSizeException
         * @throws BadPaddingException
         */
        protected byte[] decrypt(RSAPrivateKey privateKey, byte[] srcBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
            if (privateKey != null) {
                //Cipher负责完成加密或解密工作,基于RSA
                Cipher cipher = Cipher.getInstance("RSA");
                //根据公钥,对Cipher对象进行初始化
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                return cipher.doFinal(srcBytes);
            }
            return null;
        }
    
        /**
         * The method checks if the pair of public and private key has been
         * generated.
         *
         * @return flag indicating if the pair of keys were generated.
         */
        public static boolean areKeysPresent() {
    
            File privateKey = new File(PRIVATE_KEY_FILE);
            File publicKey = new File(PUBLIC_KEY_FILE);
    
            if (privateKey.exists() && publicKey.exists()) {
                return true;
            }
            return false;
        }
    
        /**
         * String to hold the name of the private key file.
         */
        public static final String PRIVATE_KEY_FILE = "/tmp/rsatest/private.key";
    
        /**
         * String to hold name of the public key file.
         */
        public static final String PUBLIC_KEY_FILE = "/tmp/rsatest/public.key";
    
        /**
         * @param args
         * @throws NoSuchAlgorithmException
         * @throws BadPaddingException
         * @throws IllegalBlockSizeException
         * @throws NoSuchPaddingException
         * @throws InvalidKeyException
         */
        public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException, ClassNotFoundException {
            EncrypRSAUtil rsa = new EncrypRSAUtil();
            //KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            //初始化密钥对生成器,密钥大小为1024位
            keyPairGen.initialize(1024);
            //生成一个密钥对,保存在keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
    
            if (!areKeysPresent()) {
    
                File privateKeyFile = new File(PRIVATE_KEY_FILE);
                File publicKeyFile = new File(PUBLIC_KEY_FILE);
    
                // Create files to store public and private key
                if (privateKeyFile.getParentFile() != null) {
                    privateKeyFile.getParentFile().mkdirs();
                }
                privateKeyFile.createNewFile();
    
                if (publicKeyFile.getParentFile() != null) {
                    publicKeyFile.getParentFile().mkdirs();
                }
                publicKeyFile.createNewFile();
    
                // Saving the Public key in a file
                ObjectOutputStream publicKeyOS = new ObjectOutputStream(
                        new FileOutputStream(publicKeyFile));
                publicKeyOS.writeObject(keyPair.getPublic());
                publicKeyOS.close();
    
                // Saving the Private key in a file
                ObjectOutputStream privateKeyOS = new ObjectOutputStream(
                        new FileOutputStream(privateKeyFile));
                privateKeyOS.writeObject(keyPair.getPrivate());
                privateKeyOS.close();
            }
    
            ObjectInputStream inputStream = null;
    
            // Decrypt the cipher text using the private key.
            inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
    
            //得到私钥
            RSAPrivateKey privateKey = (RSAPrivateKey) inputStream.readObject();
    
            // Encrypt the string using the public key
            inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
            //得到公钥
            RSAPublicKey publicKey = (RSAPublicKey) inputStream.readObject();
    
            String msg = "郭XX-精品相声";
            byte[] srcBytes = msg.getBytes();
    
            //用公钥加密
            byte[] resultBytes = rsa.encrypt(publicKey, srcBytes);
    
            //用私钥解密
            byte[] decBytes = rsa.decrypt(privateKey, resultBytes);
    
            System.out.println("明文是:" + msg);
            System.out.println("加密后是:" + new String(resultBytes));
            System.out.println("解密后是:" + new String(decBytes));
        }
        /**
         * 公钥
         */
        private static RSAPublicKey publicKey;
    
        static {
            try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(Resources.getResource("public.key").getFile()))) {
                publicKey = (RSAPublicKey) inputStream.readObject();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    
        private static String generateToken() throws IOException, ClassNotFoundException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            String tokenValue = "-TOKEN-" + Calendar.getInstance().getTimeInMillis();
            // Cipher负责完成加密或解密工作,基于RSA
            Cipher cipher = Cipher.getInstance("RSA");
            //根据公钥,对Cipher对象进行初始化
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return new String(cipher.doFinal(tokenValue.getBytes()), "ISO-8859-1");
        }
    
        public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, IOException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, ClassNotFoundException {
            String en = HttpRequestUtils.generateToken();
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(Resources.getResource("private.key").getFile()));
            RSAPrivateKey privateKey = (RSAPrivateKey) inputStream.readObject();
            //Cipher负责完成加密或解密工作,基于RSA
            Cipher cipher = Cipher.getInstance("RSA");
            //根据公钥,对Cipher对象进行初始化
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] de = cipher.doFinal(en.getBytes("ISO-8859-1"));
            System.out.println(new String(de));
        }
  • 相关阅读:
    进化中的技术小白
    mybatis的学习5______使用注解实现CURD
    mybatis的学习4______分页的实现
    Mybatis的学习3______使用log4j打印日志信息
    mybatis的学习2_____配置文件的详解和代码的优化
    Java代码实现邮件的上传
    JavaWeb小作业 用户表单数据的获取
    Java的学习JSP____4
    Javaweb的学习session___3
    Javaweb的学习(servlet和request)___2
  • 原文地址:https://www.cnblogs.com/voctrals/p/8625330.html
Copyright © 2011-2022 走看看