java公钥加密私钥解密_加密方案:rsa使用公钥对字符串加密和私钥解密

package com.duoduozb.constants;

import java.io.ByteArrayOutputStream;

import java.security.Key;

import java.security.KeyFactory;

import java.security.PublicKey;

import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**

* @author Created by deli

* @date 2018/9/21 08:14

* @description rsa加密工具

*/

public class RsaEncryptUtil {

/** */

/**

* 加密算法RSA

*/

public static final String KEY_ALGORITHM = "RSA";// RSA/NONE/NoPadding,RSA/NONE/PKCS1Padding

/**

* String to hold name of the encryption padding.

*/

public static final String PADDING = "RSA/NONE/PKCS1Padding";// RSA/NONE/NoPadding

/**

* String to hold name of the security provider.

*/

public static final String PROVIDER = "BC";

/** */

/**

* 签名算法

*/

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;

/*

* 公钥加密

*/

public static String encryptByPublicKey(String str) throws Exception {

Cipher cipher = Cipher.getInstance(PADDING, PROVIDER);

// 获得公钥

Key publicKey = getPublicKey();

// 用公钥加密

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

// 读数据源

byte[] data = str.getBytes("UTF-8");

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 Base64Util.encode(encryptedData);

}

/*

* 公钥解密

*/

public static String decryptByPublicKey(String str) throws Exception {

Cipher cipher = Cipher.getInstance(PADDING, PROVIDER);

// 获得公钥

Key publicKey = getPublicKey();

// 用公钥解密

cipher.init(Cipher.DECRYPT_MODE, publicKey);

// 读数据源

byte[] encryptedData = Base64Util.decode(str);

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 new String(decryptedData, "UTF-8");

}

/**

* 读取公钥

*

* @return

* @throws Exception

* @comment

*/

private static Key getPublicKey() throws Exception {

String key = GlobalConstants.ras_public_key;

byte[] keyBytes;

keyBytes = Base64Util.decode(key);

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

PublicKey publicKey = keyFactory.generatePublic(keySpec);

return publicKey;

}

}

package com.duoduozb.constants;

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 it.sauronsoftware.base64.Base64;

/**

* @author Created by deli

* @date 2018/9/21 08:17

* @description rsa 工具类

*/

public class Base64Util {

/** */

/**

* 文件读取缓冲区大小

*/

private static final int CACHE_SIZE = 1024;

/** */

/**

*

* BASE64字符串解码为二进制数据

*

*

* @param base64

* @return

* @throws Exception

*/

public static byte[] decode(String base64) throws Exception {

return Base64.decode(base64.getBytes());

}

/** */

/**

*

* 二进制数据编码为BASE64字符串

*

*

* @param bytes

* @return

* @throws Exception

*/

public static String encode(byte[] bytes) throws Exception {

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

}

/** */

/**

*

* 将文件编码为BASE64字符串

*

*

* 大文件慎用,可能会导致内存溢出

*

*

* @param filePath

*            文件绝对路径

* @return

* @throws Exception

*/

public static String encodeFile(String filePath) throws Exception {

byte[] bytes = fileToByte(filePath);

return encode(bytes);

}

/** */

/**

*

* BASE64字符串转回文件

*

*

* @param filePath

*            文件绝对路径

* @param base64

*            编码字符串

* @throws Exception

*/

public static void decodeToFile(String filePath, String base64)

throws Exception {

byte[] bytes = decode(base64);

byteArrayToFile(bytes, filePath);

}

/** */

/**

*

* 文件转换为二进制数组

*

*

* @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;

}

/** */

/**

*

* 二进制数据写文件

*

*

* @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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
公钥加密私钥解密是一种非对称加密算法,常用于保护数据的安全性。在Java中,可以使用Java Cryptography Extension(JCE)提供的API实现公钥加密私钥解密。 下面是一个简单的示例代码: ```java import java.security.*; import javax.crypto.*; import java.util.*; public class RSAExample { public static void main(String[] args) throws Exception { // 生成RSA密钥对 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 获取公钥私钥 PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // 使用公钥加密数据 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedData = cipher.doFinal("Hello World!".getBytes()); // 使用私钥解密数据 cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedData = cipher.doFinal(encryptedData); // 输出结果 System.out.println("原始数据:" + "Hello World!"); System.out.println("加密后数据:" + Base64.getEncoder().encodeToString(encryptedData)); System.out.println("解密后数据:" + new String(decryptedData)); } } ``` 在上述代码中,首先使用`KeyPairGenerator`生成2048位的RSA密钥对,然后获取公钥私钥。接着,使用公钥进行加密私钥进行解密,最后输出原始数据、加密后的数据和解密后的数据。 需要注意的是,在实际应用中,公钥通常是公开的,而私钥应该严格保密,不应该被泄露。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值