RSA加密

package com.uns.mpos.ins.util;


import java.security.InvalidKeyException;
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.Signature;
import java.security.SignatureException;
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 org.apache.commons.codec.binary.Base64;


import java.util.HashMap;
import java.util.Map;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;


public abstract class RSACoder {

/**加密算法RSA**/
public static final String KEY_ALGORITHM = "RSA";
/**签名算法MD5**/
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**公钥**/
private static final String PUBLIC_KEY = "RSAPublicKey";
/**私钥**/
private static final String PRIVATE_KEY = "RSAPrivateKey";
/**十六进制标识**/
private static final String FLAG="0123456789ABCDEF";


/**
* 用私钥对信息生成数字签名

* @param data 加密数据
* @param privateKey 私钥
* @return
* @throws NoSuchAlgorithmException 
* @throws InvalidKeySpecException 
* @throws InvalidKeyException 
* @throws SignatureException 
* @throws Exception
*/
public static String sign(byte[] data, String privateKey) {
try {
// 解密由base64编码的私钥
byte[] keyBytes = decryptBASE64(privateKey);


// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);


// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);


// 取私钥匙对象
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);


// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data);


return encryptBASE64(signature.sign());
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
}
return null;
}


/**
* 校验数字签名

* @param data 加密数据
* @param publicKey 公钥
* @param sign  数字签名
* @return 校验成功返回true 失败返回false
* @throws Exception

*/
public static boolean verify(byte[] data, String publicKey, String sign){
try {
// 解密由base64编码的公钥
byte[] keyBytes = decryptBASE64(publicKey);


// 构造X509EncodedKeySpec对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);


// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);


// 取公钥匙对象
PublicKey pubKey = keyFactory.generatePublic(keySpec);


Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);
// 验证签名是否正常
return signature.verify(decryptBASE64(sign));
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
}
return false;
}


/**
* 解密<br>
* 用私钥解密

* @param data 解密的数据
* @param key 
* @return
* @throws NoSuchAlgorithmException 
* @throws InvalidKeySpecException 
* @throws NoSuchPaddingException 
* @throws InvalidKeyException 
* @throws BadPaddingException 
* @throws IllegalBlockSizeException 
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, String key) {
try {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key);


// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);


// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);


return cipher.doFinal(data);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}


/**
* 解密<br>
* 用公钥解密

* @param data
* @param key
* @return
* @throws NoSuchAlgorithmException 
* @throws InvalidKeySpecException 
* @throws NoSuchPaddingException 
* @throws InvalidKeyException 
* @throws BadPaddingException 
* @throws IllegalBlockSizeException 
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] data, String key){
try {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key);


// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);


// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);


return cipher.doFinal(data);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}


/**
* 加密<br>
* 用公钥加密

* @param data 加密的BASE64数组
* @param key 公钥
* @return
* @throws NoSuchAlgorithmException 
* @throws InvalidKeySpecException 
* @throws NoSuchPaddingException 
* @throws InvalidKeyException 
* @throws BadPaddingException 
* @throws IllegalBlockSizeException 
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, String key) {
try {
// 对公钥解密
byte[] keyBytes = decryptBASE64(key);


// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);


// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);


return cipher.doFinal(data);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}


/**
* 加密<br>
* 用私钥加密

* @param data
* @param key
* @return
* @throws NoSuchAlgorithmException 
* @throws InvalidKeySpecException 
* @throws NoSuchPaddingException 
* @throws InvalidKeyException 
* @throws BadPaddingException 
* @throws IllegalBlockSizeException 
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String key) {
try {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key);


// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);


// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);


return cipher.doFinal(data);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}


/**
* 取得私钥

* @param keyMap
* @return
* @throws Exception
*/
public static String getPrivateKey(Map<String, Object> keyMap){
Key key = (Key) keyMap.get(PRIVATE_KEY);
return encryptBASE64(key.getEncoded());
}


/**
* 取得公钥

* @param keyMap
* @return
* @throws Exception
*/
public static String getPublicKey(Map<String, Object> keyMap){
Key key = (Key) keyMap.get(PUBLIC_KEY);
return encryptBASE64(key.getEncoded());
}


/**
* 初始化密钥

* @return
* @throws NoSuchAlgorithmException 
* @throws Exception
*/
public static Map<String, Object> initKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(2048);


KeyPair keyPair = keyPairGen.generateKeyPair();


// 公钥
RSAPublicKey publicKey =  (RSAPublicKey) keyPair.getPublic();


// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();


Map<String, Object> keyMap = new HashMap<String, Object>(2);


keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}

/**
* 对字符串用Base64加密
* @param key
* @return
*/
    public static byte[] decryptBASE64(String key) {
        return Base64.decodeBase64(key);
    }
    
    /**
* 对字符串用Base64加密
* @param key
* @return
*/
    public static String encryptBASE64(byte[] key) {
        return Base64.encodeBase64String(key);
    }
    
    /**
     * 字节流转换成字符串
     * @param bytes 字节流
     * @return
     */
    public static String Byte2String(byte[] bytes){
    StringBuffer result = new StringBuffer();
    StringBuffer temp = new StringBuffer();
    for (int i = 0; i < bytes.length; i++) {
    //初始化中间量
    temp.delete(0, temp.length());
    //取字节高四位的转为十六进制
    temp.append(String.valueOf(FLAG.charAt(( bytes[i]&0xF0 ) >> 4)));
    //去字节第四位的转为十六进制
    temp.append(String.valueOf(FLAG.charAt(bytes[i]&0x0F)));
    result.append(temp);
}
return result.toString();
    }


    /**
     * 字符串转字节流
     * @param str 字符串
     * @return
     */
    public static byte[] String2Byte(String str){
    byte[] result = new byte[str.length()>>1];
    int high = 0;
    int low =0;
    for (int i = 0; i < result.length; i++) {
    high=(byte)((FLAG.indexOf(str.charAt(i*2)))<<4);
    low=(byte)(FLAG.indexOf(str.charAt(i*2+1)));
    result[i]=(byte) (high|low);
}
return result;
    }

}







package com.uns.mpos.ins.util;


import static org.junit.Assert.*;


import org.junit.Before;
import org.junit.Test;




import java.util.Map;




public class RSACoderTest {

private String publicKey;

private String privateKey;

@Before
public void setUp() throws Exception {
Map<String, Object> keyMap = RSACoder.initKey();


publicKey = RSACoder.getPublicKey(keyMap);
privateKey = RSACoder.getPrivateKey(keyMap);
System.err.println("公钥: \n\r" + publicKey);
System.err.println("私钥: \n\r" + privateKey);
}


@Test
public void test(){
System.err.println("公钥加密——私钥解密");
String inputStr = "美丽中国";
byte[] data = inputStr.getBytes();
byte[] encodedData = RSACoder.encryptByPublicKey(data, publicKey);

/**
* 中间可以将字节数组转换成字符串方便传输数据,再将字符串转换成字节数组
*/
//    String encodedString=RSACoder.Byte2String(encodedData);
//    byte[] temp=RSACoder.String2Byte(encodedString);

byte[] decodedData = RSACoder.decryptByPrivateKey(encodedData,privateKey);
String outputStr = new String(decodedData);
System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);
assertEquals(inputStr, outputStr);


}


@Test
public void testSign(){
System.err.println("私钥加密——公钥解密");
String inputStr = "美丽中国";
byte[] data = inputStr.getBytes();


byte[] encodedData = RSACoder.encryptByPrivateKey(data, privateKey);


byte[] decodedData = RSACoder.decryptByPublicKey(encodedData, publicKey);


String outputStr = new String(decodedData);
System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);
assertEquals(inputStr, outputStr);


System.err.println("私钥签名——公钥验证签名");
// 产生签名
String sign = RSACoder.sign(encodedData, privateKey);
System.err.println("签名:\r" + sign);


// 验证签名
boolean status = RSACoder.verify(encodedData, publicKey, sign);
System.err.println("状态:\r" + status);
assertTrue(status);


}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值