GVKun编程网logo

Java RSA 公钥加密私钥解密(java使用rsa公钥私钥加密解密)

7

此处将为大家介绍关于JavaRSA公钥加密私钥解密的详细内容,并且为您解答有关java使用rsa公钥私钥加密解密的相关问题,此外,我们还将为您介绍关于AndroidRSA数据加密与Java服务端RSA

此处将为大家介绍关于Java RSA 公钥加密私钥解密的详细内容,并且为您解答有关java使用rsa公钥私钥加密解密的相关问题,此外,我们还将为您介绍关于Android RSA 数据加密与 Java 服务端 RSA 私钥解密出错问题、Android RSA数据加密与Java服务端RSA私钥解密出错问题、C# 与JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle来实现私钥加密,公钥解密的方法、java rsa 公钥加密的有用信息。

本文目录一览:

Java RSA 公钥加密私钥解密(java使用rsa公钥私钥加密解密)

Java RSA 公钥加密私钥解密(java使用rsa公钥私钥加密解密)

package com.lee.utils;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;

import javax.crypto.Cipher;

public class RSAUtil {

    private final static String PUBLIC_KEY_PATH = "c:/publicKeyFile";
    private final static String PRIVATE_KEY_PATH = "c:/privateKeyFile";

    /**
     *生成私钥  公钥
     */
    private 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();
        }  
    }
    
    /**
     * 获取公钥
     * @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); 
    } 
    
    
    
    /**
     * 获取私钥
     * @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); 
      } 

    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();
        } 
    } 
}

 

Android RSA 数据加密与 Java 服务端 RSA 私钥解密出错问题

Android RSA 数据加密与 Java 服务端 RSA 私钥解密出错问题

1. 出错描述:服务 RSA 解密抛出 javax.crypto.BadPaddingException: Decryption error

2. 出错原因:Android 系统使用的虚拟机(dalvik)跟 SUN 标准 JDK 是有所区别的,其中他们默认的 RSA 实现就不同。即 Android 端用 Cipher.getInstance ("RSA") 方法进行加密时,使用的 provider 是 Bouncycastle Security provider,Bouncycastle Security provider 默认实现的是 “RSA/None/NoPadding” 算法,而服务器 (PC) 端用 Cipher.getInstance ("RSA") 进行解密时,使用的是 Sun 的 security provider,实现的是 “RSA/None/PKCS1Padding” 算法,所以,解密时会失败。

3. 解决方法:Android 端的加密算法如下

/**
 * 公钥加密
 * @param data 待加密数据
 * @param key 密钥
 * @return byte[] 加密数据
 * */
public static byte[] encryptByPublicKey(byte[] data,String key) throws Exception{

    //解密密钥
    byte[] keyBytes = decryptBASE64(key);

    //实例化密钥工厂
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
    //初始化公钥
    //密钥材料转换
    X509EncodedKeySpec x509KeySpec=new X509EncodedKeySpec(keyBytes);
    //产生公钥
    PublicKey pubKey=keyFactory.generatePublic(x509KeySpec);

    //数据加密
    Cipher cipher=Cipher.getInstance("RSA/None/PKCS1Padding");//Android端使用
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    return cipher.doFinal(data);
}

Android RSA数据加密与Java服务端RSA私钥解密出错问题

Android RSA数据加密与Java服务端RSA私钥解密出错问题

 

1. 出错描述:服务RSA解密抛出javax.crypto.BadPaddingException: Decryption error

2.出错原因:Android系统使用的虚拟机(dalvik)跟SUN标准JDK是有所区别的,其中他们默认的RSA实现就不同。即Android端用Cipher.getInstance("RSA")方法进行加密时,使用的provider是Bouncycastle Security provider,Bouncycastle Security provider默认实现的是“RSA/None/NoPadding”算法,而服务器(PC)端用Cipher.getInstance("RSA")进行解密时,使用的是Sun的security provider,实现的是“RSA/None/PKCS1Padding”算法,所以,解密时会失败。

3. 解决方法:Android端的加密算法如下

/**
 * 公钥加密
 * @param data 待加密数据
 * @param key 密钥
 * @return byte[] 加密数据
 * */
public static byte[] encryptByPublicKey(byte[] data,String key) throws Exception{

    //解密密钥
    byte[] keyBytes = decryptBASE64(key);

    //实例化密钥工厂
    KeyFactory keyFactory=KeyFactory.getInstance(KEY_ALGORITHM);
    //初始化公钥
    //密钥材料转换
    X509EncodedKeySpec x509KeySpec=new X509EncodedKeySpec(keyBytes);
    //产生公钥
    PublicKey pubKey=keyFactory.generatePublic(x509KeySpec);

    //数据加密
    Cipher cipher=Cipher.getInstance("RSA/None/PKCS1Padding");//Android端使用
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    return cipher.doFinal(data);
}

C# 与JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle来实现私钥加密,公钥解密的方法

C# 与JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle来实现私钥加密,公钥解密的方法

因为C#的RSA加密解密只有公钥加密,私钥解密,没有私钥加密,公钥解密。在网上查了很久也没有很好的实现。BouncyCastle的文档少之又少。很多人可能会说,C#也是可以的,通过Biginteger开源类来实现,不过那个是有一个文章,不过他加密出来的是16进制结果的。根本不能和JAVA互通。连加密出来的都不和C#原生的加密出来的结果格式一样。所以还是没有好的解决方法。

接下来还是不断的找资料,找方法。找朋友找同事。个个都找。问题是有的,方法也是有的,所以总结各路大神之后写了这个类。实现了私钥加密,公钥解密。并通过在线的校验之后,发布上来。大家可以做一个DEMO,然后进去在线RSA加密解密校验。

在线RSA,DES等加密解密地址:

http://tool.chacuo.net/cryptrsapubkey

下面直接粘贴代码,不多说:

BouncyCastle相关DLL,估计不用我多说,大家可以百度下载。然后引用就可以了!
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto.Encodings;

namespace CryptionUtils
{
    public class RSAForJava
    {

        public RSAForJava()
        {
             
        }
        /// <summary>
        /// KEY 结构体
        /// </summary>
        public struct RSAKEY
        {
            /// <summary>
            /// 公钥
            /// </summary>
            public string PublicKey
            {
                get;
                set;
            }
            /// <summary>
            /// 私钥
            /// </summary>
            public string PrivateKey
            {
                get;
                set;
            }
        }
        public RSAKEY GetKey()
        {
            //RSA密钥对的构造器  
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();

            //RSA密钥构造器的参数  
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度  
                25);
            //用参数初始化密钥构造器  
            keyGenerator.Init(param);
            //产生密钥对  
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和密钥  
            AsymmetricKeyParameter publicKey = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            
            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8");
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");  

            RSAKEY item = new RSAKEY()
            {
                PublicKey =Convert.ToBase64String(publicInfoByte),
                PrivateKey=Convert.ToBase64String(privateInfoByte)
            };
            return item;
        }
        private AsymmetricKeyParameter GetPublicKeyParameter(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ","");
            byte[] publicInfoByte = Convert.FromBase64String(s);
            Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入   
            AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
            return pubKey;
        }
        private AsymmetricKeyParameter GetPrivateKeyParameter(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            byte[] privateInfoByte = Convert.FromBase64String(s);
           // Asn1Object priKeyObj = Asn1Object.FromByteArray(privateInfoByte);//这里也可以从流中读取,从本地导入   
           // PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
            AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
            return priKey;
        }
        public string EncryptByPrivateKey(string s,string key)
        {
            //非对称加密算法,加解密用  
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
          
          
            //加密  
            
            try
            {
                engine.Init(true, GetPrivateKeyParameter(key));
                byte[] byteData = System.Text.Encoding.UTF8.GetBytes(s);
                var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                return Convert.ToBase64String(ResultData);
                //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);
            }
            catch (Exception ex)
            {
                return ex.Message;
                
            }  
        }
        public string DecryptByPublicKey(string s,string key)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            //非对称加密算法,加解密用  
            IAsymmetricBlockCipher engine = new Pkcs1Encoding( new RsaEngine());
              

            //解密  
            
            try
            {
                engine.Init(false, GetPublicKeyParameter(key));
                byte[] byteData = Convert.FromBase64String(s);
                var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                return System.Text.Encoding.UTF8.GetString(ResultData);
                
            }
            catch (Exception ex)
            {
                return ex.Message;
                 
            }  
        }
    }
}
复制代码

 

java rsa 公钥加密

java rsa 公钥加密

 注意JAVA 的STRING .getBytes() 默认取的是操作系统的编码,最好统一UTF-8.

-- 

 

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

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;

/**
 *
 * @author jk
 */
public class RSAUtils {

    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

     //  public static final String ECB_PKCS1_PADDING = "RSA";//加密填充方式

      public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式

       private static final int _rsa_keysize = 1024;
       
    /**
     * RSA最大加密明文大小,keysize=1024, (1024/8)-11=117
     */
    private static final int MAX_ENCRYPT_BLOCK = (_rsa_keysize/8)-11;

    public static final String _charset = "UTF-8";

    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);
        // 对数据加密
        String getAgorithm = keyFactory.getAlgorithm();
        getAgorithm = ECB_PKCS1_PADDING;
        Cipher cipher = Cipher.getInstance(getAgorithm);
        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;
    }

    /**
     * java端公钥加密
     */
    public static String encryptedDataOnJava(String data, String PUBLICKEY) {
        try {
            data = Base64Utils.encode(encryptByPublicKey(data.getBytes(_charset), PUBLICKEY));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return data;
    }

}

 

--

  

package javaapplication1;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64;

/**
 *  */
/**
 * <p>
 * BASE64编码解码工具包
 * </p>
 * <p>
 * 依赖javabase64-1.3.1.jar
 * </p>
 *
 * @author IceWee
 * @date 2012-5-19
 * @version 1.0
 */
public class Base64Utils {

    /**
     *      */
    /**
     * 文件读取缓冲区大小
     */
    private static final int CACHE_SIZE = 1024;

    public static final String _charset = "UTF-8";

    /**
     *      */
    /**
     * <p>
     * BASE64字符串解码为二进制数据
     * </p>
     *
     * @param base64
     * @return
     * @throws Exception
     */
    public static byte[] decode(String str) throws Exception {
        Base64 _base64 = new Base64();
        return _base64.decodeBase64(str.getBytes(_charset));
    }

    /**
     *      */
    /**
     * <p>
     * 二进制数据编码为BASE64字符串
     * </p>
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String encode(byte[] bytes) throws Exception {
        Base64 _base64 = new Base64();
        return new String(_base64.encodeBase64Chunked(bytes));
    }

    /**
     *      */
    /**
     * <p>
     * 将文件编码为BASE64字符串
     * </p>
     * <p>
     * 大文件慎用,可能会导致内存溢出
     * </p>
     *
     * @param filePath 文件绝对路径
     * @return
     * @throws Exception
     */
    public static String encodeFile(String filePath) throws Exception {
        byte[] bytes = fileToByte(filePath);
        return encode(bytes);
    }

    /**
     *      */
    /**
     * <p>
     * BASE64字符串转回文件
     * </p>
     *
     * @param filePath 文件绝对路径
     * @param base64 编码字符串
     * @throws Exception
     */
    public static void decodeToFile(String filePath, String base64) throws Exception {
        byte[] bytes = decode(base64);
        byteArrayToFile(bytes, filePath);
    }

    /**
     *      */
    /**
     * <p>
     * 文件转换为二进制数组
     * </p>
     *
     * @param filePath 文件路径
     * @return
     * @throws Exception
     */
    public static byte[] fileToByte(String filePath) throws Exception {
        byte[] data = new byte[0];
        File file = new File(filePath);
        if (file.exists()) {
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = in.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                out.flush();
            }
            out.close();
            in.close();
            data = out.toByteArray();
        }
        return data;
    }

    /**
     *      */
    /**
     * <p>
     * 二进制数据写文件
     * </p>
     *
     * @param bytes 二进制数据
     * @param filePath 文件生成目录
     */
    public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
        InputStream in = new ByteArrayInputStream(bytes);
        File destFile = new File(filePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        destFile.createNewFile();
        OutputStream out = new FileOutputStream(destFile);
        byte[] cache = new byte[CACHE_SIZE];
        int nRead = 0;
        while ((nRead = in.read(cache)) != -1) {
            out.write(cache, 0, nRead);
            out.flush();
        }
        out.close();
        in.close();
    }

}

 

--

关于Java RSA 公钥加密私钥解密java使用rsa公钥私钥加密解密的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Android RSA 数据加密与 Java 服务端 RSA 私钥解密出错问题、Android RSA数据加密与Java服务端RSA私钥解密出错问题、C# 与JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle来实现私钥加密,公钥解密的方法、java rsa 公钥加密的相关知识,请在本站寻找。

本文标签: