C# RSA和Java RSA互通

C# RSA和Java RSA互通

今天调查了C# RSA和Java RSA,网上很多人说,C#加密或者java加密 ,Java不能解密或者C#不能解密

但是我尝试了一下,发现是可以的,下面就是我尝试的代码,如果您有什么问题,我想看看,他们为什么不能互通?

Rsamain代码  
  1. package rsa;   
  2.   
  3. import java.math.BigInteger;   
  4. import java.security.KeyFactory;   
  5. import java.security.PrivateKey;   
  6. import java.security.PublicKey;   
  7. import java.security.spec.RSAPrivateKeySpec;   
  8. import java.security.spec.RSAPublicKeySpec;   
  9.   
  10. import javax.crypto.Cipher;   
  11.   
  12. import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;   
  13. import com.sun.org.apache.xml.internal.security.utils.Base64;   
  14.   
  15.   
  16. /**   
  17.  * @author cnchenhl   
  18.  * Jul 82011  
  19.  */   
  20. public class RSAMain {   
  21.   
  22.     private static String module = "5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=";   
  23.     private static String exponentString = "AQAB";   
  24.     private static String delement = "vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=";   
  25.     private static String encryptString = "Vx/dGjS1YWKRubsoDgiShiwLgqyNE2z/eM65U7HZx+RogwaiZimNBxjuOS6acEhKZx66cMYEAd1fc6oewbEvDIfP44GaN9dCjKE/BkkQlwEg6aTO5q+yqy+nEGe1kvLY9EyXS/Kv1LDh3e/2xAk5FNj8Zp6oU2kq4ewL8kK/ai4=";   
  26.     /**   
  27.      * @param args   
  28.      */   
  29.     public static void main(String[] args) {   
  30.         byte[] en = encrypt();   
  31.         System.out.println(Base64.encode(en));   
  32.         byte[] enTest = null;   
  33.         try {   
  34.             enTest = Base64.decode(encryptString);   
  35.         } catch (Base64DecodingException e) {   
  36.             e.printStackTrace();   
  37.         }   
  38.         System.out.println(enTest.length);   
  39.         System.out.println(en.length);   
  40.         System.out.println(new String(Dencrypt(en)));   
  41.         System.out.println(new String(Dencrypt(enTest)));   
  42.     }   
  43.   
  44.     public static byte[] encrypt() {   
  45.         try {   
  46.             byte[] modulusBytes = Base64.decode(module);   
  47.             byte[] exponentBytes = Base64.decode(exponentString);   
  48.             BigInteger modulus = new BigInteger(1, modulusBytes);   
  49.             BigInteger exponent = new BigInteger(1, exponentBytes);   
  50.   
  51.             RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);   
  52.             KeyFactory fact = KeyFactory.getInstance("RSA");   
  53.             PublicKey pubKey = fact.generatePublic(rsaPubKey);   
  54.   
  55.             Cipher cipher = Cipher.getInstance("RSA");   
  56.             cipher.init(Cipher.ENCRYPT_MODE, pubKey);   
  57.   
  58.             byte[] cipherData = cipher.doFinal(new String("chenhailong").getBytes());   
  59.             return cipherData;   
  60.         } catch (Exception e) {   
  61.             e.printStackTrace();   
  62.         }   
  63.         return null;   
  64.   
  65.     }   
  66.   
  67.     public static byte[] Dencrypt(byte[] encrypted) {   
  68.         try {   
  69.             byte[] expBytes = Base64.decode(delement);   
  70.             byte[] modBytes = Base64.decode(module);   
  71.   
  72.             BigInteger modules = new BigInteger(1, modBytes);   
  73.             BigInteger exponent = new BigInteger(1, expBytes);   
  74.   
  75.             KeyFactory factory = KeyFactory.getInstance("RSA");   
  76.             Cipher cipher = Cipher.getInstance("RSA");   
  77.   
  78.             RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modules, exponent);   
  79.             PrivateKey privKey = factory.generatePrivate(privSpec);   
  80.             cipher.init(Cipher.DECRYPT_MODE, privKey);   
  81.             byte[] decrypted = cipher.doFinal(encrypted);   
  82.             return decrypted;   
  83.         } catch (Exception e) {   
  84.             e.printStackTrace();   
  85.         }   
  86.         return null;   
  87.     }   
  88. }  
package rsa;

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;


/**
 * @author cnchenhl
 * Jul 8, 2011
 */
public class RSAMain {

    private static String module = "5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=";
    private static String exponentString = "AQAB";
    private static String delement = "vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=";
    private static String encryptString = "Vx/dGjS1YWKRubsoDgiShiwLgqyNE2z/eM65U7HZx+RogwaiZimNBxjuOS6acEhKZx66cMYEAd1fc6oewbEvDIfP44GaN9dCjKE/BkkQlwEg6aTO5q+yqy+nEGe1kvLY9EyXS/Kv1LDh3e/2xAk5FNj8Zp6oU2kq4ewL8kK/ai4=";
    /**
     * @param args
     */
    public static void main(String[] args) {
        byte[] en = encrypt();
        System.out.println(Base64.encode(en));
        byte[] enTest = null;
        try {
            enTest = Base64.decode(encryptString);
        } catch (Base64DecodingException e) {
            e.printStackTrace();
        }
        System.out.println(enTest.length);
        System.out.println(en.length);
        System.out.println(new String(Dencrypt(en)));
        System.out.println(new String(Dencrypt(enTest)));
    }

    public static byte[] encrypt() {
        try {
            byte[] modulusBytes = Base64.decode(module);
            byte[] exponentBytes = Base64.decode(exponentString);
            BigInteger modulus = new BigInteger(1, modulusBytes);
            BigInteger exponent = new BigInteger(1, exponentBytes);

            RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
            KeyFactory fact = KeyFactory.getInstance("RSA");
            PublicKey pubKey = fact.generatePublic(rsaPubKey);

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);

            byte[] cipherData = cipher.doFinal(new String("chenhailong").getBytes());
            return cipherData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    public static byte[] Dencrypt(byte[] encrypted) {
        try {
            byte[] expBytes = Base64.decode(delement);
            byte[] modBytes = Base64.decode(module);

            BigInteger modules = new BigInteger(1, modBytes);
            BigInteger exponent = new BigInteger(1, expBytes);

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

            RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modules, exponent);
            PrivateKey privKey = factory.generatePrivate(privSpec);
            cipher.init(Cipher.DECRYPT_MODE, privKey);
            byte[] decrypted = cipher.doFinal(encrypted);
            return decrypted;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

 

C#代码  
  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Text;   
  5. using System.Security.Cryptography;   
  6.   
  7. namespace RSA   
  8. {   
  9.     class Program   
  10.     {   
  11.         static void Main(string[] args)   
  12.         {   
  13.             string de  = "iBILuPJFgPMxgpbgN3F2JjD6XjcqRSApjVVbvBBEBDV21Pjj7lTrfhEjSVnJX/MVoZrmX0lxsvoXTMvvVwVF7K7W5hs7Qo+aMN96yWke7wiLEM9M4pPz60A/KSckskiona67tXcqOLXb8N18TKaNCKHv0Ce+GyEKK5+MT7e1vao=";   
  14.             //string encrypt = RSAEncrypt("", "chenhailong");   
  15.             byte[] encrypt = RSAEncrypt("chenhailong");   
  16.             //string name = RSADecrypt(encrypt);   
  17.             string name = RSADecrypt(Convert.FromBase64String(de));   
  18.             Console.WriteLine(encrypt.Length);   
  19.             Console.WriteLine(Convert.ToBase64String(encrypt));   
  20.             Console.WriteLine(name);   
  21.             Console.ReadKey();   
  22.         }   
  23.         ///    
  24.         /// RSA encrypt   
  25.         ///    
  26.         ///    
  27.         ///    
  28.         ///    
  29.         public static byte[] RSAEncrypt(string content)   
  30.         {   
  31.             string publickey = @"5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=AQAB";   
  32.             RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();   
  33.             byte[] cipherbytes;   
  34.             rsa.FromXmlString(publickey);   
  35.             cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);   
  36.   
  37.             //return Convert.ToBase64String(cipherbytes);   
  38.             return cipherbytes;   
  39.         }   
  40.   
  41.         ///    
  42.         /// RSA decrypt   
  43.         ///    
  44.         ///    
  45.         ///    
  46.         ///    
  47.         public static string RSADecrypt(byte[] content)   
  48.         {   
  49.             string privatekey = @"5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=AQAB

    /hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==

    6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=
    "
    ;   
  50.             RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();   
  51.             byte[] cipherbytes;   
  52.             rsa.FromXmlString(privatekey);   
  53.             cipherbytes = rsa.Decrypt(content, false);   
  54.   
  55.             return Encoding.UTF8.GetString(cipherbytes);   
  56.         }   
  57.   
  58.   
  59.     }   
  60.   
  61. }  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace RSA
{
    class Program
    {
        static void Main(string[] args)
        {
            string de  = "iBILuPJFgPMxgpbgN3F2JjD6XjcqRSApjVVbvBBEBDV21Pjj7lTrfhEjSVnJX/MVoZrmX0lxsvoXTMvvVwVF7K7W5hs7Qo+aMN96yWke7wiLEM9M4pPz60A/KSckskiona67tXcqOLXb8N18TKaNCKHv0Ce+GyEKK5+MT7e1vao=";
            //string encrypt = RSAEncrypt("", "chenhailong");
            byte[] encrypt = RSAEncrypt("chenhailong");
            //string name = RSADecrypt(encrypt);
            string name = RSADecrypt(Convert.FromBase64String(de));
            Console.WriteLine(encrypt.Length);
            Console.WriteLine(Convert.ToBase64String(encrypt));
            Console.WriteLine(name);
            Console.ReadKey();
        }
        /// 
        /// RSA encrypt
        /// 
        /// 
        /// 
        /// 
        public static byte[] RSAEncrypt(string content)
        {
            string publickey = @"5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=AQAB";
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(publickey);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);

            //return Convert.ToBase64String(cipherbytes);
            return cipherbytes;
        }

        /// 
        /// RSA decrypt
        /// 
        /// 
        /// 
        /// 
        public static string RSADecrypt(byte[] content)
        {
            string privatekey = @"5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=AQAB

/hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==

6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=
"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(privatekey); cipherbytes = rsa.Decrypt(content, false); return Encoding.UTF8.GetString(cipherbytes); } } }

 有什么问题 请给我留言

下面是Key的互通代码

Java代码  
  1. private byte[] removeMSZero(byte[] data) {   
  2.       byte[] data1;   
  3.       int len = data.length;   
  4.       if (data[0] == 0) {   
  5.           data1 = new byte[data.length - 1];   
  6.           System.arraycopy(data, 1, data1, 0, len - 1);   
  7.       } else  
  8.           data1 = data;   
  9.   
  10.       return data1;   
  11.   }  

转载于:https://www.cnblogs.com/wcp066/articles/2174843.html

你可能感兴趣的:(C# RSA和Java RSA互通)