将 PHP RSA 公钥转换为 Android 公钥

发布于 2024-11-29 09:05:20 字数 183 浏览 4 评论 0原文

我正在开发基于客户端服务器的应用程序。

我会以这种格式

在此处输入图像描述

当我将其保存到字符串中时,

获得公钥。现在我想在我的Android(Java代码)中使用这个键,我该如何使用它?

I am working on a client server based application.

Where I get PublicKey in this format

enter image description here

as I saved it into String.

Now I want to use this key in my Android(Java code), how can I use this ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

西瓜 2024-12-06 09:05:20

首先,您需要从您提供的 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");
}

First you need to generate the public key from the pem format you provided, here is my method for doing this:

/**
 * 
 * @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)));

}

And here is how I use it to read (decode) the content signed with the public key provided.

/**
 * 
 * @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");
}
ぶ宁プ宁ぶ 2024-12-06 09:05:20

有一个名为“bouncycastle”的项目,我们在 j2me 上使用它,但它也可以在 android 上运行。它可用于处理 openssl 证书。

bouncycastle.org

Java KeyStore 实现:

导入 java.security.cert.Certificate
import java.security.KeyStore

并自述了很多,因为 java 不直接支持 openssl 密钥,java 带来了自己的机制。

KeyStore 内容的 Java 示例:

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();
}

There is a project called "bouncycastle" we use it on j2me but it woll work on android too. it can be used to handle openssl certificates.

bouncycastle.org

Java KeyStore implementation:

import java.security.cert.Certificate
import java.security.KeyStore

and readme a LOT because openssl keys are not directly supported by java which is bringing their own mechanisms.

Java example for KeyStore stuff:

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文