RSA 공개 키 암호 화, 비밀 키 서명 도구 클래스
8739 단어 Java
import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; 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.HashMap; import java.util.Map;
public class RSAUtils {
/**
* ,
*/
private static final String RSA_KEY_ALGORITHM = "RSA";
/**
* /
*/
private static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
/**
* RSA ,RSA 1024 64 , 512 65536
*/
private static final int KEY_SIZE = 2048;
/**
*
*/
public static final String CHARSET = "UTF-8";
public static Map createKeys() {
// RSA KeyPairGenerator
KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance(RSA_KEY_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("No such algorithm-->[" + RSA_KEY_ALGORITHM + "]");
}
// KeyPairGenerator ,
kpg.initialize(KEY_SIZE);
//
KeyPair keyPair = kpg.generateKeyPair();
//
Key publicKey = keyPair.getPublic();
String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
//
Key privateKey = keyPair.getPrivate();
String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
Map keyPairMap = new HashMap();
keyPairMap.put("publicKey", publicKeyStr);
keyPairMap.put("privateKey", privateKeyStr);
return keyPairMap;
}
/**
*
*
* @param publicKey ( base64 )
* @throws Exception
*/
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
// X509 Key
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
return key;
}
/**
*
*
* @param privateKey ( base64 )
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String privateKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
// PKCS#8 Key
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
return key;
}
/**
*
*
* @param data
* @param publicKey
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public static String publicEncrypt(String data, String publickeys) throws Exception {
RSAPublicKey publicKey = getPublicKey(publickeys);
try {
// RSA/None/PKCS1Padding ,
Cipher cipher = Cipher.getInstance(RSA_KEY_ALGORITHM);
// // "RSA/None/NoPadding", "BC" ,
// Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET),
publicKey.getModulus().bitLength()));
} catch (Exception e) {
throw new RuntimeException(" [" + data + "] ", e);
}
}
/**
*
*
* @param data
* @param privateKey
* @return
*/
public static String privateDecrypt(String data, String privateKeys) throws Exception {
RSAPrivateKey privateKey = getPrivateKey(privateKeys);
try {
Cipher cipher = Cipher.getInstance(RSA_KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data),
privateKey.getModulus().bitLength()), CHARSET);
} catch (Exception e) {
throw new RuntimeException(" [" + data + "] ", e);
}
}
/**
*
*
* @param data
* @param privateKey
* @return
*/
public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET),
privateKey.getModulus().bitLength()));
} catch (Exception e) {
throw new RuntimeException(" [" + data + "] ", e);
}
}
/**
*
*
* @param data
* @param publicKey
* @return
*/
public static String publicDecrypt(String data, RSAPublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data),
publicKey.getModulus().bitLength()), CHARSET);
} catch (Exception e) {
throw new RuntimeException(" [" + data + "] ", e);
}
}
/**
* RSA
*
* @param data
* @param priKey
* @return
* @throws Exception
*/
public static String sign(byte[] data, byte[] priKey) throws Exception {
//
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
//
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// Signature
signature.initSign(privateKey);
//
signature.update(data);
//
return Base64.encodeBase64String(signature.sign());
}
/**
* RSA
*
* @param data
* @param priKey
* @return
* @throws Exception
*/
public static String sign(String data, String priKey) throws Exception {
//
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKey));
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
//
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// Signature
signature.initSign(privateKey);
//
signature.update(data.getByte());
//
return Base64.encodeBase64String(signature.sign());
}
/**
* RSA
*
* @param data
* @param sign
* @param pubKey
* @return boolean true, false
*/
public static boolean verify(byte[] data, byte[] sign, byte[] pubKey) throws Exception {
//
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
//
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
//
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// Signature
signature.initVerify(publicKey);
//
signature.update(data);
//
return signature.verify(sign);
}
/**
* RSA
*
* @param data
* @param sign
* @param pubKey
* @return boolean true, false
*/
public static boolean verify(String data, String sign, String pubKey) throws Exception {
//
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
//
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubKey));
//
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// Signature
signature.initVerify(publicKey);
//
signature.update(data.getByte());
//
return signature.verify(Base64.decodeBase64(sign));
}
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
int maxBlock = 0;
if (opmode == Cipher.DECRYPT_MODE) {
maxBlock = keySize / 8;
} else {
maxBlock = keySize / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try {
while (datas.length > offSet) {
if (datas.length - offSet > maxBlock) {
buff = cipher.doFinal(datas, offSet, maxBlock);
} else {
buff = cipher.doFinal(datas, offSet, datas.length - offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
} catch (Exception e) {
throw new RuntimeException(" [" + maxBlock + "] ", e);
}
byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out);
return resultDatas;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.