RSA加密解密demo

Shaka 8月前 ⋅ 379 阅读

 

private static final String ALGORITHM = "RSA";
private static final String PUBLICK_EY = "PUBLICK_EY";
private static final String PRIVATE_KEY = "PRIVATE_KEY";
/**
* 加密算法
*/
private static final String CIPHER_DE = "RSA";
/**
* 解密算法
*/
private static final String CIPHER_EN = "RSA";
/**
* 密钥长度
*/
private static final Integer KEY_LENGTH = 2048;

/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 1024;

/**
* 生成秘钥对,公钥和私钥
*
* @return
* @throws NoSuchAlgorithmException
*/
public static Map<String, Object> genKeyPair() throws NoSuchAlgorithmException {
Map<String, Object> keyMap = new HashMap<String, Object>();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_LENGTH); // 秘钥字节数
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
keyMap.put(PUBLICK_EY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}

/**
* 公钥加密
*
* @param data
* @param publicKey
* @return
* @throws InvalidKeySpecException
*/
public static void encryptByPublicKey(byte[] data, String publicKey, FileOutputStream out) throws Exception {
// 得到公钥
byte[] keyBytes = Base64.decode(publicKey.getBytes());
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
Key key = keyFactory.generatePublic(x509EncodedKeySpec);
// 加密数据,分段加密
Cipher cipher = Cipher.getInstance(CIPHER_EN);
cipher.init(Cipher.ENCRYPT_MODE, key);
int inputLength = data.length;
int offset = 0;
byte[] cache;
int i = 0;
while (inputLength - offset > 0) {
if (inputLength - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offset, inputLength - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
out.close();
}

/**
* 私钥解密
*
* @param data
* @param privateKey
* @return
* @throws Exception
*/
public static void decryptByPrivateKey(byte[] data, String privateKey,FileOutputStream out) throws Exception {
// 得到私钥
byte[] keyBytes = Base64.decode(privateKey.getBytes());
PKCS8EncodedKeySpec pKCS8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
Key key = keyFactory.generatePrivate(pKCS8EncodedKeySpec);
// 解密数据,分段解密
Cipher cipher = Cipher.getInstance(CIPHER_DE);
cipher.init(Cipher.DECRYPT_MODE, key);
int inputLength = data.length;
int offset = 0;
byte[] cache;
int i = 0;
byte[] tmp;
while (inputLength - offset > 0) {
if (inputLength - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(data, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offset, inputLength - offset);
}
// out.write(cache, 0, cache.length);
out.write(cache);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
out.close();
}

/**
* 获取公钥
*
* @param keyMap
* @return
*/
public static String getPublicKey(Map<String, Object> keyMap) {
Key key = (Key) keyMap.get(PUBLICK_EY);
System.out.println(key);
String str = new String(Base64.encode(key.getEncoded()));
return str;
}

/**
* 获取私钥
*
* @param keyMap
* @return
*/
public static String getPrivateKey(Map<String, Object> keyMap) {
Key key = (Key) keyMap.get(PRIVATE_KEY);
String str = new String(Base64.encode(key.getEncoded()));
return str;
}

public static void main(String[] args) throws Exception {
Map<String, Object> keyMap = StudentServiceTests.genKeyPair();
String publicKey = StudentServiceTests.getPublicKey(keyMap);
System.out.println("公钥:" + publicKey);
String privateKey = StudentServiceTests.getPrivateKey(keyMap);
System.out.println("私钥:" + privateKey);
File inFile =new File("C:\\Users\\administrators\\Desktop\\测试.txt");
File outFile =new File("C:\\Users\\administrators\\Desktop\\测试.txt.abc");
FileInputStream fis = new FileInputStream(inFile);
FileOutputStream out = new FileOutputStream(outFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] b = new byte[1024];
int len = -1;
while((len = fis.read(b)) != -1) {
bos.write(b, 0, len);
}
byte[] fileByte = bos.toByteArray();

// 公钥加密
StudentServiceTests.encryptByPublicKey(fileByte, publicKey,out);

File inFile2 =new File("C:\\Users\\administrators\\Desktop\\测试.txt.abc");
File outFile2 =new File("C:\\Users\\administrators\\Desktop\\测试1.txt");
FileInputStream fis2 = new FileInputStream(inFile2);
FileOutputStream out2 = new FileOutputStream(outFile2);
ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
byte[] b2 = new byte[28];
int len2 = -1;
while((len2 = fis2.read(b2)) != -1) {
bos2.write(b2, 0, len2);
}
byte[] fileByte2 = bos2.toByteArray();
// 私钥解密
StudentServiceTests.decryptByPrivateKey(fileByte2, privateKey,out2);
}


注意:本文归作者所有,未经作者允许,不得转载

全部评论: 0

    我有话说: