RSA 공개 키 암호 화, 비밀 키 서명 도구 클래스

8739 단어 Java
package *;
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;
}
}

좋은 웹페이지 즐겨찾기