RSA 非對稱加密演算法的Java實現

来源:https://www.cnblogs.com/MillerKevin/archive/2019/06/24/11079076.html
-Advertisement-
Play Games

關於RSA的介紹Google一下很多,這裡不做說明。項目開發中一般會把公鑰放在本地進行加密,服務端通過私鑰進行解密。Android項目開發中要用到這個加密演算法,總結後實現如下: 使用如下: ...


關於RSA的介紹Google一下很多,這裡不做說明。項目開發中一般會把公鑰放在本地進行加密,服務端通過私鑰進行解密。Android項目開發中要用到這個加密演算法,總結後實現如下:

import android.content.Context;
import android.util.Base64;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;


public class RSAUtil {

    /**
     * KEY_ALGORITHM
     */
    public static final String KEY_ALGORITHM = "RSA";
    /**
     * 加密Key的長度等於1024
     */
    public static int KEYSIZE = 1024;
    /**
     * 解密時必須按照此分組解密
     */
    public static int decodeLen = KEYSIZE / 8;
    /**
     * 加密時小於117即可
     */
    public static int encodeLen = 110;//(DEFAULT_KEY_SIZE / 8) - 11;

    /**
     * 加密填充方式,android系統的RSA實現是"RSA/None/NoPadding",而標準JDK實現是"RSA/None/PKCS1Padding" ,這造成了在android機上加密後無法在伺服器上解密的原因
     */
    public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";


    public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];


    /**
     * 通過公鑰加密
     */
    public static byte[] encryptPublicKey(byte[] encryptedData, String key) throws Exception {
        if (encryptedData == null) {
            throw new IllegalArgumentException("Input encryption data is null");
        }
        byte[] encode = new byte[]{};
        for (int i = 0; i < encryptedData.length; i += encodeLen) {
            byte[] subarray = subarray(encryptedData, i, i + encodeLen);
            byte[] doFinal = encryptByPublicKey(subarray, key);
            encode = addAll(encode, doFinal);
        }
        return encode;
    }

    /**
     * 通過私鑰解密
     */
    public static byte[] decryptPrivateKey(byte[] encode, String key) throws Exception {
        if (encode == null) {
            throw new IllegalArgumentException("Input data is null");
        }
        byte[] buffers = new byte[]{};
        for (int i = 0; i < encode.length; i += decodeLen) {
            byte[] subarray = subarray(encode, i, i + decodeLen);
            byte[] doFinal = decryptByPrivateKey(subarray, key);
            buffers = addAll(buffers, doFinal);
        }
        return buffers;
    }

    /**
     * 從字元串中載入公鑰
     *
     * @param publicKeyStr 公鑰數據字元串
     */
    private static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
        try {
            byte[] buffer = decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //表示根據 ASN.1 類型 SubjectPublicKeyInfo 進行編碼的公用密鑰的 ASN.1 編碼。
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return 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指令)。
     */
    private static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
        try {
            byte[] buffer = decode(privateKeyStr);
            //表示按照 ASN.1 類型 PrivateKeyInfo 進行編碼的專用密鑰的 ASN.1 編碼。
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            return keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此演算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私鑰非法");
        } catch (NullPointerException e) {
            throw new Exception("私鑰數據為空");
        }
    }


    /**
     * 用私鑰解密
     */
    private static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {
        if (data == null) {
            throw new IllegalArgumentException("Input data is null");
        }
        //取得私鑰
        Key privateKey = loadPrivateKey(key);
        // 對數據解密
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        return cipher.doFinal(data);
    }


    /**
     * 用公鑰加密
     */
    private static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
        if (data == null) {
            throw new IllegalArgumentException("Input data is null");
        }
        // 取得公鑰
        Key publicKey = loadPublicKey(key);
        // 對數據加密
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        return cipher.doFinal(data);
    }


    /**
     * <p>
     * BASE64字元串解碼為二進位數據
     * </p>
     */
    public static byte[] decode(String base64) {
        return Base64.decode(base64, Base64.DEFAULT);
    }

    /**
     * <p>
     * 二進位數據編碼為BASE64字元串
     * </p>
     */
    public static String encode(byte[] bytes) {
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }


    /**
     * <p>Produces a new {@code byte} array containing the elements
     * between the start and end indices.
     *
     * <p>The start index is inclusive, the end index exclusive.
     * Null array input produces null output.
     *
     * @param array               the array
     * @param startIndexInclusive the starting index. Undervalue (&lt;0)
     *                            is promoted to 0, overvalue (&gt;array.length) results
     *                            in an empty array.
     * @param endIndexExclusive   elements up to endIndex-1 are present in the
     *                            returned subarray. Undervalue (&lt; startIndex) produces
     *                            empty array, overvalue (&gt;array.length) is demoted to
     *                            array length.
     * @return a new array containing the elements between
     * the start and end indices.
     * @since 2.1
     */
    private static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {
        if (array == null) {
            return null;
        }
        if (startIndexInclusive < 0) {
            startIndexInclusive = 0;
        }
        if (endIndexExclusive > array.length) {
            endIndexExclusive = array.length;
        }
        final int newSize = endIndexExclusive - startIndexInclusive;
        if (newSize <= 0) {
            return EMPTY_BYTE_ARRAY;
        }

        final byte[] subarray = new byte[newSize];
        System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
        return subarray;
    }

    /**
     * <p>Adds all the elements of the given arrays into a new array.
     * <p>The new array contains all of the element of {@code array1} followed
     * by all of the elements {@code array2}. When an array is returned, it is always
     * a new array.
     *
     * @param array1 the first array whose elements are added to the new array.
     * @param array2 the second array whose elements are added to the new array.
     * @return The new byte[] array.
     * @since 2.1
     */
    private static byte[] addAll(final byte[] array1, final byte... array2) {
        if (array1 == null) {
            return clone(array2);
        } else if (array2 == null) {
            return clone(array1);
        }
        final byte[] joinedArray = new byte[array1.length + array2.length];
        System.arraycopy(array1, 0, joinedArray, 0, array1.length);
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
        return joinedArray;
    }

    /**
     * <p>Clones an array returning a typecast result and handling
     * {@code null}.
     *
     * <p>This method returns {@code null} for a {@code null} input array.
     *
     * @param array the array to clone, may be {@code null}
     * @return the cloned array, {@code null} if {@code null} input
     */
    private static byte[] clone(final byte[] array) {
        if (array == null) {
            return null;
        }
        return array.clone();
    }


    /**
     * 讀取密鑰信息
     */
    public static String readString(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 encryptStr 待加密字元串
     * rsa_public_key.pem 為本地公鑰
     */
    public String getEncryptData(Context context, String encryptStr) {

        try {
            InputStream inPublic = context.getResources().getAssets().open("rsa_public_key.pem");
            String publicKey = readString(inPublic);
            byte[] encodedData = encryptPublicKey(encryptStr.getBytes(), publicKey);

            return encode(encodedData);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一.安裝redis #一主二從三台Server安裝步驟相同。 wget http://download.redis.io/releases/redis-5.0.4.tar.gz tar xzf redis-5.0.4.tar.gz cd redis-5.0.4 make 二.配置埠 master默 ...
  • 1、getset key newValue //給key設置value,並返回舊的value,如果沒有舊的value,返回nil。 示例: set age 10 getset age 20 //age 的值被設置為20,並返回舊的值10 2、getrange key start end //獲取va ...
  • ①length 函數說明:計算字元串長度的函數 返回結果:數字 使用圖解: ②lengthb 函數說明:計算字元串位元組長度。在學習過程中,瞭解到還有一個 lengthb 函數。位元組和字元的區別 返回結果:數字 使用圖解:(漢字占兩個位元組,數字和字母占一個位元組) 🌂substr 函數說明:字元截取函 ...
  • 上周遇到了將數據從orcle導入到impala的問題,這個項目耽誤了我近一周的時間,雖然是種種原因導致的,但是還是做個總結。 需求首先是跑數據,跑數據這個就不敘述,用的是公司的平臺。 講講耽誤我最久的事吧 數據的導入導出。 將數據從orcle導出 PLSQL直接導出 我這邊連接公司的orcle資料庫 ...
  • 文 | 子龍 有技術,有乾貨,有故事的斜杠青年 一,寫在前面的話 最近公司需要按天,按小時查看數據,可以直觀的看到時間段的數據峰值。接到需求,就開始瘋狂百度搜索,但是搜索到的資料有很多都不清楚,需要自己去總結和挖掘其中的重要信息。現在我把分享出來了呢,希望大家喜歡。 針對sqlserver, 有幾點 ...
  • select dateadd(dd,-day(getdate()) + 1,getdate()) '當月起始時間' //查詢當月起始時間 select dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0)) '當月結束時間' //查詢當月結束 ...
  • 1.什麼是redis redis是用C語言開發的一個開源的高性能鍵值對(key-value)資料庫。它通過提供多種鍵值數據類型來適應不同場景下的存儲需求,目前為止redis支持的鍵值數據類型如下字元串、列表(lists)、集合(sets)、有序集合(sorts sets)、哈希表(hashs) 2. ...
  • flutter最近顯得格外的火,公司的同事也一直在談論flutter,感覺自己不學學就要失業了。。。所以決定順應潮流學習以下flutter,做一下學習筆記,希望可以給需要的同學帶來一些幫助~ ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...