Android網(wǎng)絡(luò)數(shù)據(jù)傳輸安全——實現(xiàn)RSA公鑰加密私鑰解密

一,整體流程

后臺生成一個RSA秘鑰對妇押,包括公鑰和私鑰
后臺將公鑰字符串下發(fā)給客戶端跷究,
然后客戶端用此公鑰生成一個RSAPublicKey對象,再將手機號密碼等數(shù)據(jù)用此對象加密舆吮,
客戶端將加密的數(shù)據(jù)發(fā)送給后臺揭朝,
后臺將加密的數(shù)據(jù)用私鑰解密队贱。

[圖片來自https://blog.csdn.net/SImple_a/article/details/80185363]

image.png

二色冀,公私鑰

你可以利用工具一鍵生成密鑰對
訪問支付寶官網(wǎng),進入如下頁面柱嫌,該頁面的URL:https://docs.open.alipay.com/291/105971

image.png

image.png
image.png
image.png

一般默認的公鑰格式是這樣的

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiwMSxbRias7DmFkp6V0Qx2nMG+"/n
AuhhR7H/wj62aufaDlUwhzaWQOKXHi+SBVcTM0n+qzhtt4Kmr44MHAqW8NE9Pgzx
UY8S7WVLn9wEGKGpZKlSHlZUdOKUabBFbS7dyBoVTYTkhrfXnOvtJJz5KGeYPT2x
dEwA78dYEmHxvmwhrwIDAQAB
-----END PUBLIC KEY-----

私鑰是這樣的

-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKLAxLFtGJqzsOYW
SnpXRDHacwYC6GFHsf/CPrZq59oOVTCHNpZA4pceL5IFVxMzSf6rOG23gqavjgwc
Cpbw0T0+DPFRjxLtZUuf3AQYoalkqVIeVlR04pRpsEVtLt3IGhVNhOSGt9ec6+0k
nPkoZ5g9PbF0TADvx1gSYfG+bCGvAgMBAAECgYAXWeceudNs5tk7ufkHopuzN2+H
bkVfJ8U/N+R9kcsgOyw34T6QwlCAdCFJJyD+LT6xnmljPJAvUELmM+PFElpC34e5
cJUFGhwjDax18tb3LW7/MBB/XH1W+9KS5ninn3Homan1x8VIE9104QMLmj2HwDCH
nI9HMXmYVhmzylNFIQJBANgvsTWq3Rw8UOXTY9uMR65Ia4Rz4fr0jyD9UIhF7j5+
dEycncrI9d7XjxgEObcegR8eoCGCALMzEmXyjcDbov8CQQDAuemo/OmHLqpA8tQm
MHhvSdLxV0lruez3ok1gFuqwTtMxBsipLFVkTZMnMqnKY/ZDqFDrXOpom7yvEy5p
BXFRAkAxDTEyMiCVRYI9g2dG619gRgJPPVPq8w5+t7tMEEHsYBjXQTn0RwCynUpU
crD9wagefX5r2+l4v3/PLefH+I3VAkBvcpLmP+qjW57klAeOVfUvFde/7CPvAcNA
qEBqUpZAgjSqYyvieFqg+CMiRa/d89RS56BzmnWLLJP+Ae+Sl60hAkEAuhheSdjL
vaVUq5UZPEtqZAuIRbQHETU7/INSViJeKvaSg9MuXJUG0f98HweMRLxHr1TjcX1c
MGojP9s2ME7b3A==
-----END PRIVATE KEY-----

可以看到都有一個頭部和尾部用來表示是公私鑰锋恬。
但是java中用收到的用于生成加密的對象接收的公鑰自串是要把頭和尾去掉的也就是這樣
去掉頭和尾

public static final String publickkey =MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiwMSxbRias7DmFkp6V0Qx2nMG+
AuhhR7H/wj62aufaDlUwhzaWQOKXHi+SBVcTM0n+qzhtt4Kmr44MHAqW8NE9Pgzx
UY8S7WVLn9wEGKGpZKlSHlZUdOKUabBFbS7dyBoVTYTkhrfXnOvtJJz5KGeYPT2x
dEwA78dYEmHxvmwhrwIDAQAB

三,執(zhí)行代碼

下面是RSAUtil 工具類的代碼

/**
 * @author: 程龍 on 2019/3/13.
 * bolg:  https://me.csdn.net/qq_25749749
 * RSA算法编丘,實現(xiàn)數(shù)據(jù)的加密解密与学。 
 */
public class RSAUtil {

    /**
     *  使用私鑰解密
     * @param content
     * @param private_key
     * @param input_charset
     * @return
     * @throws Exception
     */
    public static String decrypt(String content, String private_key, String input_charset) throws Exception {
        PrivateKey prikey = getPrivateKey(private_key);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, prikey);

        InputStream ins = new ByteArrayInputStream(Base64Util.decode(content));
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buf = new byte[128];
        int bufl;

        while ((bufl = ins.read(buf)) != -1) {
            byte[] block = null;

            if (buf.length == bufl) {
                block = buf;
            } else {
                block = new byte[bufl];
                for (int i = 0; i < bufl; i++) {
                    block[i] = buf[i];
                }
            }

            writer.write(cipher.doFinal(block));
        }

        return new String(writer.toByteArray(), input_charset);
    }

    /**
     * 獲得私鑰
     *
     * @param key
     *            私鑰
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String key) throws Exception {

        byte[] keyBytes;

        keyBytes = Base64Util.decode(key);

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        return privateKey;
    }

    /**
     * 得到公鑰
     *
     * @param bysKey
     * @return
     */
    private static PublicKey getPublicKeyFromX509(String bysKey) throws NoSuchAlgorithmException, Exception {
        byte[] decodedKey = Base64Util.decode(bysKey);
        X509EncodedKeySpec x509 = new X509EncodedKeySpec(decodedKey);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(x509);
    }

    /**
     * 使用公鑰加密
     *
     * @param content 密文
     * @param pub_key 公鑰
     * @return
     */
    public static String encryptByPublic(String content, String pub_key) {
        try {
            PublicKey pubkey = getPublicKeyFromX509(pub_key);

            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubkey);

            byte plaintext[] = content.getBytes("UTF-8");
            byte[] output = cipher.doFinal(plaintext);

            String s = new String(Base64Util.encode(output));

            return s;

        } catch (Exception e) {
            return null;
        }
    }
}

在這里提供Base64Util 的工具類

public final class Base64Util {

    static private final int     BASELENGTH           = 128;
    static private final int     LOOKUPLENGTH         = 64;
    static private final int     TWENTYFOURBITGROUP   = 24;
    static private final int     EIGHTBIT             = 8;
    static private final int     SIXTEENBIT           = 16;
    static private final int     FOURBYTE             = 4;
    static private final int     SIGN                 = -128;
    static private final char    PAD                  = '=';
    static private final boolean fDebug               = false;
    static final private byte[]  base64Alphabet       = new byte[BASELENGTH];
    static final private char[]  lookUpBase64Alphabet = new char[LOOKUPLENGTH];

    static {
        for (int i = 0; i < BASELENGTH; ++i) {
            base64Alphabet[i] = -1;
        }
        for (int i = 'Z'; i >= 'A'; i--) {
            base64Alphabet[i] = (byte) (i - 'A');
        }
        for (int i = 'z'; i >= 'a'; i--) {
            base64Alphabet[i] = (byte) (i - 'a' + 26);
        }

        for (int i = '9'; i >= '0'; i--) {
            base64Alphabet[i] = (byte) (i - '0' + 52);
        }

        base64Alphabet['+'] = 62;
        base64Alphabet['/'] = 63;

        for (int i = 0; i <= 25; i++) {
            lookUpBase64Alphabet[i] = (char) ('A' + i);
        }

        for (int i = 26, j = 0; i <= 51; i++, j++) {
            lookUpBase64Alphabet[i] = (char) ('a' + j);
        }

        for (int i = 52, j = 0; i <= 61; i++, j++) {
            lookUpBase64Alphabet[i] = (char) ('0' + j);
        }
        lookUpBase64Alphabet[62] = (char) '+';
        lookUpBase64Alphabet[63] = (char) '/';

    }

    private static boolean isWhiteSpace(char octect) {
        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
    }

    private static boolean isPad(char octect) {
        return (octect == PAD);
    }

    private static boolean isData(char octect) {
        return (octect < BASELENGTH && base64Alphabet[octect] != -1);
    }

    /**
     * Encodes hex octects into Base64
     *
     * @param binaryData Array containing binaryData
     * @return Encoded Base64 array
     */
    public static String encode(byte[] binaryData) {

        if (binaryData == null) {
            return null;
        }

        int lengthDataBits = binaryData.length * EIGHTBIT;
        if (lengthDataBits == 0) {
            return "";
        }

        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
        int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
        char encodedData[] = null;

        encodedData = new char[numberQuartet * 4];

        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;

        int encodedIndex = 0;
        int dataIndex = 0;
        if (fDebug) {
            System.out.println("number of triplets = " + numberTriplets);
        }

        for (int i = 0; i < numberTriplets; i++) {
            b1 = binaryData[dataIndex++];
            b2 = binaryData[dataIndex++];
            b3 = binaryData[dataIndex++];

            if (fDebug) {
                System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
            }

            l = (byte) (b2 & 0x0f);
            k = (byte) (b1 & 0x03);

            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
            byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);

            if (fDebug) {
                System.out.println("val2 = " + val2);
                System.out.println("k4   = " + (k << 4));
                System.out.println("vak  = " + (val2 | (k << 4)));
            }

            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
        }

        // form integral number of 6-bit groups
        if (fewerThan24bits == EIGHTBIT) {
            b1 = binaryData[dataIndex];
            k = (byte) (b1 & 0x03);
            if (fDebug) {
                System.out.println("b1=" + b1);
                System.out.println("b1<<2 = " + (b1 >> 2));
            }
            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
            encodedData[encodedIndex++] = PAD;
            encodedData[encodedIndex++] = PAD;
        } else if (fewerThan24bits == SIXTEENBIT) {
            b1 = binaryData[dataIndex];
            b2 = binaryData[dataIndex + 1];
            l = (byte) (b2 & 0x0f);
            k = (byte) (b1 & 0x03);

            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);

            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
            encodedData[encodedIndex++] = PAD;
        }

        return new String(encodedData);
    }

    /**
     * Decodes Base64 data into octects
     *
     * @param encoded string containing Base64 data
     * @return Array containind decoded data.
     */
    public static byte[] decode(String encoded) {

        if (encoded == null) {
            return null;
        }

        char[] base64Data = encoded.toCharArray();
        // remove white spaces
        int len = removeWhiteSpace(base64Data);

        if (len % FOURBYTE != 0) {
            return null;//should be divisible by four
        }

        int numberQuadruple = (len / FOURBYTE);

        if (numberQuadruple == 0) {
            return new byte[0];
        }

        byte decodedData[] = null;
        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
        char d1 = 0, d2 = 0, d3 = 0, d4 = 0;

        int i = 0;
        int encodedIndex = 0;
        int dataIndex = 0;
        decodedData = new byte[(numberQuadruple) * 3];

        for (; i < numberQuadruple - 1; i++) {

            if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
                || !isData((d3 = base64Data[dataIndex++]))
                || !isData((d4 = base64Data[dataIndex++]))) {
                return null;
            }//if found "no data" just return null

            b1 = base64Alphabet[d1];
            b2 = base64Alphabet[d2];
            b3 = base64Alphabet[d3];
            b4 = base64Alphabet[d4];

            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
        }

        if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
            return null;//if found "no data" just return null
        }

        b1 = base64Alphabet[d1];
        b2 = base64Alphabet[d2];

        d3 = base64Data[dataIndex++];
        d4 = base64Data[dataIndex++];
        if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters
            if (isPad(d3) && isPad(d4)) {
                if ((b2 & 0xf) != 0)//last 4 bits should be zero
                {
                    return null;
                }
                byte[] tmp = new byte[i * 3 + 1];
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
                return tmp;
            } else if (!isPad(d3) && isPad(d4)) {
                b3 = base64Alphabet[d3];
                if ((b3 & 0x3) != 0)//last 2 bits should be zero
                {
                    return null;
                }
                byte[] tmp = new byte[i * 3 + 2];
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
                tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
                return tmp;
            } else {
                return null;
            }
        } else { //No PAD e.g 3cQl
            b3 = base64Alphabet[d3];
            b4 = base64Alphabet[d4];
            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);

        }

        return decodedData;
    }

    /**
     * remove WhiteSpace from MIME containing encoded Base64 data.
     *
     * @param data  the byte array of base64 data (with WS)
     * @return      the new length
     */
    private static int removeWhiteSpace(char[] data) {
        if (data == null) {
            return 0;
        }

        // count characters that's not whitespace
        int newSize = 0;
        int len = data.length;
        for (int i = 0; i < len; i++) {
            if (!isWhiteSpace(data[i])) {
                data[newSize++] = data[i];
            }
        }
        return newSize;
    }
}

以上是安卓實現(xiàn)RSA公鑰加密私鑰解密的過程,有什么問題歡迎大家來討論

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末嘉抓,一起剝皮案震驚了整個濱河市索守,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌抑片,老刑警劉巖卵佛,帶你破解...
    沈念sama閱讀 211,265評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異敞斋,居然都是意外死亡截汪,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,078評論 2 385
  • 文/潘曉璐 我一進店門植捎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來衙解,“玉大人,你說我怎么就攤上這事焰枢◎韭停” “怎么了?”我有些...
    開封第一講書人閱讀 156,852評論 0 347
  • 文/不壞的土叔 我叫張陵济锄,是天一觀的道長暑椰。 經(jīng)常有香客問我,道長拟淮,這世上最難降的妖魔是什么干茉? 我笑而不...
    開封第一講書人閱讀 56,408評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮很泊,結(jié)果婚禮上角虫,老公的妹妹穿的比我還像新娘沾谓。我一直安慰自己,他們只是感情好戳鹅,可當(dāng)我...
    茶點故事閱讀 65,445評論 5 384
  • 文/花漫 我一把揭開白布均驶。 她就那樣靜靜地躺著,像睡著了一般枫虏。 火紅的嫁衣襯著肌膚如雪妇穴。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,772評論 1 290
  • 那天隶债,我揣著相機與錄音腾它,去河邊找鬼。 笑死死讹,一個胖子當(dāng)著我的面吹牛瞒滴,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播赞警,決...
    沈念sama閱讀 38,921評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼妓忍,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了愧旦?” 一聲冷哼從身側(cè)響起世剖,我...
    開封第一講書人閱讀 37,688評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎笤虫,沒想到半個月后旁瘫,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,130評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡耕皮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,467評論 2 325
  • 正文 我和宋清朗相戀三年境蜕,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片凌停。...
    茶點故事閱讀 38,617評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡粱年,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出罚拟,到底是詐尸還是另有隱情台诗,我是刑警寧澤,帶...
    沈念sama閱讀 34,276評論 4 329
  • 正文 年R本政府宣布赐俗,位于F島的核電站拉队,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏阻逮。R本人自食惡果不足惜粱快,卻給世界環(huán)境...
    茶點故事閱讀 39,882評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧事哭,春花似錦漫雷、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,740評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至谤辜,卻和暖如春蓄坏,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背丑念。 一陣腳步聲響...
    開封第一講書人閱讀 31,967評論 1 265
  • 我被黑心中介騙來泰國打工涡戳, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人渠欺。 一個月前我還...
    沈念sama閱讀 46,315評論 2 360
  • 正文 我出身青樓妹蔽,卻偏偏與公主長得像,于是被迫代替她去往敵國和親挠将。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,486評論 2 348

推薦閱讀更多精彩內(nèi)容

  • 坐在院子外面的石桌旁编整,曬著秋季溫暖的陽光舔稀,吹著干燥涼意的秋風(fēng)。我閉著眼睛掌测,腦海中細細的回想起了那么一個故事...
    念平生灬閱讀 301評論 0 1
  • 一部不是恐怖片但是我分了三次看的電影内贮。中間和鯊魚血拼的那段真的幾度放棄,真的太驚恐了汞斧。女主也是厲害外加精神強大夜郁,在...
    Super_亭小亭閱讀 207評論 0 0