最近项目涉及到传输加密,对于现在比较安全和流行的加密技术做一个记录和分享。
RSA对称加密
所谓对称加密,我的理解可以用这副图表达(灵魂画手)
client和service分别拿着一把这样的带钥匙的锁(也可以称为带锁的钥匙)
我用我的锁可以加密这个数据,可是我的钥匙打不开我锁上的东西,只有你的钥匙能打开。同理,用你的锁加密的东西,你自己打不开,只有我能打开。
这个带钥匙的锁就是 公钥&私钥
首先生成公钥需要 openssl生成工具 来生成。
生成秘钥步骤:
1.双击打开bin文件夹下的
openssl.exe
,打开之后是一个命令行窗口;
2.通过如下命令生成私钥:
genrsa -out rsa_private_key.pem 1024
执行完命令后就可在bin文件夹下看到rsa_private_key.pem文件了。
3.通过如下命令生成公钥:
rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout
4.这样密钥对的私钥是无法在代码中直接使用的,要想使用它需要借助RSAPrivateKeyStructure这个类,java是不自带的。所以为了方便使用,我们需要对私钥进行PKCS#8编码
pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt
在bin文件夹生成了pkcs8_rsa_private_key.pem文件
注意:生成的秘钥使用的时候不包含第一行和最后一行
RSA工具代码:
public class RsaUtils {
private static String RSA = "RSA";
* 随机生成RSA密钥对(默认密钥长度为1024)
* @return
public static KeyPair generateRSAKeyPair()
return generateRSAKeyPair(1024);
* 随机生成RSA密钥对
* @param keyLength
* 密钥长度,范围:512~2048<br>
* 一般1024
* @return
public static KeyPair generateRSAKeyPair(int keyLength)
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e)
e.printStackTrace();
return null;
* 用公钥加密 <br>
* 每次加密的字节数,不能超过密钥的长度值减去11
* @param data
* 需加密数据的byte数据
* @param publicKey
* 公钥
* @return 加密后的byte型数据
public static byte[] encryptData(byte[] data, PublicKey publicKey)
Cipher cipher = Cipher.getInstance(RSA);
// 编码前设定编码方式及密钥
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 传入编码数据并返回编码结果
return cipher.doFinal(data);
} catch (Exception e)
e.printStackTrace();
return null;
* 用私钥解密
* @param encryptedData
* 经过encryptedData()加密返回的byte数据
* @param privateKey
* 私钥
* @return
public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
} catch (Exception e)
return null;
* 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
* 通过私钥byte[]将公钥还原,适用于RSA算法
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
* 使用N、e值还原公钥
* @param modulus
* @param publicExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
public static PublicKey getPublicKey(String modulus, String publicExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
* 使用N、d值还原私钥
* @param modulus
* @param privateExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
public static PrivateKey getPrivateKey(String modulus, String privateExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
* 从字符串中加载公钥
* @param publicKeyStr
* 公钥数据字符串
* @throws Exception
* 加载公钥时产生的异常
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception
byte[] buffer = Base64Utils.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e)
throw new Exception("无此算法");
} catch (InvalidKeySpecException e)
throw new Exception("公钥非法");
} catch (NullPointerException e)
throw new Exception("公钥数据为空");
* 从字符串中加载私钥<br>
* 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
* @param privateKeyStr
* @return
* @throws Exception
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception
byte[] buffer = Base64Utils.decode(privateKeyStr);
// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e)
throw new Exception("无此算法");
} catch (InvalidKeySpecException e)
throw new Exception("私钥非法");
} catch (NullPointerException e)
throw new Exception("私钥数据为空");
* 从文件中输入流中加载公钥
* @param in
* 公钥输入流
* @throws Exception
* 加载公钥时产生的异常
public static PublicKey loadPublicKey(InputStream in) throws Exception
return loadPublicKey(readKey(in));
} catch (IOException e)
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e)
throw new Exception("公钥输入流为空");
* 从文件中加载私钥
* @param in
* 私钥文件名
* @return 是否成功
* @throws Exception
public static PrivateKey loadPrivateKey(InputStream in) throws Exception
return loadPrivateKey(readKey(in));
} catch (IOException e)
throw new Exception("私钥数据读取错误");
} catch (NullPointerException e)
throw new Exception("私钥输入流为空");
* 读取密钥信息
* @param in
* @return
* @throws IOException
private static String readKey(InputStream in) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null)
if (readLine.charAt(0) == '-')
continue;
} else
sb.append(readLine);
sb.append('\r');
return sb.toString();
* 打印公钥信息
* @param publicKey
public static void printPublicKeyInfo(PublicKey publicKey)
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
System.out.println("----------RSAPublicKey----------");
System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
public static void printPrivateKeyInfo(PrivateKey privateKey)
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
System.out.println("----------RSAPrivateKey ----------");
System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());
在代码中使用:
case R.id.btn_encode:
//rsa加密
String s = et_str.getText().toString();
if (!TextUtils.isEmpty(s)) {
try {
PublicKey publicKey = RsaUtils.loadPublicKey(Global.PUBLIC_KEY);
byte[] bytes = RsaUtils.encryptData(s.getBytes(), publicKey);
String encode = Base64Utils.encode(bytes);
tv_str.setText(encode);
} catch (Exception e) {
e.printStackTrace();
break;
case R.id.btn_decode:
//rsa解密
String s1 = tv_str.getText().toString().trim();
if (!TextUtils.isEmpty(s1)) {
try {
PrivateKey privateKey = RsaUtils.loadPrivateKey(Global.PRIVATE_KEY);
byte[] bytes = RsaUtils.decryptData(Base64Utils.decode(s1), privateKey);
if (null != bytes)
tv_str.setText(new String(bytes));
} catch (Exception e) {
e.printStackTrace();
break;
public class AesUtil {
private final static String HEX = "0123456789ABCDEF";
private static final String CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";//AES是加密方式 CBC是工作模式 PKCS5Padding是填充模式
private static final String AES = "AES";//AES 加密
private static final String SHA1PRNG="SHA1PRNG";//// SHA1PRNG 强随机种子算法, 要区别4.2以上版本的调用方法
* 生成随机数,可以当做动态的密钥 加密和解密的密钥必须一致,不然将不能解密
public static String generateKey() {
try {
SecureRandom localSecureRandom = SecureRandom.getInstance(SHA1PRNG);
byte[] bytes_key = new byte[20];
localSecureRandom.nextBytes(bytes_key);
String str_key = toHex(bytes_key);
return str_key;
} catch (Exception e) {
e.printStackTrace();
return null;
// 对密钥进行处理
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance(AES);
//for android
SecureRandom sr = null;
// 在4.2以上版本中,SecureRandom获取方式发生了改变
if (android.os.Build.VERSION.SDK_INT >= 17) {
sr = SecureRandom.getInstance(SHA1PRNG, "Crypto");
} else {
sr = SecureRandom.getInstance(SHA1PRNG);
// for Java
// secureRandom = SecureRandom.getInstance(SHA1PRNG);
sr.setSeed(seed);
kgen.init(128, sr); //256 bits or 128 bits,192bits
//AES中128位密钥版本有10个加密循环,192比特密钥版本有12个加密循环,256比特密钥版本则有14个加密循环。
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
public static String encrypt(String key, String cleartext) {
if (TextUtils.isEmpty(cleartext)) {
return cleartext;
try {
byte[] result = encrypt(key, cleartext.getBytes());
return Base64Utils.encode(result);
} catch (Exception e) {
e.printStackTrace();
return null;
private static byte[] encrypt(String key, byte[] clear) throws Exception {
byte[] raw = getRawKey(key.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
public static String decrypt(String key, String encrypted) {
if (TextUtils.isEmpty(encrypted)) {
return encrypted;
try {
byte[] enc = Base64Utils.decode(encrypted);
byte[] result = decrypt(key, enc);
return new String(result);
} catch (Exception e) {
e.printStackTrace();
return null;
private static byte[] decrypt(String key, byte[] encrypted) throws Exception {
byte[] raw = getRawKey(key.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}//二进制转字符
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
return result.toString();
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
AES加密代码中使用:
String secretKey = AesUtil.generateKey();
case R.id.btn_aesencode:
//aes加密
String str1 = et_str.getText().toString();
if(!TextUtils.isEmpty(str1)){
String encrypt = AesUtil.encrypt(secretKey, str1);
tv_str.setText(encrypt);
break;
case R.id.btn_aesdecode:
//aes解密
String str2 = tv_str.getText().toString();
if(!TextUtils.isEmpty(str2)){
String decrypt = AesUtil.decrypt(secretKey, str2);
tv_str.setText(decrypt);
break;
了解了两种加密方法,将他们配合起来用就容易多了,同时安全性更高。
talk is cheap ,show you the code.
case R.id.btn_allencode:
//rsa+aes加密
String ar1 = et_str.getText().toString();
if(!TextUtils.isEmpty(ar1)){
String encrypt = AesUtil.encrypt(secretKey, ar1);
if(!TextUtils.isEmpty(encrypt)){
try {
PublicKey publicKey = RsaUtils.loadPublicKey(Global.PUBLIC_KEY);
byte[] bytes = RsaUtils.encryptData(encrypt.getBytes(), publicKey);
String encode = Base64Utils.encode(bytes);
tv_str.setText(encode);
} catch (Exception e) {
e.printStackTrace();
break;
case R.id.btn_alldecode:
//rsa+aes解密
String ar2 = tv_str.getText().toString().trim();
if (!TextUtils.isEmpty(ar2)) {
try {
PrivateKey privateKey = RsaUtils.loadPrivateKey(Global.PRIVATE_KEY);
byte[] bytes = RsaUtils.decryptData(Base64Utils.decode(ar2), privateKey);
if (null != bytes)
tv_str.setText(AesUtil.decrypt(secretKey,new String(bytes)));
} catch (Exception e) {
e.printStackTrace();
break;
private static char[] base64EncodeChars = new char[]
{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '+', '/' };
private static byte[] base64DecodeChars = new byte[]
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
-1, -1, -1 };
* @param data
* @return
public static String encode(byte[] data)
StringBuffer sb = new StringBuffer();
int len = data.length;
int i = 0;
int b1, b2, b3;
while (i < len)
b1 = data[i++] & 0xff;
if (i == len)
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append("==");
break;
b2 = data[i++] & 0xff;
if (i == len)
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append("=");
break;
b3 = data[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
return sb.toString();
* @param str
* @return
public static byte[] decode(String str)
return decodePrivate(str);
} catch (UnsupportedEncodingException e)
e.printStackTrace();
return new byte[]
private static byte[] decodePrivate(String str) throws UnsupportedEncodingException
StringBuffer sb = new StringBuffer();
byte[] data = null;
data = str.getBytes("US-ASCII");
int len = data.length;
int i = 0;
int b1, b2, b3, b4;
while (i < len)
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
if (b1 == -1)
break;
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -1);
if (b2 == -1)
break;
sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
b3 = data[i++];
if (b3 == 61)
return sb.toString().getBytes("iso8859-1");
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
if (b3 == -1)
break;
sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
b4 = data[i++];
if (b4 == 61)
return sb.toString().getBytes("iso8859-1");
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
if (b4 == -1)
break;
sb.append((char) (((b3 & 0x03) << 6) | b4));