RSA 도구 클래스
9013 단어 rsa
import java.io.File;
import java.io.IOException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Random;
import javax.crypto.Cipher;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.io.FileUtils;
/**
*
* RSA 。 , , , 。
*
*/
public final class RSA {
public static final String RSA_CRYPT_ALGORITHM_NAME = "RSA";
public static final String RSA_SIGN_ALGORITHM_NAME = "MD5withRSA";
private static final int RSA_KEY_LENGTH = 1024;
/**
*
*
*
* @return KeyPair
*/
private static KeyPair generateKeyPair() throws Exception {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(RSA_CRYPT_ALGORITHM_NAME);
final int KEY_SIZE = RSA_KEY_LENGTH;// ,
SecureRandom secrand = new SecureRandom();
// , key, 。。。
secrand.setSeed(RandomUtils.generateString(RSA_KEY_LENGTH).getBytes()); //
keyPairGen.initialize(KEY_SIZE, secrand);
KeyPair keyPair = keyPairGen.genKeyPair();
return keyPair;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* RSA ,
*
* @param path
*/
public static void keyRSA(String path, boolean isBase64Encode)
throws Exception {
KeyPair kp = generateKeyPair();
//
PublicKey pubkey = kp.getPublic();
//
PrivateKey prikey = kp.getPrivate();
byte[] pubKeyBytes = pubkey.getEncoded();
byte[] priKeyBytes = prikey.getEncoded();
if (isBase64Encode) {
pubKeyBytes = Base64.encode(pubkey.getEncoded()).getBytes();
priKeyBytes = Base64.encode(prikey.getEncoded()).getBytes();
}
//
if (StringUtils.isBlank(path)) {
path = "c:/";
} else {
if (!path.endsWith("/")) {
path = path + "/";
}
}
bytes2File(pubKeyBytes, path + "rsa.publicKey");
bytes2File(priKeyBytes, path + "rsa.privateKey");
}
private static void bytes2File(byte[] keyBytes,
String filePath) throws IOException {
File file = new File(filePath);
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
FileUtils.writeByteArrayToFile(file, keyBytes);
}
public static PublicKey generateRSAPublicKey(String path,
boolean base64Encoded) throws Exception {
return generateRSAPublicKey(getBytes(path), base64Encoded);
}
/**
*
*
* @param pubKeyString
* @return
* @throws Exception
*/
public static PublicKey generateRSAPublicKey(byte[] pubKeyByte,
boolean base64Encoded) throws Exception {
byte[] encodedKey = pubKeyByte;
// base64
if (base64Encoded) {
encodedKey = Base64.decode(new String(pubKeyByte));
}
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(encodedKey);
KeyFactory keyFactory = KeyFactory
.getInstance(RSA_CRYPT_ALGORITHM_NAME);
return keyFactory.generatePublic(bobPubKeySpec);
}
public static PrivateKey generateRSAPrivateKey(String path,
boolean base64Encoded) throws Exception {
return generateRSAPrivateKey(getBytes(path), base64Encoded);
}
/**
*
*
* @param priKeyByte
* @return
* @throws Exception
*/
public static PrivateKey generateRSAPrivateKey(byte[] priKeyByte,
boolean base64Encoded) throws Exception {
byte[] encodedKey = priKeyByte;
// base64
if (base64Encoded) {
encodedKey = Base64.decode(new String(priKeyByte));
}
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(encodedKey);
KeyFactory keyFactory = KeyFactory
.getInstance(RSA_CRYPT_ALGORITHM_NAME);
return keyFactory.generatePrivate(priPKCS8);
}
private static byte[] getBytes(String path) throws IOException {
File file = new File(path);
return FileUtils.readFileToByteArray(file);
}
/**
*
*
* @param key
*
* @param data
*
* @return
*/
public static byte[] encrypt(Key key, byte[] data) throws Exception {
if (key != null) {
try {
Cipher cipher = Cipher.getInstance(RSA_CRYPT_ALGORITHM_NAME);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
*
*
* @param key
*
* @param raw
* @return
*/
public static byte[] decrypt(Key key, byte[] raw) throws Exception {
if (key != null) {
try {
Cipher cipher = Cipher.getInstance(RSA_CRYPT_ALGORITHM_NAME);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(raw);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
*
*
* @param privateKey
* @param data
* @return
*/
public static byte[] sign(PrivateKey privateKey, byte[] data)
throws Exception {
try {
//
Signature signet = Signature.getInstance(RSA_SIGN_ALGORITHM_NAME);
signet.initSign(privateKey);
signet.update(data);
byte[] signed = signet.sign(); //
return signed;
} catch (Exception e) {
throw new Exception(e);
}
}
/**
*
*
* @param publicKey
* @param signed
* @param orig
* @return
*/
public static boolean verify(PublicKey publicKey, byte[] signed, byte[] orig)
throws Exception {
try {
Signature signetcheck = Signature
.getInstance(RSA_SIGN_ALGORITHM_NAME);
signetcheck.initVerify(publicKey);
signetcheck.update(orig);
if (signetcheck.verify(signed)) {
return true;
} else {
return false;
}
} catch (Exception e) {
throw new Exception(e);
}
}
public static void main(String[] args) throws Exception {
RSA.keyRSA("D:/12", true);
PublicKey publicKey = RSA.generateRSAPublicKey("D:/12/rsa.publicKey", true);
PrivateKey privateKey = RSA.generateRSAPrivateKey("D:/12/rsa.privateKey", true);
String str = "rsa test : KKC --> kkc ~ 88";
byte[] strByte = str.getBytes();
System.out.println(" :" + str);
byte[] encrypt = RSA.encrypt(privateKey, strByte);
byte[] decrypt = RSA.decrypt(publicKey, encrypt);
System.out.println(" :" + new String(decrypt));
System.out.println(" 、 :" + new String(decrypt).equals(str));
byte[] sign = RSA.sign(privateKey, strByte);
System.out.println(" :" + RSA.verify(publicKey, sign, strByte));
System.out.println(" :" + RSA.verify(publicKey, sign, RandomUtils.generateString(20).getBytes()));
}
}
class RandomUtils {
public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* ( 、 )
*
* @param length
* @return
*/
public static String generateString(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(allChar.charAt(random.nextInt(allChar.length())));
}
return sb.toString();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
pythonrsa-oaep 암호화 예시 코드코드: 출력: -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCk5RDTc88/13NClCz2u8JbERQZ 5+5oqdic9LkqfpHXguxB...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.