簡體   English   中英

將 PHP RSA PublicKey 轉換為 Android PublicKey

[英]Convert PHP RSA PublicKey into Android PublicKey

我正在開發基於客戶端服務器的應用程序。

我在哪里獲得這種格式的 PublicKey

在此處輸入圖像描述

因為我將它保存到字符串中。

現在我想在我的 Android(Java 代碼)中使用這個鍵,我該如何使用它?

首先,您需要從您提供的 pem 格式生成公鑰,這是我執行此操作的方法:

/**
 * 
 * @param PEMString  -A file/string in .pem format with a generated RSA key (with "des3", using "openssl genrsa".)
 * @param isFilePath - If it's a file path or a string
 * @return java.security.PublicKey
 * @throws IOException -No key found
 * @throws NoSuchAlgorithmException 
 * @throws InvalidKeySpecException 
 * 
 * @author hsigmond
 */

private static PublicKey getPublicKeyFromPemFormat(String PEMString,
        boolean isFilePath) throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException {

    BufferedReader pemReader = null;
    if (isFilePath) {
        pemReader = new BufferedReader(new InputStreamReader(
                new FileInputStream(PEMString)));
    } else {
        pemReader = new BufferedReader(new InputStreamReader(
                new ByteArrayInputStream(PEMString.getBytes("UTF-8"))));
    }
    StringBuffer content = new StringBuffer();
    String line = null;
    while ((line = pemReader.readLine()) != null) {
        if (line.indexOf("-----BEGIN PUBLIC KEY-----") != -1) {
            while ((line = pemReader.readLine()) != null) {
                if (line.indexOf("-----END PUBLIC KEY") != -1) {
                    break;
                }
                content.append(line.trim());
            }
            break;
        }
    }
    if (line == null) {
        throw new IOException("PUBLIC KEY" + " not found");
    }
Log.i("PUBLIC KEY: ", "PEM content = : " + content.toString());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(content.toString(), Base64.DEFAULT)));

}

以下是我如何使用它來讀取(解碼)使用提供的公鑰簽名的內容。

/**
 * 
 * @param PEMString  -A file/string in .pem format with a generated RSA key (with "des3", using "openssl genrsa".)
 * @param content
 * @return String value of content Decoded
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * 
 * @author hsigmond
 */


    public static String getContentWithPublicKeyFromPemFormat(String PEMString,
        String content,boolean isFilePath) throws NoSuchAlgorithmException,
        InvalidKeySpecException, IOException, NoSuchProviderException,
        NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException {

    PublicKey publicKey = getPublicKeyFromPemFormat(PEMString,isFilePath);
    if (publicKey != null)
        Log.i("PUBLIC KEY: ", "FORMAT : " + publicKey.getFormat()
                + " \ntoString : " + publicKey.toString());

    byte[] contentBytes = Base64.decode(content, Base64.DEFAULT);
    byte[] decoded = null;

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");//BC=BouncyCastle Provider
    cipher.init(Cipher.DECRYPT_MODE, publicKey);
    decoded = cipher.doFinal(contentBytes);
    return new String(decoded, "UTF-8");
}

有一個名為“bouncycastle”的項目我們在 j2me 上使用它,但它也適用於 android。 可用於辦理openssl證書。

bouncycastle.org

Java KeyStore 實現:

導入 java.security.cert.Certificate 導入 java.security.KeyStore

並自述很多,因為 openssl 密鑰不受 java 直接支持,它帶來了自己的機制。

Java KeyStore 的例子:

byte[] certData = ...       
/* create KeyStore */
KeyStore ks = KeyStore.getInstance("JKS", "SUN");
/* load key store (initialization */
ks.load(null, null);
/* create CertificateFactory */
CertificateFactory cf = CertificateFactory.getInstance("X509");
/* create certificate from input stream */
Certificate cert;
/* provide cert data */
ByteArrayInputStream in = new ByteArrayInputStream(makeCert(certData));



private static byte[] makeCert(byte[] data) {
    String headline = "-----BEGIN CERTIFICATE-----";
    String footline = "-----END CERTIFICATE-----";

    String certStr = headline;
    for (int i = 0; i < data.length; i++) {
        if (i%64 == 0) {
            certStr += "\n";
        }
        certStr += (char)data[i];
    }
    if ((data.length-1)%64 != 0) {
        certStr += "\n";
    }
    certStr += footline;
    return certStr.getBytes();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM