RSA加密突破117长度限制

编程

RSA 加密   突破117长度限制

package com.topnet.utils;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Map;

import org.apache.commons.io.IOUtils;

/**

* 加密解密工具

*

* @author lpf

*

*/

public class EncryptionTool {

private static String publicKey = null;

private static String privateKey = null;

/**

* 配置公钥

*

* @param publicKey

*/

public static void setPublicKey(String publicKey) {

EncryptionTool.publicKey = publicKey;

}

/**

* 配置私钥

*

* @param privateKey

*/

public static void setPrivateKey(String privateKey) {

EncryptionTool.privateKey = privateKey;

}

public static void main(String[] args) {

String text =

"{"UNISCID":"统一社会信用代码","ENTTYPE":"市场主体类型","OPFROM":"经营(驻在)期限自","OPTO":"经营(驻在)期限至","APPRDATE":"核准日期"}";

String encrypt = encrypt(text);

System.out.println(decrypt(encrypt));;

generatorKey("/home/lpf/myproject/TopEncryption/src/main/resources");

}

/**

* 生成一对密码,放到文件夹

*

* @param folder 文件夹路径

* @return

*/

public static void generatorKey(String folder) {

ByteArrayInputStream in = null;

FileOutputStream out = null;

try {

File f = new File(folder);

if (!f.exists()) {

f.mkdirs();

}

Map<String, String> m = RSACoder.base64Key();

in = new ByteArrayInputStream(m.get("RSAPublicKey").toString().getBytes());

out = new FileOutputStream(folder + File.separator + "publickKey");

// out = new FileOutputStream(folder);

IOUtils.copy(in, out);

IOUtils.closeQuietly(in);

IOUtils.closeQuietly(out);

in = new ByteArrayInputStream(m.get("RSAPrivateKey").toString().getBytes());

out = new FileOutputStream(folder + File.separator + "privateKey");

IOUtils.copy(in, out);

IOUtils.closeQuietly(in);

IOUtils.closeQuietly(out);

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

IOUtils.closeQuietly(in);

IOUtils.closeQuietly(out);

}

}

/**

* 加密

*

* @param data

* @return

*/

public static String encrypt(String data) {

try {

return RSACoder.encryptAndBase64ByPublicKey(data, getPublicKey());

} catch (Exception e) {

throw new RuntimeException(e);

}

}

/**

* 解密

*

* @param data

* @return

*/

public static String decrypt(String data) {

try {

return new String(

RSACoder.decryptByPrivateKey(RSACoder.decryptBASE64(data), getPrivateKey()));

} catch (Exception e) {

throw new RuntimeException(e);

}

}

/**

* 得到公要

*

* @return

*/

private static String getPublicKey() {

if (publicKey == null) {

String file =

Thread.currentThread().getContextClassLoader().getResource("publickKey").getFile();

publicKey = getFileTxt(new File(file));

}

return publicKey;

}

/**

* 得到私钥

*

* @return

*/

private static String getPrivateKey() {

if (privateKey == null) {

String file =

Thread.currentThread().getContextClassLoader().getResource("privateKey").getFile();

privateKey = getFileTxt(new File(file));

}

return privateKey;

}

private static String getFileTxt(File file) {

FileInputStream in = null;

ByteArrayOutputStream out = null;

try {

in = new FileInputStream(file);

out = new ByteArrayOutputStream();

IOUtils.copy(in, out);

return out.toString();

} catch (IOException e) {

throw new RuntimeException(e);

} finally {

IOUtils.closeQuietly(in);

IOUtils.closeQuietly(out);

}

}

}

RSACoder

package com.topnet.utils;

import java.security.Key;

import java.security.KeyFactory;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.NoSuchAlgorithmException;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.Signature;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import java.util.Arrays;

import java.util.HashMap;

import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

/**

* @author lpf 在线密钥http://travistidwell.com/jsencrypt/demo/index.html

* pkcs8转码:http://tool.chacuo.net/cryptrsapkcs1pkcs8

*/

public class RSACoder {

public static final String KEY_ALGORITHM = "RSA";

public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

private static final String PUBLIC_KEY = "RSAPublicKey";

private static final String PRIVATE_KEY = "RSAPrivateKey";

public static void main(String[] args) throws Exception {

String encryptAndBase64ByPublicKey =

RSACoder.encryptAndBase64ByPublicKey("这里445545输入密文", publicKey);

System.out.println(encryptAndBase64ByPublicKey);

byte[] de = RSACoder.decryptBase64AndRSAByPrivateKey(encryptAndBase64ByPublicKey);

System.out.println(new String(de));

de = RSACoder.decryptBase64AndRSAByPrivateKey(

"UfuAgO1OeEJ3rzxrkjZcnwxNtDwDp1yuaEgrDzT6p6cw9FRusZwb8MwCTf+rFVAvitXBUPrV/7Kr/cIoB3u7Fw==");

System.out.println(new String(de));

System.out.println(privateKey);

}

/** 公钥,请换掉这里的key,乱写的 **/

public static String publicKey =

"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJK+CtxbfTYxQofcZ48yFb+MabIniIwG"

+ "5lhykq7y20Xe/7lcWQW1qL870LCsuWjlKy/GL+A5G2xta57a4Qy8Z78CAwEAAQ==";

/** 私钥,请换掉这里的key,乱写的 **/

public static String privateKey =

"MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAkr4K3Ft9NjFCh9xn

"

+ "jzIVv4xpsieIjAbmWHKSrvLbRd7/uVxZBbWovzvQsKy5aOUrL8Yv4DkbbG1rntrh

"

+ "DLxnvwIDAQABAkBxuQJlwCmLpCVxcSh421HrfwAy51x1WKuPhEuVdfTlcj1yeqdD

"

+ "I39QEH4ruXuZGNODsJrykRDruu8kW7gR6PmxAiEA1OhTrw3XaRmdDynIJ99UpiMz

"

+ "m7DsbJjmBNqkcR3or/MCIQCwcWhXZefQHbPk4QGVkRUmE3UE2eKvyj7LsCr2lUEo

"

+ "BQIgfn1o+l+m0vI8tX2FROsSR4IybxU14W8VeVzMxceXLrECIBG3ETbVMHUgxlMQ

"

+ "lEwkCO+NvI4EIlJsB+oDggzH54bRAiEAoWP+zcIYPt1F3DSjGJJ0zwdFmuo2gNKE

" + "gn2aM6Yg0Po=";

static {

init();

}

public static void init() {

/**

* 生成key

*/

// Map<String, Key> keyMap;

// try {

// keyMap = RSACoder.initKey();

// publicKey = RSACoder.getPublicKey(keyMap);

// privateKey = RSACoder.getPrivateKey(keyMap);

// } catch (Exception e) {

// // TODO Auto-generated catch block

// logger.error("初始化前端js加密秘钥失败:",e);

// }

// logger.info("公钥:

" + publicKey);

// logger.info("私钥:

" + privateKey);

}

public static byte[] decryptBASE64(String key) {

return Base64.decodeBase64(key.getBytes());

}

public static String encryptBASE64(byte[] bytes) {

return new String(Base64.encodeBase64(bytes));

}

public static byte[] decryptBase64AndRSAByPrivateKey(String data) throws Exception {

return decryptByPrivateKey(RSACoder.decryptBASE64(data), privateKey);

}

/**

* 私钥解密

*

* @param data 要解密的base64编码的数据;

* @param key 私钥的base64编码数据;

* @return

* @throws Exception

*/

public static byte[] decryptAndBase64ByPrivateKey(String data, String key) throws Exception {

return decryptByPrivateKey(RSACoder.decryptBASE64(data), key);

}

/**

* 公钥加密 返回base64字符串

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static String encryptAndBase64ByPublicKey(String data, String key) throws Exception {

return encryptBASE64(encryptByPublicKey(data, key));

}

/**

*

* 用私钥对信息生成数字签名

*

* @param data 加密数据

* @param privateKey 私钥

* @return

* @throws Exception

*/

public static String sign(byte[] data, String privateKey) throws Exception {

// 解密由base64编码的私钥

byte[] keyBytes = decryptBASE64(privateKey);

// 构造PKCS8EncodedKeySpec对象

PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

// KEY_ALGORITHM 指定的加密算法

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

// 取私钥匙对象

PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

// 用私钥对信息生成数字签名

Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

signature.initSign(priKey);

signature.update(data);

return encryptBASE64(signature.sign());

}

/**

* 校验数字签名

*

* @param data 加密数据

* @param publicKey 公钥

* @param sign 数字签名

* @return 校验成功返回true 失败返回false

* @throws Exception

*/

public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {

// 解密由base64编码的公钥

byte[] keyBytes = decryptBASE64(publicKey);

// 构造X509EncodedKeySpec对象

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

// KEY_ALGORITHM 指定的加密算法

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

// 取公钥匙对象

PublicKey pubKey = keyFactory.generatePublic(keySpec);

Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

signature.initVerify(pubKey);

signature.update(data);

// 验证签名是否正常

return signature.verify(decryptBASE64(sign));

}

/**

* 使用私钥解密

*

* @param data

* @param privateKey

* @return

* @throws Exception

*/

public static byte[] decryptByPrivateKey(byte[] data, Key privateKey) throws Exception {

// 对数据解密

Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, privateKey);

byte[] inputArray = data;

int inputLength = inputArray.length;

// 最大加密字节数,超出最大字节数需要分组加密

int MAX_ENCRYPT_BLOCK = 128;

// 标识

int offSet = 0;

byte[] resultBytes = {};

byte[] cache = {};

while (inputLength - offSet > 0) {

if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {

cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);

offSet += MAX_ENCRYPT_BLOCK;

} else {

cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);

offSet = inputLength;

}

resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);

System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);

}

return resultBytes;

}

public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {

// 对密钥解密

byte[] keyBytes = decryptBASE64(key);

// 取得私钥

PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

return decryptByPrivateKey(data, privateKey);

}

/**

* 解密<br>

* 用私钥解密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] decryptByPrivateKey(String data, String key) throws Exception {

return decryptByPrivateKey(decryptBASE64(data), key);

}

/**

* 解密<br>

* 用公钥解密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception {

// 对密钥解密

byte[] keyBytes = decryptBASE64(key);

// 取得公钥

X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key publicKey = keyFactory.generatePublic(x509KeySpec);

// 对数据解密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, publicKey);

return cipher.doFinal(data);

}

/**

* 加密<br>

* 用公钥加密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] encryptByPublicKey(String data, String key) throws Exception {

// 对公钥解密

byte[] keyBytes = decryptBASE64(key);

// 取得公钥

X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key publicKey = keyFactory.generatePublic(x509KeySpec);

// 对数据加密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

byte[] inputArray = data.getBytes();

int inputLength = inputArray.length;

// 最大加密字节数,超出最大字节数需要分组加密

int MAX_ENCRYPT_BLOCK = 117;

// 标识

int offSet = 0;

byte[] resultBytes = {};

byte[] cache = {};

while (inputLength - offSet > 0) {

if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {

cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);

offSet += MAX_ENCRYPT_BLOCK;

} else {

cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);

offSet = inputLength;

}

resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);

System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);

}

return resultBytes;

}

/**

* 加密<br>

* 用私钥加密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] encryptByPrivateKey(byte[] data, String key) throws Exception {

// 对密钥解密

byte[] keyBytes = decryptBASE64(key);

// 取得私钥

PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

// 对数据加密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, privateKey);

return cipher.doFinal(data);

}

/**

* 取得私钥

*

* @param keyMap

* @return

* @throws Exception

*/

public static String getPrivateKey(Map<String, Key> keyMap) throws Exception {

Key key = keyMap.get(PRIVATE_KEY);

return encryptBASE64(key.getEncoded());

}

/**

* 取得公钥

*

* @param keyMap

* @return

* @throws Exception

*/

public static String getPublicKey(Map<String, Key> keyMap) throws Exception {

Key key = keyMap.get(PUBLIC_KEY);

return encryptBASE64(key.getEncoded());

}

/**

* 初始化密钥

*

* @return

* @throws NoSuchAlgorithmException

* @throws Exception

*/

public static Map<String, Key> initKey() throws NoSuchAlgorithmException {

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);

keyPairGen.initialize(1024);

KeyPair keyPair = keyPairGen.generateKeyPair();

Map<String, Key> keyMap = new HashMap<String, Key>(2);

keyMap.put(PUBLIC_KEY, keyPair.getPublic());// 公钥

keyMap.put(PRIVATE_KEY, keyPair.getPrivate());// 私钥

return keyMap;

}

public static Map<String, String> base64Key() throws NoSuchAlgorithmException {

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);

keyPairGen.initialize(1024);

KeyPair keyPair = keyPairGen.generateKeyPair();

Map<String, String> keyMap = new HashMap<String, String>(2);

keyMap.put(PUBLIC_KEY, encryptBASE64(keyPair.getPublic().getEncoded()));// 公钥

keyMap.put(PRIVATE_KEY, encryptBASE64(keyPair.getPrivate().getEncoded()));// 私钥

return keyMap;

}

}

 

 

 

以上是 RSA加密突破117长度限制 的全部内容, 来源链接: utcz.com/z/518269.html

回到顶部