io.github.linmoure.utils.RSAUtils Maven / Gradle / Ivy
package io.github.linmoure.utils;
import lombok.SneakyThrows;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
public class RSAUtils {
public static final String ALGORITHM = "RSA";
private static final int MAX_ENCRYPT_BLOCK = 117;
@SneakyThrows
public static byte[] encryptByPrivateKey(byte[] data, String privateKey) {
byte[] keyBytes = java.util.Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);
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;
}
@SneakyThrows
public static String encryptByPrivateKey(String data, String privateKey) {
return new String(java.util.Base64.getEncoder().encode(encryptByPrivateKey(data.getBytes(), privateKey)));
}
}