C#RSACryptoServiceProvider加密

RSACryptoServiceProvider 解密只能使用私钥。具体代码如下

 

  public class RSAUtils
    {

       

        public byte[]
 StreamToBytes(Stream stream)
        {
            byte[]   bytes = new byte[stream.Length];
            stream.Read(bytes,  0, bytes.Length);
            // 设置当前流的位置为流的开始 
            stream.Seek(0,  SeekOrigin.Begin);
            return bytes;
        }

        public int keyLen = 1024;
        public int max_privatekeyLen = 128;
        public int max_publickeyeLen = 117;

        public byte[] EncrptyByPublicKey(string data, string xml)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xml);
            byte[] encryptedData;
            
                var plainData = Encoding.UTF8.GetBytes(data);
                using (var plaiStream = new MemoryStream(plainData))
                {
                    using (var crypStream = new MemoryStream())
                    {
                        var offSet = 0;
                        var inputLen = plainData.Length;
                        for (var i = 0; inputLen - offSet > 0; offSet = i * 117)
                        {
                            if (inputLen - offSet > 117)
                            {
                                var buffer = new Byte[117];
                                plaiStream.Read(buffer, 0, 117);
                                var cryptograph = rsa.Encrypt(buffer, false);
                                crypStream.Write(cryptograph, 0, cryptograph.Length);
                            }
                            else
                            {
                                var buffer = new Byte[inputLen - offSet];
                                plaiStream.Read(buffer, 0, inputLen - offSet);
                                var cryptograph = rsa.Encrypt(buffer, false);
                                crypStream.Write(cryptograph, 0, cryptograph.Length);
                            }
                            ++i;
                        }
                        crypStream.Position = 0;

                        return StreamToBytes(crypStream);
                    }
                }
                 
        }
        internal   string  DecrptyByPrivateKey(byte[] encryptedBytes, string p_xmlString )
        {
          
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

         
            rsa.FromXmlString(p_xmlString);
             byte[] decryptedData;
                using (var plaiStream = new MemoryStream(encryptedBytes))
                {
                    using (var decrypStream = new MemoryStream())
                    {
                        var offSet = 0;
                        var inputLen = encryptedBytes.Length;
                        for (var i = 0; inputLen - offSet > 0; offSet = i * 128)
                        {
                            if (inputLen - offSet > 128)
                            {
                                var buffer = new Byte[128];
                                plaiStream.Read(buffer, 0, 128);
                                var decrypData = rsa.Decrypt(buffer, false);
                                decrypStream.Write(decrypData, 0, decrypData.Length);
                            }
                            else
                            {
                                var buffer = new Byte[inputLen - offSet];
                                plaiStream.Read(buffer, 0, inputLen - offSet);
                                var decrypData = rsa.Decrypt(buffer, false);
                                decrypStream.Write(decrypData, 0, decrypData.Length);
                            }
                            ++i;
                        }
                        decrypStream.Position = 0;
                        decryptedData = StreamToBytes(decrypStream);
                    }
                return  Encoding.Default.GetString( decryptedData);
            }
        }


        //}
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="p_inputString">需要加密的字符串</param>
        /// <param name="p_dwKeySize">密钥的大小</param>
        /// <param name="p_xmlString">包含密钥的XML文本信息</param>
        /// <returns>加密后的文本信息</returns>
        public string EncryptString(string p_inputString, int p_dwKeySize, string p_xmlString)
        {
            RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(p_dwKeySize);
            rsaCryptoServiceProvider.FromXmlString(p_xmlString);
            int keySize = p_dwKeySize / 8;
            byte[] bytes = Encoding.UTF32.GetBytes(p_inputString);
            int maxLength = keySize - 42;
            int dataLength = bytes.Length;
            int iterations = dataLength / maxLength;
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i <= iterations; i++)
            {
                byte[] tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
                Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length);
                byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes, true);
                Array.Reverse(encryptedBytes);
                stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
            }
            return stringBuilder.ToString();
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="p_inputString">需要解密的字符串信息</param>
        /// <param name="p_dwKeySize">密钥的大小</param>
        /// <param name="p_xmlString">包含密钥的文本信息</param>
        /// <returns>解密后的文本信息</returns>
        public   string DecryptString(string inputString, int dwKeySize, string xmlString)
        {
            RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(dwKeySize);
            rsaCryptoServiceProvider.FromXmlString(xmlString);
            int base64BlockSize = ((dwKeySize / 8) % 3 != 0) ? (((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4;
            int iterations = inputString.Length / base64BlockSize;
            ArrayList arrayList = new ArrayList();
            for (int i = 0; i < iterations; i++)
            {
                byte[] encryptedBytes = Convert.FromBase64String(inputString.Substring(base64BlockSize * i, base64BlockSize));
                Array.Reverse(encryptedBytes);
                arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(encryptedBytes, true));
            }
            return Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[]);
        }



    } 

  测试

  //RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
            //using (StreamWriter writer = new StreamWriter("PrivateKey.xml"))  //这个文件要保密...
            //{

            //    writer.WriteLine(rsa.ToXmlString(true));

            //}
            //using (StreamWriter writer = new StreamWriter("PublicKey.xml"))
            //{

            //    writer.WriteLine(rsa.ToXmlString(false));

            //}

            RSAUtils rs = new RSAUtils();

            string privatekye = "<RSAKeyValue><Modulus>ssQGhY1z9G9pTqRNlXm+w0PYfsUCTw7Tz8e8q61muJehWAhrnK00Y4/6WIvIxaRW37rjBPvlGCUA+Cutl/RKTdUSP+ImpV28xfCj0hHTSNoWiIX3UOkXZ1zVBPPHJ8ywszdizdz3eoaAJeSs10aSJKzEmF8oRuJCYAcLb9kHuv0=</Modulus><Exponent>AQAB</Exponent><P>+8qH9nVZWlDelT0w6c1Sc4njoX3+02hvJJEc8Ah/JKw89mobpA4t73UkEWadX83CJkBZDy+37r8TszVC9w6lrw==</P><Q>tcEAts0PuU1NIEuSqGYhVU/vUzfLJosUHj12Q0E7rFdQDcoMzlogb5eIfAoUh88ZRkY0VwOzdrhaeznDeyBBEw==</Q><DP>Zfwtv/zeGT/iOA6V7k1U1SmHwtSWz6hgRC5myy6V2RPOiXyG/5cisff/iPDIU5Kyze2IZSdN1+0bHJ45JnqPTw==</DP><DQ>d7FlnfzHSRm+G/GI4Ht5oiwlCKGqmHRoyE1jj4DrImDRqHMSIea6i6K4UC93O8TH+T6Mg209h4Z6l8H/mRsxnw==</DQ><InverseQ>Sa4LkZbFwCB6HPqUFK4SNFn1CwU0eVob27QcPE5XUk3bK64tiI/o8EbQ7d1px3kkkQLMAUMA4Wk024Zt+PXlDA==</InverseQ><D>qZsoYN/DKx/lNtLWNUJsBlFBf40lUqLLvXBRBkUfl3Vtg9uBVgZTFT9OE2KUW0g/kEd9CoZ/Znf9QngWXHxPXYu7TeklvjnIbSY01n2pxHp1MgMdu4r6b3ltsdEibxsdvYeD8zd1nTvU6EQm8YH1kMkd1EU981ykI+8S/0Gv6TU=</D></RSAKeyValue>";

            string publickye = "<RSAKeyValue><Modulus>ssQGhY1z9G9pTqRNlXm+w0PYfsUCTw7Tz8e8q61muJehWAhrnK00Y4/6WIvIxaRW37rjBPvlGCUA+Cutl/RKTdUSP+ImpV28xfCj0hHTSNoWiIX3UOkXZ1zVBPPHJ8ywszdizdz3eoaAJeSs10aSJKzEmF8oRuJCYAcLb9kHuv0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

            string enstr = rs.EncryptString("WEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFDFFDFDFLLLLLLLKJLSJDFLSJDFLKSDJFLSJDLFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFIE2323232333333", 1024, publickye);

            Console.WriteLine("enstr:" + enstr);
            string destr = rs.DecryptString(enstr, 1024, privatekye);


         Console.WriteLine("desstr:"+destr);


            //byte[] enbt = rs.EncrptyByPublicKey("ddfdfdfdfd.........................f,,,,,dfdfdfd", privatekye);


            //Console.WriteLine(Encoding.Default.GetString(enbt));


            //string destr = rs.DecrptyByPrivateKey(enbt, privatekye);

            //Console.WriteLine("解密:" + destr);

  

------JAVA RSA

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map; 

import javax.crypto.Cipher;
/**
 * 
 * https://www.cnblogs.com/linjiqin/p/6005626.html
 * <p>
 * RSA公钥/私钥/签名工具包
 * </p>
 * <p>
 * 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)
 * </p>
 * <p>
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
 * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
 * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
 * </p>
 * 
 * @author IceWee
 * @date 2012-4-26
 * @version 1.0
 */
public class RSAUtils {

    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";
    
    /**
     * 签名算法
     */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * 获取公钥的key
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";
    
    /**
     * 获取私钥的key
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * <p>
     * 生成密钥对(公钥和私钥)
     * </p>
     * 
     * @return
     * @throws Exception
     */
    public static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }
    
    /**
     * <p>
     * 用私钥对信息生成数字签名
     * </p>
     * 
     * @param data 已加密数据
     * @param privateKey 私钥(BASE64编码)
     * 
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateK);
        signature.update(data);
        return Base64Utils.encode(signature.sign());
    }

    /**
     * <p>
     * 校验数字签名
     * </p>
     * 
     * @param data 已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @param sign 数字签名
     * 
     * @return
     * @throws Exception
     * 
     */
    public static boolean verify(byte[] data, String publicKey, String sign)
            throws Exception {
        byte[] keyBytes = Base64Utils.decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(Base64Utils.decode(sign));
    }

    /**
     * <P>
     * 私钥解密
     * </p>
     * 
     * @param encryptedData 已加密数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
     * <p>
     * 公钥解密
     * </p>
     * 
     * @param encryptedData 已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
            throws Exception {
        byte[] keyBytes = Base64Utils.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
     * <p>
     * 公钥加密
     * </p>
     * 
     * @param data 源数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey)
            throws Exception {
        byte[] keyBytes = Base64Utils.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * <p>
     * 私钥加密
     * </p>
     * 
     * @param data 源数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * <p>
     * 获取私钥
     * </p>
     * 
     * @param keyMap 密钥对
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Object> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return Base64Utils.encode(key.getEncoded());
    }

    /**
     * <p>
     * 获取公钥
     * </p>
     * 
     * @param keyMap 密钥对
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Object> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return Base64Utils.encode(key.getEncoded());
    }

}

  --测试

import java.util.Map;


public class RSATester {
	 static String publicKey;
	    static String privateKey;

	    static {
	        try {
	            Map<String, Object> keyMap = RSAUtils.genKeyPair();
	            publicKey = RSAUtils.getPublicKey(keyMap);
	            privateKey = RSAUtils.getPrivateKey(keyMap);
	            System.err.println("公钥: \n\r" + publicKey);
	            System.err.println("私钥: \n\r" + privateKey);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	    
	    public static void main(String[] args) throws Exception {
	        test();
	        testSign();
	        testHttpSign();
	    }

	    static void test() throws Exception {
	        System.err.println("公钥加密——私钥解密");
	        String source = "这是一行没有任何意义的文字,你看完了等于没看,不是吗?";
	        System.out.println("\r加密前文字:\r\n" + source);
	        byte[] data = source.getBytes();
	        byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
	        System.out.println("加密后文字:\r\n" + new String(encodedData));
	        byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);
	        String target = new String(decodedData);
	        System.out.println("解密后文字: \r\n" + target);
	    }

	    static void testSign() throws Exception {
	        System.err.println("私钥加密——公钥解密");
	        String source = "这是一行测试RSA数字签名的无意义文字这是一行测试RSA数字签名的无意义文字这是一行测试RSA数字签名的无意义文字这是一行测试RSA数字签名的无意义文字这是一行测试RSA数字签名的无意义文字这是一行测试RSA数字签名的无意义文字这是一行测试RSA数字签名的无意义文字";
	        System.out.println("原文字:\r\n" + source);
	        byte[] data = source.getBytes();
	        byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);
	        System.out.println("加密后:\r\n" + new String(encodedData));
	        byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);
	        String target = new String(decodedData);
	        System.out.println("解密后: \r\n" + target);
	        System.err.println("私钥签名——公钥验证签名");
	        String sign = RSAUtils.sign(encodedData, privateKey);
	        System.err.println("签名:\r" + sign);
	        boolean status = RSAUtils.verify(encodedData, publicKey, sign);
	        System.err.println("验证结果:\r" + status);
	    }
	    
	    static void testHttpSign() throws Exception {
	        String param = "id=1&name=张三";
	        byte[] encodedData = RSAUtils.encryptByPrivateKey(param.getBytes(), privateKey);
	        System.out.println("加密后:" + encodedData);
	        
	        byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);
	        System.out.println("解密后:" + new String(decodedData));
	        
	        String sign = RSAUtils.sign(encodedData, privateKey);
	        System.err.println("签名:" + sign);
	        
	        boolean status = RSAUtils.verify(encodedData, publicKey, sign);
	        System.err.println("签名验证结果:" + status);
	    }

}

  

 

------https://www.cnblogs.com/datous/p/RSAKeyConvert.html

格式转换要用到一个开源加密库Bouncy Castle Crypto APIs,官网地址: http://www.bouncycastle.org/csharp/

下载地址https://files.cnblogs.com/files/Chareree/BouncyCastle.Crypto.rar

  具体实现代码如下:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.Xml;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
 
/// <summary>
/// RSA密钥格式转换
/// </summary>
public class RSAKeyConvert
{
     /// <summary>
     /// RSA私钥格式转换,java->.net
     /// </summary>
     /// <param name="privateKey">java生成的RSA私钥</param>
     /// <returns></returns>
     public static string RSAPrivateKeyJava2DotNet( string privateKey)
     {
         RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
 
         return string .Format( "<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>" ,
             Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
             Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
             Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
             Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
             Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
             Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
             Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
             Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
     }
 
     /// <summary>
     /// RSA私钥格式转换,.net->java
     /// </summary>
     /// <param name="privateKey">.net生成的私钥</param>
     /// <returns></returns>
     public static string RSAPrivateKeyDotNet2Java( string privateKey)
     {
         XmlDocument doc = new XmlDocument();
         doc.LoadXml(privateKey);
         BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName( "Modulus" )[0].InnerText));
         BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName( "Exponent" )[0].InnerText));
         BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName( "D" )[0].InnerText));
         BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName( "P" )[0].InnerText));
         BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName( "Q" )[0].InnerText));
         BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName( "DP" )[0].InnerText));
         BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName( "DQ" )[0].InnerText));
         BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName( "InverseQ" )[0].InnerText));
 
         RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
 
         PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
         byte [] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
         return Convert.ToBase64String(serializedPrivateBytes);
     }
 
     /// <summary>
     /// RSA公钥格式转换,java->.net
     /// </summary>
     /// <param name="publicKey">java生成的公钥</param>
     /// <returns></returns>
     public static string RSAPublicKeyJava2DotNet( string publicKey)
     {
         RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
         return string .Format( "<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>" ,
             Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
             Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
     }
 
     /// <summary>
     /// RSA公钥格式转换,.net->java
     /// </summary>
     /// <param name="publicKey">.net生成的公钥</param>
     /// <returns></returns>
     public static string RSAPublicKeyDotNet2Java( string publicKey)
     {
         XmlDocument doc = new XmlDocument();
         doc.LoadXml(publicKey);
         BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName( "Modulus" )[0].InnerText));
         BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName( "Exponent" )[0].InnerText));
         RsaKeyParameters pub = new RsaKeyParameters( false , m, p);
 
         SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
         byte [] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
         return Convert.ToBase64String(serializedPublicBytes);
     }
}

转载于:https://www.cnblogs.com/Chareree/p/8708630.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值