mobi.cangol.mobile.security.RSAUtils Maven / Gradle / Ivy
/**
* Copyright (c) 2013 Cangol
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mobi.cangol.mobile.security;
/**
* RSA加密解密类
*
* @author Cangol
*/
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
public class RSAUtils {
private static final String CHARSET = "utf-8";
private RSAUtils() {
}
/**
* 生成公钥和私钥
*
* @throws NoSuchAlgorithmException
*/
public static Map getKeys() throws NoSuchAlgorithmException {
final Map map = new HashMap<>();
final KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024);
final KeyPair keyPair = keyPairGen.generateKeyPair();
final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
map.put("public", publicKey);
map.put("private", privateKey);
return map;
}
/**
* 使用模和指数生成RSA公钥
* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
* /None/NoPadding】
*
* @param modulus 模
* @param exponent 指数
* @return
*/
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
try {
final BigInteger b1 = new BigInteger(modulus);
final BigInteger b2 = new BigInteger(exponent);
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
return null;
}
}
/**
* 使用模和指数生成RSA私钥
* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
* /None/NoPadding】
*
* @param modulus 模
* @param exponent 指数
* @return
*/
public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
try {
final BigInteger b1 = new BigInteger(modulus);
final BigInteger b2 = new BigInteger(exponent);
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
return null;
}
}
/**
* 公钥加密
*
* @param data
* @param publicKey
* @return
* @throws Exception
*/
public static String encryptByPublicKey(String data, RSAPublicKey publicKey)
throws Exception {
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 模长
final int keyLen = publicKey.getModulus().bitLength() / 8;
// 加密数据长度 <= 模长-11
final String[] datas = splitString(data, keyLen - 11);
final StringBuilder mi = new StringBuilder();
//如果明文长度大于模长-11则要分组加密
for (final String s : datas) {
mi.append(bcd2Str(cipher.doFinal(s.getBytes(CHARSET))));
}
return mi.toString();
}
/**
* 私钥解密
*
* @param data
* @param privateKey
* @return
* @throws Exception
*/
public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)
throws Exception {
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//模长
final int keyLen = privateKey.getModulus().bitLength() / 8;
final byte[] bytes = data.getBytes(CHARSET);
final byte[] bcd = asciiToBcd(bytes, bytes.length);
//如果密文长度大于模长则要分组解密
final StringBuilder ming = new StringBuilder();
final byte[][] arrays = splitArray(bcd, keyLen);
for (final byte[] arr : arrays) {
ming.append(new String(cipher.doFinal(arr), CHARSET));
}
return ming.toString();
}
/**
* ASCII码转BCD码
*/
protected static byte[] asciiToBcd(byte[] ascii, int ascLen) {
byte[] bcd = new byte[ascLen / 2];
int j = 0;
for (int i = 0; i < (ascLen + 1) / 2; i++) {
bcd[i] = ascToBcd(ascii[j++]);
bcd[i] = (byte) (((j >= ascLen) ? 0x00 : ascToBcd(ascii[j++])) + (bcd[i] << 4));
}
return bcd;
}
protected static byte ascToBcd(byte asc) {
byte bcd;
if ((asc >= '0') && (asc <= '9')) {
bcd = (byte) (asc - '0');
} else if ((asc >= 'A') && (asc <= 'F')) {
bcd = (byte) (asc - 'A' + 10);
} else if ((asc >= 'a') && (asc <= 'f')) {
bcd = (byte) (asc - 'a' + 10);
} else {
bcd = (byte) (asc - 48);
}
return bcd;
}
/**
* BCD转字符串
*/
protected static String bcd2Str(byte[] bytes) {
char temp[] = new char[bytes.length * 2];
char val;
for (int i = 0; i < bytes.length; i++) {
val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
val = (char) (bytes[i] & 0x0f);
temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
}
return new String(temp);
}
/**
* 拆分字符串
*/
protected static String[] splitString(String string, int len) {
final int x = string.length() / len;
final int y = string.length() % len;
int z = 0;
if (y != 0) {
z = 1;
}
String[] strings = new String[x + z];
String str = "";
for (int i = 0; i < x + z; i++) {
if (i == x + z - 1 && y != 0) {
str = string.substring(i * len, i * len + y);
} else {
str = string.substring(i * len, i * len + len);
}
strings[i] = str;
}
return strings;
}
/**
* 拆分数组
*/
protected static byte[][] splitArray(byte[] data, int len) {
final int x = data.length / len;
final int y = data.length % len;
int z = 0;
if (y != 0) {
z = 1;
}
byte[][] arrays = new byte[x + z][];
byte[] arr;
for (int i = 0; i < x + z; i++) {
arr = new byte[len];
if (i == x + z - 1 && y != 0) {
System.arraycopy(data, i * len, arr, 0, y);
} else {
System.arraycopy(data, i * len, arr, 0, len);
}
arrays[i] = arr;
}
return arrays;
}
}