# andBase **Repository Path**: aggies/andBase ## Basic Information - **Project Name**: andBase - **Description**: No description available - **Primary Language**: Android - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2015-11-17 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README andBase ======= Base android Tool ``` import android.util.Base64; import java.math.BigInteger; 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.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import kotlin.text.Charsets; public class RsaParmper { public static String pubKey = ""; public static String priKey = ""; public static String data = "who are you!!"; public static void test() throws Exception { createKEY(); System.out.println("原文:" + data); //公钥加密 String encrypted = encrypt(data, pubKey); System.out.println("加密后:" + encrypted); //私钥解密 String decrypted = decrypt(encrypted, priKey); System.out.println("解密后:" + new String(decrypted)); } public static void createKEY() { int keyLength = 1024; try { //生成密钥对 KeyPair keyPair = generateRSAKeyPair(keyLength); //获取公钥 byte[] publicKey = getPublicKey(keyPair); System.out.println("RSA 公钥:" + byteArrayToString(publicKey)); //公钥用base64编码 String encodePublic = Base64.encodeToString(publicKey, Base64.DEFAULT); System.out.println("RSA base64编码的公钥:" + encodePublic); pubKey = encodePublic; //获取私钥 byte[] privateKey = getPrivateKey(keyPair); System.out.println("RSA 私钥:" + byteArrayToString(privateKey)); //私钥用base64编码 String encodePrivate = Base64.encodeToString(privateKey, Base64.DEFAULT); System.out.println("RSA base64编码的私钥:" + encodePrivate); priKey = encodePrivate; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } //将base64编码后的公钥字符串转成PublicKey实例 public static PublicKey getPublicKey(String modulusStr, String exponentStr) throws Exception { BigInteger modulus = new BigInteger(modulusStr); BigInteger exponent = new BigInteger(exponentStr); RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(modulus, exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(publicKeySpec); } //将base64编码后的私钥字符串转成PrivateKey实例 public static PrivateKey getPrivateKey(String modulusStr, String exponentStr) throws Exception { BigInteger modulus = new BigInteger(modulusStr); BigInteger exponent = new BigInteger(exponentStr); RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(modulus, exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(privateKeySpec); } //公钥加密,并转换成十六进制字符串打印出来 public static String encrypt(String content) throws Exception { PublicKey publicKey = getPublicKey(pubKey); Cipher cipher = Cipher.getInstance("RSA");//java默认"RSA"="RSA/ECB/PKCS1Padding" cipher.init(Cipher.ENCRYPT_MODE, publicKey); int splitLength = ((RSAPublicKey) publicKey).getModulus().bitLength() / 8 - 11; byte[][] arrays = splitBytes(content.getBytes(), splitLength); StringBuffer sb = new StringBuffer(); for (byte[] array : arrays) { sb.append(bytesToHexString(cipher.doFinal(array))); } return sb.toString(); } //私钥解密,并转换成十六进制字符串打印出来 public static String decrypt(String content) throws Exception { PrivateKey privateKey = getPrivateKey(priKey); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); int splitLength = ((RSAPrivateKey) privateKey).getModulus().bitLength() / 8; byte[] contentBytes = hexString2Bytes(content); byte[][] arrays = splitBytes(contentBytes, splitLength); StringBuffer sb = new StringBuffer(); for (byte[] array : arrays) { sb.append(new String(cipher.doFinal(array))); } return sb.toString(); } //公钥加密,并转换成十六进制字符串打印出来 public static String encrypt(String content, String pubKey) throws Exception { PublicKey publicKey = getPublicKey(pubKey); Cipher cipher = Cipher.getInstance("RSA");//java默认"RSA"="RSA/ECB/PKCS1Padding" cipher.init(Cipher.ENCRYPT_MODE, publicKey); int splitLength = ((RSAPublicKey) publicKey).getModulus().bitLength() / 8 - 11; byte[][] arrays = splitBytes(content.getBytes(), splitLength); StringBuffer sb = new StringBuffer(); for (byte[] array : arrays) { sb.append(bytesToHexString(cipher.doFinal(array))); } return sb.toString(); } //私钥解密,并转换成十六进制字符串打印出来 public static String decrypt(String content, String priKey) throws Exception { PrivateKey privateKey = getPrivateKey(priKey); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); int splitLength = ((RSAPrivateKey) privateKey).getModulus().bitLength() / 8; byte[] contentBytes = hexString2Bytes(content); byte[][] arrays = splitBytes(contentBytes, splitLength); StringBuffer sb = new StringBuffer(); for (byte[] array : arrays) { sb.append(new String(cipher.doFinal(array))); } return sb.toString(); } //拆分byte数组 public static byte[][] splitBytes(byte[] bytes, int splitLength) { int x; //商,数据拆分的组数,余数不为0时+1 int y; //余数 y = bytes.length % splitLength; if (y != 0) { x = bytes.length / splitLength + 1; } else { x = bytes.length / splitLength; } byte[][] arrays = new byte[x][]; byte[] array; for (int i = 0; i < x; i++) { if (i == x - 1 && bytes.length % splitLength != 0) { array = new byte[bytes.length % splitLength]; System.arraycopy(bytes, i * splitLength, array, 0, bytes.length % splitLength); } else { array = new byte[splitLength]; System.arraycopy(bytes, i * splitLength, array, 0, splitLength); } arrays[i] = array; } return arrays; } //byte数组转十六进制字符串 public static String bytesToHexString(byte[] bytes) { StringBuffer sb = new StringBuffer(bytes.length); String sTemp; for (int i = 0; i < bytes.length; i++) { sTemp = Integer.toHexString(0xFF & bytes[i]); if (sTemp.length() < 2) sb.append(0); sb.append(sTemp.toUpperCase()); } return sb.toString(); } //十六进制字符串转byte数组 public static byte[] hexString2Bytes(String hex) { int len = (hex.length() / 2); hex = hex.toUpperCase(); byte[] result = new byte[len]; char[] achar = hex.toCharArray(); for (int i = 0; i < len; i++) { int pos = i * 2; result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1])); } return result; } private static byte toByte(char c) { byte b = (byte) "0123456789ABCDEF".indexOf(c); return b; } //将base64编码后的公钥字符串转成PublicKey实例 public static PublicKey getPublicKey(String base64Key) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec data = new X509EncodedKeySpec(Base64.decode(base64Key.getBytes(), Base64.DEFAULT)); PublicKey publicKey = keyFactory.generatePublic(data); return publicKey; } //将base64编码后的私钥字符串转成PrivateKey实例 public static PrivateKey getPrivateKey(String base64Key) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decode(base64Key.getBytes(), Base64.DEFAULT)); PrivateKey privateKey = keyFactory.generatePrivate(spec); return privateKey; } private static String byteArrayToString(byte[] publicKey) { return new String(publicKey, Charsets.UTF_8); } /** * 生成密钥对,即公钥和私钥。key长度是512-2048,一般为1024 */ public static KeyPair generateRSAKeyPair(int keyLength) throws NoSuchAlgorithmException { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(keyLength); return kpg.genKeyPair(); } /** * 获取公钥,打印为48-12613448136942-12272-122-913111503-126115048-12...等等一长串用-拼接的数字 */ public static byte[] getPublicKey(KeyPair keyPair) { RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); return rsaPublicKey.getEncoded(); } /** * 获取私钥,同上 */ public static byte[] getPrivateKey(KeyPair keyPair) { RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); return rsaPrivateKey.getEncoded(); } } ```