当前位置 : 主页 > 编程语言 > java >

RSA加密

来源:互联网 收集:自由互联 发布时间:2021-06-28
pom.xml commons-codec commons-codec 1.9 RsaTool package org.common.serveradmin.utils;import com.alibaba.fastjson.JSON;import org.apache.commons.codec.binary.Base64;import org.common.serveradmin.emuns.ServerAdminCodeEmun;import org.common.se
pom.xml
 
      
 
        
  
   commons-codec
  
        
  
   commons-codec
  
        
  
   1.9
  
      
 
RsaTool
package org.common.serveradmin.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.common.serveradmin.emuns.ServerAdminCodeEmun;
import org.common.serveradmin.exception.ServerAdminException;

import java.io.UnsupportedEncodingException;
import java.security.*;

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 javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;


/**
 * Created by Administrator on 2017/9/28.
 */

public class RsaTool {
	private static String siyao="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKQcgRZ2VfyUj5uA+U3OhZJ2D7yNdY7z6n2os5Z8RXJTHSR9mLLBL8nLv3r9/CfcOli0x5uJVxH+Li+x+sTwJukeKUtrvRMNy8Wwlyud5wwGPvWtwGARbnwjXFt4ekdHRQ8TuYGDW1hYS2K350H91Ule1634e50PI3NugmSrcaypAgMBAAECgYEAjrI+SGLC56nhqMwfelkd6bkAe+ngk1lhxrue1DXgSMUeLPGMibnTLLseFvqre5lRnnoqqgJklD+Yt14hd4Z9vYHwZq6bJqvzs3Y9qpfPJrshSQqjs2pOW8xQkxkIH8vgSc84DgpcUo8w7G4BmzCdc+NIEAWV4yoW2JJ22/l0xhECQQDzsHI3jOnlf7OAbeNE8GHNjoPGE3jMkr84bnSeJPJfoBkwDhDIg6UNoxOMyCnNegNw3u1BMbsRBLANdR+LZEqNAkEArGbnKWg3P+hXmJv2C18shuuE9Sde6StVgiRkkftoaTEOx41jszMJMXUVgRHxvxBlWca6e2oG8DdTIV63J5ZRjQJAAtZMDh+C3Zwl/9nHqpbN3LHLEPRLFL6koUiP7QNrGvfnMysGwP7fXhBG+v2dlvnTrm25/2dP0TvnvNBfRKUvRQJAGgOZA+1+0LzdYuC9uq+Mx3sIX/ml36czSuT06/Y0phLJ+SCDl8murHDPYt9zS/JMaMSM5Qx1qY+fkpx5JJcRDQJAYyGw7qqxZrW5n24F9f9uxgJqIHM5Nlkfcp9JbnlML/mS6jFaaHDsXAmm+YtGo7+iliKrPII7go8wOv64D79fVQ==";
	private static String jiami="micQJUVIuUAnup8jPZvVJMQUHjNWsr7uqTCKH3sqS3dOnVcT4bzAorAGPu1fBDeLqn0JgWn15WTuOi3cG60+aTwsQiCtwhd3NEsssn6pIBjb832qk/GmHq5lK5QNUV5bdLZ+Yg6zYWYMEUPeb5QBW3AZsYhjIPq3Pdbw4Ach6s8=";
	
	public static String src = "this is test message";
	public static String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkHIEWdlX8lI+bgPlNzoWSdg+8jXWO8+p9qLOWfEVyUx0kfZiywS/Jy796/fwn3DpYtMebiVcR/i4vsfrE8CbpHilLa70TDcvFsJcrnecMBj71rcBgEW58I1xbeHpHR0UPE7mBg1tYWEtit+dB/dVJXtet+HudDyNzboJkq3GsqQIDAQAB";
	public static String RESULT = "E7J9MwY9PNfKTRAMK7NUC2dHMa+2DMxHY+9GU6THHti4dGkwrTwY66/7o+rEyC8Nqqblm4mWfoze9A8doZ09UYI0obYV0pfJbcrk3rkheNV0GUk467qQdCbuQSM3r56sbcC/ZBwf8S6OR1ymQfwvyiLoLlL+hvstnHnndqXHIEwRvu+77/hBHi5sWB9kKrsPTP3eeSwHP4GlwGHTYLPj2wp88HcBWhRWAl+ZziNv38ieMUL53XZQIemMG4AHi6jANSZq2MmAPlJOx0c9OJf+VuElKWH1YTbDbDKkJErZKEG7H0X6ZRpFnn7v/3vAWHDKU5J6NO9jrUXpVleLkAHBbw==";

	public static void main(String[] args) {
		Map map=new HashMap();
		map.put("code","1234");
		map.put("serviceProviderId","201710101543313668118756268");
		map.put("serviceProviderTel","18691496390");
		String str=JSON.toJSONString(map);
		try {
			System.out.println(publicKeyEncryption(str));
		} catch (ServerAdminException e) {
			e.printStackTrace();
		}

	}
	/**
	 *@Author:LiuHao
	 *@Date:14:47 2017/10/16
	 *公钥加密,私钥解密的解密 输入加密后的requestString 返回明文的requestString
	**/
	public static String privateKeyDecryption(String requestString) throws  ServerAdminException{
		if(requestString==null){
			return null;
		}
		Map requestStringMap= new HashMap();
		try {

			requestStringMap=JSON.parseObject(requestString);
			Set set=requestStringMap.keySet();
			for (Object obj:set
                 ) {
                requestStringMap.put(obj,privateKeyDecryption(siyao,requestStringMap.get(obj).toString()));
            }

		} catch (Exception e) {
			e.printStackTrace();
			throw new ServerAdminException(ServerAdminCodeEmun.TO_LONG_FAIL);
		}
		return JSON.toJSONString(requestStringMap);
	}
	/**
	 *@Author:LiuHao
	 *@Date:14:47 2017/10/16
	 *公钥加密,私钥解密的解密 输入加密后的requestString 返回明文的requestString  有些字段不加密
	 **/
	public static String privateKeyDecryptionTwo(String requestString) throws  ServerAdminException{
		if(requestString==null){
			return null;
		}

		Map requestStringMap= new HashMap();
		try {
			requestStringMap=JSON.parseObject(requestString);
			Set set=requestStringMap.keySet();
			for (Object obj:set
					) {
				String str=obj+"";
				if(!((str.equals("createName")||str.equals("serviceProviderQualificationsUrl1")||str.equals("notificationcontent")||str.equals("msgcontent"))||str.equals("communicationKey")||str.equals("refordReason"))){
					requestStringMap.put(obj,privateKeyDecryption(siyao,requestStringMap.get(obj).toString()));
				}else {
					requestStringMap.put(obj,requestStringMap.get(obj));
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new ServerAdminException(ServerAdminCodeEmun.TO_LONG_FAIL);
		}
		return JSON.toJSONString(requestStringMap);
	}
	/**
	 *@Author:LiuHao
	 *@Date:10:16 2017/10/19
	 *公钥加密,私钥解密的解密 输入加密后的userId 返回明文的userId
	**/
	public static String privateKeyDecryptionForUserId(String userId) throws  ServerAdminException{
		if(userId==null){
			return null;
		}
		String result=null;
		try {
			result=privateKeyDecryption(siyao,userId);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServerAdminException(ServerAdminCodeEmun.TO_LONG_FAIL);
		}
		return result;
	}

	// 公钥加密,私钥解密——加密 输入加密前的的requestString 返回加密后的的requestString
	//
	public static String publicKeyEncryption(String requestString) throws  ServerAdminException{
		Map requestStringMap=new HashMap();
		try {
			requestStringMap=JSON.parseObject(requestString);
			Set set=requestStringMap.keySet();
			for (Object obj:set
                    ) {
                requestStringMap.put(obj,publicKeyEncryption(PUBLIC_KEY,requestStringMap.get(obj).toString()));
            }
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServerAdminException(ServerAdminCodeEmun.TO_LONG_FAIL);
		}
		return JSON.toJSONString(requestStringMap);
	}

	/**
	 * 生成新的RSA密钥
	 * @return
	 */
	public static List
 
   createRSAKey(){
		List
  
    rsaList=new ArrayList(); KeyPairGenerator keyPairGenerator = null; try { keyPairGenerator = KeyPairGenerator .getInstance("RSA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); rsaList.add(Base64Util.byteEncodeToString(publicKey.getEncoded())); System.out.println("RSA 公钥: ---------------->"+Base64Util.byteEncodeToString(publicKey.getEncoded())); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); rsaList.add(Base64Util.byteEncodeToString(privateKey.getEncoded())); System.out.println("RSA 私钥: ---------------->"+Base64Util.byteEncodeToString(privateKey.getEncoded())); return rsaList; } // 私钥加密、公钥解密——加密 public static String privateKeyEncryption(String rsaPrivateKey,String src){ byte[] buffer_private = Base64.decodeBase64(rsaPrivateKey); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(buffer_private); byte[] result = new byte[0]; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE,privateKey); try { result = cipher.doFinal(src.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } System.out.print("ttt-私钥加密、公钥解密——加密"+Base64.encodeBase64String(result)); String s=Base64.encodeBase64String(result); return s; } // 私钥加密、公钥解密——解密 public static String publicKeyDecryption(String rsaPublicKey,String jiemi){ byte[] buffer_rsaPublicKey = Base64.decodeBase64(rsaPublicKey); byte[] buffer_jiemi = Base64.decodeBase64(jiemi); //私钥加密、公钥解密——解密 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(buffer_rsaPublicKey); String ress=null; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, publicKey); buffer_jiemi = cipher.doFinal(buffer_jiemi); ress = new String(buffer_jiemi, "UTF-8"); System.out.println(ress); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ress; } // 公钥加密,私钥解密——加密密 public static String publicKeyEncryption(String rasPublicKey,String src){ byte[] buffer = Base64.decodeBase64(rasPublicKey); //byte[] buffer = Base64Util.dncodeToString(PUBLIC_KEY).getBytes(); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(buffer); String key=null; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] result = new byte[0]; try { cipher.doFinal(src.getBytes("UTF8")); result = cipher.doFinal(src.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } key=Base64.encodeBase64String(result); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return key; } // 公钥加密,私钥解密——解密 public static String privateKeyDecryption(String rsaprivateKey,String jiami){ byte[] buffer_private = Base64.decodeBase64(rsaprivateKey); byte[] buffer_jiami = Base64.decodeBase64(jiami); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(buffer_private); String ress=null; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); buffer_jiami = cipher.doFinal(buffer_jiami); ress = new String(buffer_jiami, "UTF-8"); //System.out.print("ttt-公钥加密,私钥解密——解密" + new String(buffer_jiami, "UTF-8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ress; } // public static void jdkRas() { // // 初始化秘钥 // try { // /* // * KeyPairGenerator keyPairGenerator = // * KeyPairGenerator.getInstance("RSA"); // * keyPairGenerator.initialize(512); KeyPair keyPair = // * keyPairGenerator.generateKeyPair(); RSAPublicKey rsaPublicKey = // * (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey rsaPrivateKey = // * (RSAPrivateKey) keyPair.getPrivate(); Log.e("ttt-rsaPublicKey", // * "rsaPublicKey:" + // * Base64.encodeToString(rsaPublicKey.getEncoded(), // * Base64.DEFAULT)); Log.e("ttt-rsaPrivateKey", "rsaPrivateKey:" + // * Base64.encodeToString(rsaPrivateKey.getEncoded(), // * Base64.DEFAULT)); // * // * // * //私钥加密、公钥解密——加密 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new // * PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded()); // * KeyFactory // * keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey // * = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Cipher cipher // * = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, // * privateKey); byte[] result = cipher.doFinal(src.getBytes()); // * Log.e("ttt-私钥加密、公钥解密——加密", Base64.encodeToString(result, // * Base64.DEFAULT)); // * // * // * //私钥加密、公钥解密——解密 X509EncodedKeySpec x509EncodedKeySpec = new // * X509EncodedKeySpec(rsaPublicKey.getEncoded()); keyFactory = // * KeyFactory.getInstance("RSA"); PublicKey publicKey = // * keyFactory.generatePublic(x509EncodedKeySpec); cipher = // * Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, // * publicKey); result = cipher.doFinal(result); String ress = new // * String(result, "UTF-8"); Log.e("ttt-私钥加密、公钥解密——解密", ress); // */ // // // 公钥加密,私钥解密——加密 // byte[] buffer = Base64.decodeBase64(PUBLIC_KEY); // //byte[] buffer = Base64Util.dncodeToString(PUBLIC_KEY).getBytes(); // X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(buffer); // KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); // Cipher cipher = Cipher.getInstance("RSA"); // cipher.init(Cipher.ENCRYPT_MODE, publicKey); // cipher.doFinal(src.getBytes()); // byte[] result = cipher.doFinal(src.getBytes()); // // // 公钥加密,私钥解密——解密 // // byte[] buffer_private = Base64.decodeBase64(siyao); // byte[] buffer_jiami = Base64.decodeBase64(jiami); //// byte[] buffer_private = Base64Util.dncodeToString(siyao).getBytes(); //// byte[] buffer_jiami =Base64Util.dncodeToString(jiami).getBytes(); // PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(buffer_private); // keyFactory = KeyFactory.getInstance("RSA"); // PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); // cipher = Cipher.getInstance("RSA"); // cipher.init(Cipher.DECRYPT_MODE, privateKey); // buffer_jiami = cipher.doFinal(buffer_jiami); // String ress = new String(buffer_jiami, "UTF-8"); // System.out.print("ttt-公钥加密,私钥解密——解密" + new String(buffer_jiami, "UTF-8")); // } catch (Exception e) { // e.printStackTrace(); // // } // } // public static String decodeByPrivateKEy(String base64data, String privatekey) { // try { // byte[] result_base64 = Base64.decodeBase64(base64data); // byte[] buffer_private = Base64.decodeBase64(privatekey); // PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(buffer_private); // KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); // Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // cipher.init(Cipher.DECRYPT_MODE, privateKey); // result_base64 = cipher.doFinal(result_base64); // String result = new String(result_base64, "UTF-8"); // return result; // } catch (Exception e) { // return e.getMessage(); // } // } }
  
 
上一篇:跨工程
下一篇:极光推送
网友评论