zoukankan      html  css  js  c++  java
  • Java RSA公钥加密,私钥解密算法的尝试

    https://www.cnblogs.com/liemng/p/6699257.html

    写这篇博客其实是有点意外的,来源最初也算是入职当前这家公司算吧,由于项目要求数据几乎都进行了加密(政府项目么!!!),当时看到这块就想好好看看这块的东西,苦于时间一直寻找不开,慢慢的都忘记了,忽然有天在网上看到一些关于加密的博客,讨论到说支付宝这样的商业软件加密是如何进行操作,后来了解了下,由于我是做android开发的所以我想当然的就下载了一个支付宝的android版本,进阶着就是迫不及待的改后缀,然后看看内部构造,发现支付宝的.so文件是超级多,那么问题来了,对于支付宝这样当量的用户,放到android 的java层去加密肯定是不合适的,这里来源于java语言的不安全性的考虑。多的不说apk的反编译,一旦反编译了看到了你java加密算法,卧槽,那问题就大了去了,估计马云爸爸想杀人的新都有,那么很显然对于支付宝而言肯定不能这么干,那么多的.so就很能说明问题了(加密是通过jni使用C代码实现的加密)。

      那么到了这里加密基本算是确认了,要是想保证你的数据的安全放到.so里会更加的安全(android上才有的东西哈).

      说道加密那么就进入到本篇博客的主题,加密算法之RSA非对称的加密算法。直译为私钥加密,公钥解密。其实也是很简单了,私钥只要你自己知道就好了,这样就能保证加密的数据只能你自己才能解密。公钥可以公开,公钥仅仅是用于加密的,是无法用于去解密数据的。

      RSA非对称的算法,也是不可逆的,不可逆就是无法根据公钥得到其算法,然后根据公钥去获去私钥!!!

      好了 ,基本的讲解就这些吧,紧接着一起来看下关于Java中的一些RSA的使用吧!!!

      Java使用分为三步走战略!!!

        1,生成私钥和秘钥

        2,公钥加密

        3,私钥解密

      看到这里是不是很so easy.

      java代码生成私钥和秘钥如下代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    /**
         *生成私钥  公钥
         */
        public static void geration(){
            KeyPairGenerator keyPairGenerator;
            try {
                keyPairGenerator = KeyPairGenerator.getInstance("RSA");
                SecureRandom secureRandom = new SecureRandom(new Date().toString().getBytes()); 
                keyPairGenerator.initialize(1024, secureRandom); 
                KeyPair keyPair = keyPairGenerator.genKeyPair(); 
                byte[] publicKeyBytes = keyPair.getPublic().getEncoded(); 
                FileOutputStream fos = new FileOutputStream(PUBLIC_KEY_PATH);  
                fos.write(publicKeyBytes);  
                fos.close(); 
                byte[] privateKeyBytes = keyPair.getPrivate().getEncoded(); 
                fos = new FileOutputStream(PRIVATE_KEY_PATH);  
                fos.write(privateKeyBytes);  
                fos.close(); 
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
        }

      

      获去公钥代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
     * 获取公钥
     * @param filename
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String filename) throws Exception { 
        File f = new File(filename); 
        FileInputStream fis = new FileInputStream(f);  
        DataInputStream dis = new DataInputStream(fis); 
        byte[] keyBytes = new byte[(int)f.length()];
        dis.readFully(keyBytes);  
        dis.close();
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); 
        KeyFactory kf = KeyFactory.getInstance("RSA");  
        return kf.generatePublic(spec); 

      获去私钥的代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    /**
      * 获取私钥
      * @param filename
      * @return
      * @throws Exception
      */
     public static PrivateKey getPrivateKey(String filename)throws Exception { 
         File f = new File(filename); 
         FileInputStream fis = new FileInputStream(f); 
         DataInputStream dis = new DataInputStream(fis); 
         byte[] keyBytes = new byte[(int)f.length()]; 
         dis.readFully(keyBytes); 
         dis.close(); 
         PKCS8EncodedKeySpec spec =new PKCS8EncodedKeySpec(keyBytes); 
         KeyFactory kf = KeyFactory.getInstance("RSA"); 
         return kf.generatePrivate(spec); 
       

      测试如上代码的可用性:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    public static void main(String[] args) {
         
        geration();
          
        String input = "!!!hello world!!!"
        RSAPublicKey pubKey;
        RSAPrivateKey privKey;
        byte[] cipherText;
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("RSA");         
            pubKey = (RSAPublicKey) getPublicKey(PUBLIC_KEY_PATH);
            privKey = (RSAPrivateKey) getPrivateKey(PRIVATE_KEY_PATH);
             
            cipher.init(Cipher.ENCRYPT_MODE, pubKey); 
            cipherText = cipher.doFinal(input.getBytes()); 
            //加密后的东西 
            System.out.println("cipher: " + new String(cipherText));         
            //开始解密 
            cipher.init(Cipher.DECRYPT_MODE, privKey);  
            byte[] plainText = cipher.doFinal(cipherText); 
            System.out.println("publickey: " + Base64.getEncoder().encode(cipherText));
            System.out.println("plain : " + new String(plainText));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        

      测试结果如下:

    1
    2
    3
    cipher: D?:?=羖O縜?,^辀?$偞/�致?2懁B鏣靴臧??2e嗀|?,w馋i纂W俞:�&圼?G6?弑橰H桞℉鬜?=)^呸b?? ?;皒D�dm`苣+.+?
    ?:& ??#f-?扴8eE]?(
    plain : !!!hello world!!!

      如上是RSA加密的java版本

      

      当然上述最终生成的byte写入到了一个文件中。如果你感觉这样和你不方便你也可以直接用base64编码成一个字符串,保留下来。

      

    1
    2
    3
    使用Base64.getEncoder().encodeToString(keyBytes)进行编译
     
    使用Base64.getDecoder().decode(PUBLIC_KEY)进行解码

      

    你得有足够的实力,你的原则和底线才会被人尊重。
  • 相关阅读:
    Network (poj1144)
    C. Hongcow Builds A Nation
    ZYB loves Xor I(hud5269)
    D. Chloe and pleasant prizes
    Game(hdu5218)
    约瑟夫环的递推方法
    Misaki's Kiss again(hdu5175)
    Exploration(hdu5222)
    B. Arpa's weak amphitheater and Mehrdad's valuable Hoses
    C. Arpa's loud Owf and Mehrdad's evil plan
  • 原文地址:https://www.cnblogs.com/yaowen/p/9120908.html
Copyright © 2011-2022 走看看