您现在的位置是:网站首页> C#技术

ASP.NET JAVA Go的非对称加密和AES对称加解密

摘要

//JAVA端代码

// Java,需要以下引用:


import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

import java.security.KeyFactory;

import java.security.NoSuchAlgorithmException;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.interfaces.RSAPrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.security.spec.InvalidKeySpecException;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import java.util.*;


import static java.util.Base64.getEncoder;


//另外需要对String和byte[]相互转换的类,我自己写的Base64Helper


 // @author miracle.qu

 // @see AES算法加密明文

 // @param data 明文

 // @param key 密钥,长度16

 // @param iv 偏移量,长度16

 //@return 密文



public class Main {


    public static String encryptAES(String data,String key,String iv) throws Exception {

        try {

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = data.getBytes("utf-8");

            int plaintextLength = dataBytes.length;


            if (plaintextLength % blockSize != 0) {

                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));

            }


            byte[] plaintext = new byte[plaintextLength];

            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);


            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");

            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());


            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

            byte[] encrypted = cipher.doFinal(plaintext);


            return Base64.getEncoder().encodeToString(encrypted );


            //return Base64Helper.encode(encrypted).trim();


        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }


    // @author miracle.qu

    // @see AES算法解密密文

    // @param data 密文

    // @param key 密钥,长度16

    //@param iv 偏移量,长度16

    //@return 明文


    public static String decryptAES(String data,String key,String iv) throws Exception {

        try

        {

            byte[] encrypted1 = Base64.getDecoder().decode(data);


            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");

            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());


            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);


            byte[] original = cipher.doFinal(encrypted1);

            String originalString = new String(original);

            return originalString.trim();

        }

        catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }





    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {

        String data="";

        try {

            data=encryptAES("xn忠魂", "aaabbbcccdddeeef", "1234567890abcdef");

            System.out.println(data);

        }catch(Exception e)

        {

            System.out.println(e.toString());

        }

        try

        {

            String outString=decryptAES(data,"aaabbbcccdddeeef", "1234567890abcdef");

            System.out.println(outString);


        }catch(Exception e)

        {

            System.out.println(e.toString());

        }



        String src="中华";


        String publicKeyString="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVTy+1uRxJeWtkPAm/y7CSix0LS148IeU4NXPbR8DEiT6m26wz9OYR9/Aj2Z64ncQBytsQlHUI5opmRFtkDGqgfKadhG0GcAQMRCH/wNCFKdJX20TAdHtJ1jTzQb/vrd0EszPR247Z5jeQMMGtyQbZO9xvDL4jOAqur4dCigFLhQIDAQAB";

        String privateKeyString="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANVPL7W5HEl5a2Q8Cb/LsJKLHQtLXjwh5Tg1c9tHwMSJPqbbrDP05hH38CPZnridxAHK2xCUdQjmimZEW2QMaqB8pp2EbQZwBAxEIf/A0IUp0lfbRMB0e0nWNPNBv++t3QSzM9HbjtnmN5Awwa3JBtk73G8MviM4Cq6vh0KKAUuFAgMBAAECgYACpWnVGkfEjZIMe0Yvr+ov1zP0COpRWqZKTTdzt+8nQQCa90yqlFYqUOYUu8VhSuu8jfSrvvu4sYtz+1Ma6aCE+VWBuXIAEBI9LsE78GNKyYTJ72uEt0VEMSRmyEMbspvMMsbQFMA9zL1qWC14eNEAghlYUk5MbeAykji6aWnnAQJBAP3z2k8+sZx+MDA05nvP41lcqDsdLfl7TtARsTm8e73DLMjdM7S37z2yoGJ+bv13p2rftgIHUTiXBHKqDmQ0I8UCQQDXB3Kc3T8Tqf3FtDOGHElkRf7pEIr9XfwnpLLdieuuw6BQq/71TSOoc5dzonNKTtsxEqHZtkYihXj752U5ikTBAkB0odEqwf1qhR32leUhCfo9aWuuMpmR0gsBTo7ZmHIwVfo0ijscDbnn2SkF81FgQdr3H6WEyv2Hgvw8+VNAvB2NAkAoW1F7d1q7ShBC5ss0xGJR24E4JM6xNs54ckTPp28AYd7YxS8Ywt2KZAdswHR64cnpr+GIhtkq6XoHbSpmXjkBAkEA8HP1XnU7F69JjSi0GJZK2I03LiU6K9QIZH5NcdDaxAwvWrlDjT0Im2uiwcRXCyaH/57zJ4iuIqfJmLG6Df5f4g==";



        RSAPrivateKey rsaprivateKey;

        RSAPublicKey rsapublicKey;

        try {

            //PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaprivateKey.getEncoded());

            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));

            KeyFactory privateKeyFactory = KeyFactory.getInstance("RSA");

            PrivateKey privateKey = privateKeyFactory.generatePrivate(pkcs8EncodedKeySpec);

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

            privateCipher.init(Cipher.ENCRYPT_MODE, privateKey);

            byte[] result = privateCipher.doFinal(src.getBytes());

            //System.out.println("私钥加密,公钥解密--加密:"+Base64.encodeBase64String(result));

            System.out.println("私钥加密,公钥解密--加密:" + Base64.getEncoder().encodeToString(result));


            //私钥加密,公钥解密--解密

            //X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsapublicKey.getEncoded());

            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyString));

            KeyFactory publicKeyFactory = KeyFactory.getInstance("RSA");

            PublicKey publicKey = publicKeyFactory.generatePublic(x509EncodedKeySpec);

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

            publicCipher.init(Cipher.DECRYPT_MODE, publicKey);

            result = publicCipher.doFinal(result);

            System.out.println("私钥加密,公钥解密--解密:" + new String(result));



            //公钥加密,私钥解密---加密

            //x509EncodedKeySpec = new X509EncodedKeySpec(rsapublicKey.getEncoded());

            x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyString));

            publicKeyFactory = KeyFactory.getInstance("RSA");

            publicKey = publicKeyFactory.generatePublic(x509EncodedKeySpec);

            publicCipher = Cipher.getInstance("RSA");

            publicCipher.init(Cipher.ENCRYPT_MODE, publicKey);

            result = publicCipher.doFinal(src.getBytes());

            //System.out.println("公钥加密,私钥解密---加密:"+Base64.encodeBase64String(result));

            System.out.println("公钥加密,私钥解密---加密:" + Base64.getEncoder().encodeToString(result));



            //公钥加密,私钥解密---解密

            //pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaprivateKey.getEncoded());

            pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));

            privateKeyFactory = KeyFactory.getInstance("RSA");

            privateKey = privateKeyFactory.generatePrivate(pkcs8EncodedKeySpec);

            privateCipher = Cipher.getInstance("RSA");

            privateCipher.init(Cipher.DECRYPT_MODE, privateKey);

            result = privateCipher.doFinal(result);

            System.out.println("公钥加密,私钥解密---解密:" + new String(result));

        }

        catch(Exception ex)

        {

            System.out.println(ex.toString());

        }




    }

}


DotNot的


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Security.Cryptography;


namespace XNWebEngine.JsonBase

{

    public class AESJavaASPDotNet

    {

        /// <summary>AES加密</summary>

        /// <param name="text">明文</param>

        /// <param name="key">密钥,长度为16的字符串</param>

        /// <param name="iv">偏移量,长度为16的字符串</param>

        /// <returns>密文</returns>

        public static string EncodeAES(string text, string key, string iv)

        {

            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            rijndaelCipher.Mode = CipherMode.CBC;

            rijndaelCipher.Padding = PaddingMode.Zeros;

            rijndaelCipher.KeySize = 128;

            rijndaelCipher.BlockSize = 128;

            byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);

            byte[] keyBytes = new byte[16];

            int len = pwdBytes.Length;

            if (len > keyBytes.Length)

                len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;

            rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv);

            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

            byte[] plainText = Encoding.UTF8.GetBytes(text);

            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);

            return Convert.ToBase64String(cipherBytes);

        }


        /// <summary>AES解密</summary>

        /// <param name="text">密文</param>

        /// <param name="key">密钥,长度为16的字符串</param>

        /// <param name="iv">偏移量,长度为16的字符串</param>

        /// <returns>明文</returns>

        public static string DecodeAES(string text, string key, string iv)

        {

            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            rijndaelCipher.Mode = CipherMode.CBC;

            rijndaelCipher.Padding = PaddingMode.Zeros;

            rijndaelCipher.KeySize = 128;

            rijndaelCipher.BlockSize = 128;

            byte[] encryptedData = Convert.FromBase64String(text);

            byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);

            byte[] keyBytes = new byte[16];

            int len = pwdBytes.Length;

            if (len > keyBytes.Length)

                len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;

            rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv);

            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();

            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

            return Encoding.UTF8.GetString(plainText);

        }

    }

}


namespace XNWebEngine.JsonBase

{

    public class RESJavaHelper

    {

    /// <summary>

        /// 生成公钥和私钥对

        /// </summary>

        public static void GeneratePublicAndPrivateKeyInfo()

        {

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            using (StreamWriter writer = new StreamWriter("PrivateKey.xml"))  //这个文件要保密...

            {

                string privateKey = rsa.ToXmlString(true);

                writer.WriteLine(privateKey);

            }

            using (StreamWriter writer = new StreamWriter("PublicKey.xml"))

            {

                string publicKey = rsa.ToXmlString(false);

                writer.WriteLine(publicKey);

            }

        }


        public static void GeneratePublicAndPrivateKeyInfo(out string privateKey, out string publicKey)

        {

            privateKey = "";

            publicKey = "";

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            privateKey = rsa.ToXmlString(true);

            publicKey = rsa.ToXmlString(false);

            

        }

 

        /// <summary>

        /// 用私钥给数据进行RSA加密

        /// </summary>

        /// <param name="xmlPrivateKey"> 私钥(XML格式字符串)</param>

        /// <param name="strEncryptString">要加密的数据</param>

        /// <returns> 加密后的数据 </returns>

        public static string PrivateKeyEncrypt(string xmlPrivateKey, string strEncryptString)

        {

            //加载私钥

            RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider();

            privateRsa.FromXmlString(ReadFile(xmlPrivateKey));

 

            //转换密钥

            AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);

            IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //使用RSA/ECB/PKCS1Padding格式

            //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥

 

            c.Init(true, keyPair.Private);

            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString);

            #region 分段加密

            int bufferSize = (privateRsa.KeySize / 8) - 11;

            byte[] buffer = new byte[bufferSize];

            byte[] outBytes = null;

            //分段加密

            using (MemoryStream input = new MemoryStream(dataToEncrypt))

            using (MemoryStream ouput = new MemoryStream())

            {

                while (true)

                {

                    int readLine = input.Read(buffer, 0, bufferSize);

                    if (readLine <= 0)

                    {

                        break;

                    }

                    byte[] temp = new byte[readLine];

                    Array.Copy(buffer, 0, temp, 0, readLine);

                    byte[] encrypt = c.DoFinal(temp);

                    ouput.Write(encrypt, 0, encrypt.Length);

                }

                outBytes = ouput.ToArray();

            }

            #endregion

            //byte[] outBytes = c.DoFinal(DataToEncrypt);//加密

            string strBase64 = Convert.ToBase64String(outBytes);

 

            return strBase64;

        }

 

        /// <summary>

        /// 用公钥给数据进行RSA解密 

        /// </summary>

        /// <param name="xmlPublicKey"> 公钥(XML格式字符串) </param>

        /// <param name="strDecryptString"> 要解密数据 </param>

        /// <returns> 解密后的数据 </returns>

        public static string PublicKeyDecrypt(string xmlPublicKey, string strDecryptString)

        {

            //加载公钥

            RSACryptoServiceProvider publicRsa = new RSACryptoServiceProvider();

            publicRsa.FromXmlString(ReadFile(xmlPublicKey));

            RSAParameters rp = publicRsa.ExportParameters(false);

 

            //转换密钥

            AsymmetricKeyParameter pbk = DotNetUtilities.GetRsaPublicKey(rp);

 

            IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");

            //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥

            c.Init(false, pbk);

            byte[] outBytes = null;

            byte[] dataToDecrypt = Convert.FromBase64String(strDecryptString);

            #region 分段解密

            int keySize = publicRsa.KeySize / 8;

            byte[] buffer = new byte[keySize];

 

            using (MemoryStream input = new MemoryStream(dataToDecrypt))

            using (MemoryStream output = new MemoryStream())

            {

                while (true)

                {

                    int readLine = input.Read(buffer, 0, keySize);

                    if (readLine <= 0)

                    {

                        break;

                    }

                    byte[] temp = new byte[readLine];

                    Array.Copy(buffer, 0, temp, 0, readLine);

                    byte[] decrypt = c.DoFinal(temp);

                    output.Write(decrypt, 0, decrypt.Length);

                }

                outBytes = output.ToArray();

            }

            #endregion

            //byte[] outBytes = c.DoFinal(DataToDecrypt);//解密

 

            string strDec = Encoding.UTF8.GetString(outBytes);

            return strDec;

        }

 

        /// <summary>

        /// 使用公钥加密,分段加密

        /// </summary>

        /// <param name="content"></param>

        /// <param name="privateKeyPath"></param>

        /// <returns></returns>

        public static string EncrytByPublic(string publicKeyPath, string strEncryptString)

        {

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.FromXmlString(ReadFile(publicKeyPath));

            byte[] originalData = Encoding.UTF8.GetBytes(strEncryptString);

            if (originalData == null || originalData.Length <= 0)

            {

                throw new NotSupportedException();

            }

            if (rsa == null)

            {

                throw new ArgumentNullException();

            }

            byte[] encryContent = null;

            #region 分段加密

            int bufferSize = (rsa.KeySize / 8) - 11;

            byte[] buffer = new byte[bufferSize];

            //分段加密

            using (MemoryStream input = new MemoryStream(originalData))

            using (MemoryStream ouput = new MemoryStream())

            {

                while (true)

                {

                    int readLine = input.Read(buffer, 0, bufferSize);

                    if (readLine <= 0)

                    {

                        break;

                    }

                    byte[] temp = new byte[readLine];

                    Array.Copy(buffer, 0, temp, 0, readLine);

                    byte[] encrypt = rsa.Encrypt(temp, false);

                    ouput.Write(encrypt, 0, encrypt.Length);

                }

                encryContent = ouput.ToArray();

            }

            #endregion

            return Convert.ToBase64String(encryContent);

        }

 

        /// <summary>

        /// 通过私钥解密,分段解密

        /// </summary>

        /// <param name="content"></param>

        /// <param name="privateKeyPath"></param>

        /// <returns></returns>

        public static string DecryptByPrivate(string privateKeyPath, string strDecryptString)

        {

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.FromXmlString(ReadFile(privateKeyPath));

            byte[] encryptData = Convert.FromBase64String(strDecryptString);

            //byte[] dencryContent = rsa.Decrypt(encryptData, false);

            byte[] dencryContent = null;

            #region 分段解密

            if (encryptData == null || encryptData.Length <= 0)

            {

                throw new NotSupportedException();

            }

 

            int keySize = rsa.KeySize / 8; 

            byte[] buffer = new byte[keySize];

 

            using (MemoryStream input = new MemoryStream(encryptData))

            using (MemoryStream output = new MemoryStream())

            {

                while (true)

                {

                    int readLine = input.Read(buffer, 0, keySize);

                    if (readLine <= 0)

                    {

                        break;

                    }

                    byte[] temp = new byte[readLine];

                    Array.Copy(buffer, 0, temp, 0, readLine);

                    byte[] decrypt = rsa.Decrypt(temp, false);

                    output.Write(decrypt, 0, decrypt.Length);

                }

                dencryContent = output.ToArray();

            }

            #endregion

            return Encoding.UTF8.GetString(dencryContent);

        }







        public static string PrivateKeyStringEncrypt(string xmlPrivateKey, string strEncryptString)

        {

            //加载私钥

            RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider();

            privateRsa.FromXmlString(xmlPrivateKey);


            //转换密钥

            AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);

            IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //使用RSA/ECB/PKCS1Padding格式

            //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥


            c.Init(true, keyPair.Private);

            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString);

            #region 分段加密

            int bufferSize = (privateRsa.KeySize / 8) - 11;

            byte[] buffer = new byte[bufferSize];

            byte[] outBytes = null;

            //分段加密

            using (MemoryStream input = new MemoryStream(dataToEncrypt))

            using (MemoryStream ouput = new MemoryStream())

            {

                while (true)

                {

                    int readLine = input.Read(buffer, 0, bufferSize);

                    if (readLine <= 0)

                    {

                        break;

                    }

                    byte[] temp = new byte[readLine];

                    Array.Copy(buffer, 0, temp, 0, readLine);

                    byte[] encrypt = c.DoFinal(temp);

                    ouput.Write(encrypt, 0, encrypt.Length);

                }

                outBytes = ouput.ToArray();

            }

            #endregion

            //byte[] outBytes = c.DoFinal(DataToEncrypt);//加密

            string strBase64 = Convert.ToBase64String(outBytes);


            return strBase64;

        }


        /// <summary>

        /// 用公钥给数据进行RSA解密 

        /// </summary>

        /// <param name="xmlPublicKey"> 公钥(XML格式字符串) </param>

        /// <param name="strDecryptString"> 要解密数据 </param>

        /// <returns> 解密后的数据 </returns>

        public static string PublicKeyStringDecrypt(string xmlPublicKey, string strDecryptString)

        {

            //加载公钥

            RSACryptoServiceProvider publicRsa = new RSACryptoServiceProvider();

            publicRsa.FromXmlString(xmlPublicKey);

            RSAParameters rp = publicRsa.ExportParameters(false);


            //转换密钥

            AsymmetricKeyParameter pbk = DotNetUtilities.GetRsaPublicKey(rp);


            IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");

            //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥

            c.Init(false, pbk);

            byte[] outBytes = null;

            byte[] dataToDecrypt = Convert.FromBase64String(strDecryptString);

            #region 分段解密

            int keySize = publicRsa.KeySize / 8;

            byte[] buffer = new byte[keySize];


            using (MemoryStream input = new MemoryStream(dataToDecrypt))

            using (MemoryStream output = new MemoryStream())

            {

                while (true)

                {

                    int readLine = input.Read(buffer, 0, keySize);

                    if (readLine <= 0)

                    {

                        break;

                    }

                    byte[] temp = new byte[readLine];

                    Array.Copy(buffer, 0, temp, 0, readLine);

                    byte[] decrypt = c.DoFinal(temp);

                    output.Write(decrypt, 0, decrypt.Length);

                }

                outBytes = output.ToArray();

            }

            #endregion

            //byte[] outBytes = c.DoFinal(DataToDecrypt);//解密


            string strDec = Encoding.UTF8.GetString(outBytes);

            return strDec;

        }


        /// <summary>

        /// 使用公钥加密,分段加密

        /// </summary>

        /// <param name="content"></param>

        /// <param name="privateKeyPath"></param>

        /// <returns></returns>

        public static string EncrytByPublicString(string publicKeyPath, string strEncryptString)

        {

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.FromXmlString(publicKeyPath);

            byte[] originalData = Encoding.UTF8.GetBytes(strEncryptString);

            if (originalData == null || originalData.Length <= 0)

            {

                throw new NotSupportedException();

            }

            if (rsa == null)

            {

                throw new ArgumentNullException();

            }

            byte[] encryContent = null;

            #region 分段加密

            int bufferSize = (rsa.KeySize / 8) - 11;

            byte[] buffer = new byte[bufferSize];

            //分段加密

            using (MemoryStream input = new MemoryStream(originalData))

            using (MemoryStream ouput = new MemoryStream())

            {

                while (true)

                {

                    int readLine = input.Read(buffer, 0, bufferSize);

                    if (readLine <= 0)

                    {

                        break;

                    }

                    byte[] temp = new byte[readLine];

                    Array.Copy(buffer, 0, temp, 0, readLine);

                    byte[] encrypt = rsa.Encrypt(temp, false);

                    ouput.Write(encrypt, 0, encrypt.Length);

                }

                encryContent = ouput.ToArray();

            }

            #endregion

            return Convert.ToBase64String(encryContent);

        }


        /// <summary>

        /// 通过私钥解密,分段解密

        /// </summary>

        /// <param name="content"></param>

        /// <param name="privateKeyPath"></param>

        /// <returns></returns>

        public static string DecryptByPrivateString(string privateKeyPath, string strDecryptString)

        {

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.FromXmlString(privateKeyPath);

            byte[] encryptData = Convert.FromBase64String(strDecryptString);

            //byte[] dencryContent = rsa.Decrypt(encryptData, false);

            byte[] dencryContent = null;

            #region 分段解密

            if (encryptData == null || encryptData.Length <= 0)

            {

                throw new NotSupportedException();

            }


            int keySize = rsa.KeySize / 8;

            byte[] buffer = new byte[keySize];


            using (MemoryStream input = new MemoryStream(encryptData))

            using (MemoryStream output = new MemoryStream())

            {

                while (true)

                {

                    int readLine = input.Read(buffer, 0, keySize);

                    if (readLine <= 0)

                    {

                        break;

                    }

                    byte[] temp = new byte[readLine];

                    Array.Copy(buffer, 0, temp, 0, readLine);

                    byte[] decrypt = rsa.Decrypt(temp, false);

                    output.Write(decrypt, 0, decrypt.Length);

                }

                dencryContent = output.ToArray();

            }

            #endregion

            return Encoding.UTF8.GetString(dencryContent);

        }

 







        /// <summary>

        /// 读取文件

        /// </summary>

        /// <param name="filePath"></param>

        /// <returns></returns>

        public static string ReadFile(string filePath)

        {

            string content = "";

            if (File.Exists(filePath))

            {

                content = File.ReadAllText(filePath);

                byte[] mybyte = Encoding.UTF8.GetBytes(content);

                content = Encoding.UTF8.GetString(mybyte);

            }

            return content;

        }

 

        /// <summary>

        /// 将私钥转换成java所用的私钥字符串

        /// </summary>

        /// <param name="privateKeyPath">私钥文件路径</param>

        /// <returns></returns>

        public static string RSAPrivateKeyDotNet2Java(string privateKeyPath)

        {

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(ReadFile(privateKeyPath));

            Org.BouncyCastle.Math.BigInteger m = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger exp = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math. BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger p = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger q = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger dp = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger dq = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger qinv = new Org.BouncyCastle.Math.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>

        /// 将公钥转换成java所用的公钥字符串

        /// </summary>

        /// <param name="publicKeyPath">公钥路径</param>

        /// <returns></returns>

        public static string RSAPublicKeyDotNet2Java(string publicKeyPath)

        {

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(ReadFile(publicKeyPath));

            Org.BouncyCastle.Math.BigInteger m = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger p = new Org.BouncyCastle.Math.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);

        }



        public static string RSAPrivateKeyStringDotNet2Java(string privateKeyString)

        {

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(privateKeyString);

            Org.BouncyCastle.Math.BigInteger m = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger exp = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger p = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger q = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger dp = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger dq = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger qinv = new Org.BouncyCastle.Math.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>

        /// 将公钥转换成java所用的公钥字符串

        /// </summary>

        /// <param name="publicKeyPath">公钥路径</param>

        /// <returns></returns>

        public static string RSAPublicKeyStringDotNet2Java(string publicKeyPath)

        {

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(publicKeyPath);

            Org.BouncyCastle.Math.BigInteger m = new Org.BouncyCastle.Math.BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));

            Org.BouncyCastle.Math.BigInteger p = new Org.BouncyCastle.Math.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);

        }

    

}


}



//Go的对称加密算法

// HelloAES project main.go

package main


import (

"fmt"

//"net/http"


// "io/ioutil"


//"encoding/json"


//"strconv"


"bytes"

"crypto/aes"

"crypto/cipher"


//"crypto/rand"

//"crypto/rsa"

//"crypto/sha1"

//"crypto/sha256"


// "time"

//"crypto/rand"

"encoding/base64"

//"io"

"github.com/Lyafei/go-rsa"

)


func PKCS5Padding(ciphertext []byte, blockSize int) []byte {

padding := blockSize - len(ciphertext)%blockSize

padtext := bytes.Repeat([]byte{byte(padding)}, padding)

return append(ciphertext, padtext...)

}


func PKCS5UnPadding(origData []byte) []byte {

length := len(origData)

unpadding := int(origData[length-1])

return origData[:(length - unpadding)]

}


//使用PKCS7进行填充

func PKCS7Padding(ciphertext []byte, blockSize int) []byte {

padding := blockSize - len(ciphertext)%blockSize

padtext := bytes.Repeat([]byte{byte(padding)}, padding)

return append(ciphertext, padtext...)

}


func PKCS7UnPadding(origData []byte) []byte {

length := len(origData)

unpadding := int(origData[length-1])

return origData[:(length - unpadding)]

}


func ZerosPadding(ciphertext []byte, blockSize int) []byte {

padding := blockSize - len(ciphertext)%blockSize

fmt.Println("padding", padding)

padtext := bytes.Repeat([]byte{byte(0)}, padding)

return append(ciphertext, padtext...)

}


func ZerosUnPadding(origData []byte) []byte {

length := len(origData)

unpadding := int(origData[length-1])

return origData[:(length - unpadding)]

}


//aes加密,填充秘钥key的16位,24,32分别对应AES-128, AES-192, or AES-256.

func AesCBCEncrypt(rawData, key []byte, iv []byte) ([]byte, error) {

block, err := aes.NewCipher(key)

if err != nil {

panic(err)

}

//填充原文

blockSize := block.BlockSize()


//fmt.Println(blockSize)


//rawData = PKCS5Padding(rawData, blockSize)

rawData = ZerosPadding(rawData, blockSize)


//初始向量IV必须是唯一,但不需要保密

cipherText := make([]byte, blockSize+len(rawData))


//block大小 16

/*

iv := cipherText[:blockSize]


if _, err := io.ReadFull(rand.Reader, iv); err != nil {

panic(err)

}

*/


//block大小和初始向量大小一定要一致

mode := cipher.NewCBCEncrypter(block, iv)


mode.CryptBlocks(cipherText[blockSize:], rawData)


return cipherText, nil

}


func AesCBCDncrypt(encryptData, key []byte, iv []byte) ([]byte, error) {

block, err := aes.NewCipher(key)

if err != nil {

panic(err)

}


blockSize := block.BlockSize()


if len(encryptData) < blockSize {

panic("ciphertext too short")

}

/*

iv := encryptData[:blockSize]

*/


encryptData = encryptData[blockSize:]

fmt.Println("encryptData=", encryptData)

fmt.Println(len(encryptData) % blockSize)


// CBC mode always works in whole blocks.

if len(encryptData)%blockSize != 0 {

panic("ciphertext is not a multiple of the block size")

}


mode := cipher.NewCBCDecrypter(block, iv)


// CryptBlocks can work in-place if the two arguments are the same.

mode.CryptBlocks(encryptData, encryptData)

//解填充

//encryptData = PKCS5UnPadding(encryptData)

encryptData = ZerosUnPadding(encryptData)

return encryptData, nil

}


func Encrypt(rawData, key []byte, iv []byte) (string, error) {

data, err := AesCBCEncrypt(rawData, key, iv)

if err != nil {

return "", err

}

fmt.Println("data", data)


data = data[16:]

fmt.Println("outdata", data)


//return base64.EncodeToString(data), nil

return base64.StdEncoding.EncodeToString(data), nil

}


func Dncrypt(rawData string, key []byte, iv []byte) (string, error) {


data, err := base64.StdEncoding.DecodeString(rawData)

fmt.Println("dn data", data)

if err != nil {

return "", err

}

zeroArray := [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

data = append(zeroArray[:], data...)


dnData, err := AesCBCDncrypt(data, key, iv)

if err != nil {

return "", err

}

return string(dnData), nil //


}


func main() {

fmt.Println("Hello World!")


var data []byte = []byte("xn忠魂{:程序员}")


outJMData, _ := Encrypt(data, []byte("aaabbbcccdddeeef"), []byte("1234567890abcdef"))


fmt.Println(outJMData)

outData, _ := Dncrypt(outJMData, []byte("aaabbbcccdddeeef"), []byte("1234567890abcdef"))

fmt.Println(outData)


//m_Data := make(map[string]interface{})


publicKeyString := "-----BEGIN Public key-----\r\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVTy+1uRxJeWtkPAm/y7CSix0LS148IeU4NXPbR8DEiT6m26wz9OYR9/Aj2Z64ncQBytsQlHUI5opmRFtkDGqgfKadhG0GcAQMRCH/wNCFKdJX20TAdHtJ1jTzQb/vrd0EszPR247Z5jeQMMGtyQbZO9xvDL4jOAqur4dCigFLhQIDAQAB\r\n-----END Public key-----"

privateKeyString := "-----BEGIN Private key-----\r\nMIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANVPL7W5HEl5a2Q8Cb/LsJKLHQtLXjwh5Tg1c9tHwMSJPqbbrDP05hH38CPZnridxAHK2xCUdQjmimZEW2QMaqB8pp2EbQZwBAxEIf/A0IUp0lfbRMB0e0nWNPNBv++t3QSzM9HbjtnmN5Awwa3JBtk73G8MviM4Cq6vh0KKAUuFAgMBAAECgYACpWnVGkfEjZIMe0Yvr+ov1zP0COpRWqZKTTdzt+8nQQCa90yqlFYqUOYUu8VhSuu8jfSrvvu4sYtz+1Ma6aCE+VWBuXIAEBI9LsE78GNKyYTJ72uEt0VEMSRmyEMbspvMMsbQFMA9zL1qWC14eNEAghlYUk5MbeAykji6aWnnAQJBAP3z2k8+sZx+MDA05nvP41lcqDsdLfl7TtARsTm8e73DLMjdM7S37z2yoGJ+bv13p2rftgIHUTiXBHKqDmQ0I8UCQQDXB3Kc3T8Tqf3FtDOGHElkRf7pEIr9XfwnpLLdieuuw6BQq/71TSOoc5dzonNKTtsxEqHZtkYihXj752U5ikTBAkB0odEqwf1qhR32leUhCfo9aWuuMpmR0gsBTo7ZmHIwVfo0ijscDbnn2SkF81FgQdr3H6WEyv2Hgvw8+VNAvB2NAkAoW1F7d1q7ShBC5ss0xGJR24E4JM6xNs54ckTPp28AYd7YxS8Ywt2KZAdswHR64cnpr+GIhtkq6XoHbSpmXjkBAkEA8HP1XnU7F69JjSi0GJZK2I03LiU6K9QIZH5NcdDaxAwvWrlDjT0Im2uiwcRXCyaH/57zJ4iuIqfJmLG6Df5f4g==\r\n-----END Private key-----"


str := "中华"

prienctypt, err := gorsa.PriKeyEncrypt(str, privateKeyString)

if err != nil {

fmt.Println(err)

return

}

//fmt.Println(publicKeyString)

fmt.Println("私钥加密后:", prienctypt)


pubdecrypt, err := gorsa.PublicDecrypt(prienctypt, publicKeyString)

if err != nil {

return

}

fmt.Println("公钥解密后:", string(pubdecrypt))


pubenctypt, err := gorsa.PublicEncrypt(str, publicKeyString)

if err != nil {

fmt.Println(err)

return

}


fmt.Println("公钥加密后:", pubenctypt)


pridecrypt, err := gorsa.PriKeyDecrypt(pubenctypt, privateKeyString)

if err != nil {

return

}

fmt.Println("私钥解密后:", string(pridecrypt))


}


Top