import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
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.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.crypto.Cipher;
import javax.naming.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
* 通过加密本地身份证号和已经加密的远程身份证号比较,查找是否有同一个人
* @author Administrator
*
*/
public class RSATest {
//main
public static void main(String[] args) {
try {
//模拟远程已经加密的身分证号
RSATest encrypt = new RSATest();
String id="130528";//身份证前6位
String encryptText = "19851026xxx2";//身份证后12位 需要加密
Set ids=RSATest.getIds();
//迭代出本地身份证号
Iterator<String> iter=ids.iterator();
while(iter.hasNext())
{
//分解set中和身份证号
String currentId=iter.next();
String header=currentId.substring(0,6);//前6
String feer=currentId.substring(6);//后12
// Generate keys
KeyPair keyPair = encrypt.generateKey();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();//公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); //私钥
// System.out.println("公钥:"+publicKey);
// System.out.println("私钥:"+privateKey);
byte[] e1 = encrypt.encrypt(publicKey, encryptText.getBytes());//加密(远程身份证号)
byte[] e2 = encrypt.encrypt(publicKey, feer.getBytes());//加密(本地身份证号)
boolean isTrue=RSATest.isTrue(e1, e2);//比较密文
if(isTrue)
{
System.out.println("it is :"+header+feer);
}
else
{
System.out.println("no:"+header+feer);
}
// byte[] de = encrypt.decrypt(privateKey, e2);//解密
// System.out.println("加过密:"+toEnString(e2));
// System.out.println("解过密:"+toHexString(de));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成密钥
* @return
* @throws NoSuchAlgorithmException
*/
public KeyPair generateKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
return keyPair;
}
/**
* 保存密钥(没有用到)
* @param keyPair
* @param publicKeyFile
* @param privateKeyFile
* @throws Exception
*/
public void saveKey(KeyPair keyPair, String publicKeyFile,String privateKeyFile) throws Exception {
PublicKey pubkey = keyPair.getPublic();
PrivateKey prikey = keyPair.getPrivate();
// save public key
PropertiesConfiguration publicConfig = new PropertiesConfiguration(publicKeyFile);
publicConfig.setProperty("PULIICKEY", toHexString(pubkey.getEncoded()));
publicConfig.save(privateKeyFile);
// save private key
PropertiesConfiguration privateConfig = new PropertiesConfiguration(privateKeyFile);
privateConfig.setProperty("PRIVATEKEY", toHexString(prikey.getEncoded()));
privateConfig.save(privateKeyFile);
}
/**
* 载入密钥(没有用到)
* @param filename
* @param type:
* 1-public 0-private
* @return
* @throws ConfigurationException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public Key loadKey(String filename, int type)throws Exception
{
PropertiesConfiguration config = new PropertiesConfiguration(filename);
KeyFactory keyFactory = KeyFactory.getInstance("RSA",
new BouncyCastleProvider());
if (type == 0) {
// privateKey
String privateKeyValue = config.getString("PULIICKEY");
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
toBytes(privateKeyValue));
PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);
return privateKey;
} else {
// publicKey
String privateKeyValue = config.getString("PRIVATEKEY");
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(
toBytes(privateKeyValue));
PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);
return publicKey;
}
}
/**
* 加密
* @param publicKey
* @param data
* @return
*/
protected byte[] encrypt(RSAPublicKey publicKey, byte[] data) {
if (publicKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA",new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data); //真正加密地方
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* 解密
* @param privateKey
* @param raw
* @return
*/
protected byte[] decrypt(RSAPrivateKey privateKey, byte[] raw) {
if (privateKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA",new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(raw);//真正解密的地方
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static String toEnString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]);
sb.append(HEXCHAR[b[i] & 0x0f]);
}
return sb.toString();
}
public static String toHexString(byte[] b) {
String sb=new String(b);
return sb.toString();
}
public static final byte[] toBytes(String s) {
byte[] bytes;
bytes = new byte[s.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),
16);
}
return bytes;
}
private static char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//模拟的本地身份证号
public static Set getIds()
{
Set ids=new HashSet();
ids.add("13052819851026xxx9");
ids.add("13052819851026xxx2");
ids.add("13052819851026xxx8");
ids.add("13052819851026xxx0");
return ids;
}
//比较远程和本地身份证号
public static boolean isTrue(byte[] e1,byte[] e2)
{
String e1Str=toEnString(e1);
String e2Str=toEnString(e2);
return e1Str.equals(e2Str);
}
}