公钥/私钥加密Android-PHP

我正在尝试加密 android端的数据并在PHP端解密它
我在PHP中使用PHPseclib来生成公钥/私钥

在我生成密钥之后,我在PHP端获得了这个公钥:

-----BEGIN RSA PUBLIC KEY-----".
            "MIGJAoGBAKks62Itns2uU/dVZJ4kCkMinHgyeh/rdMD53a4Zu2a76OIJvdSZ8q4c".
            "YTWvPj0giefVtMc7tV4c6AAw04jyIfmCTvcQUlHI+sspHxXDlQTagNoxcua29b5L".
            "9MKO6Ok0LwF9rGgTywC1heNEulZz9ISn9FQDazJT+Bd9cnnorJRdAgMBAAE=".
            "-----END RSA PUBLIC KEY-----

然后我将其编码为base64并获得此base64编码密钥

LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tTUlHSkFvR0JBS2tzNjJJdG5zMnVVL2RWWko0a0NrTWluSGd5ZWgvcmRNRDUzYTradTJhNzZPSUp2ZFNaOHE0Y1lUV3ZQajBnaWVmVnRNYzd0VjRjNkFBdzA0anlJZm1DVHZjUVVsSEkrc3NwSHhYRGxRVGFnTm94Q3VBMjliNUw5TUtPNk9rMEx3RjlyR2dUeXdDMWhlTkV1bFp6OUlTbjlGUURhekpUK0JkOWNuTk9ySlJkQWdNQkFBRT0tLS0tLUVORCBSU0EgUFVCTElDIEtFWS0tLS0t

我将它复制到android端使用它加密数据,但我得到了InvalidKeySpecException

Android侧码:

public static byte[] encrypt(String text) {

        byte[] encodedPublicKey= Base64.decode("LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tTUlHSkFvR0JBS2tzNjJJdG5zMnVVL2RWWko0a0NrTWluSGd5ZWgvcmRNRDUzYTradTJhNzZPSUp2ZFNaOHE0Y1lUV3ZQajBnaWVmVnRNYzd0VjRjNkFBdzA0anlJZm1DVHZjUVVsSEkrc3NwSHhYRGxRVGFnTm94Q3VBMjliNUw5TUtPNk9rMEx3RjlyR2dUeXdDMWhlTkV1bFp6OUlTbjlGUURhekpUK0JkOWNuTk9ySlJkQWdNQkFBRT0tLS0tLUVORCBSU0EgUFVCTElDIEtFWS0tLS0t",Base64.DEFAULT);



   PublicKey publicKey=null;
    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
        publicKey = keyFactory.generatePublic(publicKeySpec);

    } catch (NoSuchAlgorithmException e) {
        e.printstacktrace();
    }catch (InvalidKeySpecException e) {
        e.printstacktrace();
    }


    byte[] cipherText = null;
    try {
        // get an RSA cipher object and print the provider
        final Cipher cipher = Cipher.getInstance("RSA");
        // encrypt the plain text using the public key
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
        cipherText = cipher.doFinal(text.getBytes());
    } catch (Exception e) {
        e.printstacktrace();
    }
    return cipherText;
}

解决方法

以下代码解析PEM,将其从BouncyCastle提供给PKCS#1 RSAPublicKey类解析器,然后根据模数和指数构造JCE RSAPublicKey.其余的是错误处理,密钥本身和显示它的主要方法.

对于Android,您可能需要使用Spongy Castle.

package nl.owlstead.stackoverflow;

import java.io.IOException;
import java.io.StringReader;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;

import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

public final class RSAPublicKeyFromOpenSSL_PKCS1_PEM {
    private static final String PEM = "-----BEGIN RSA PUBLIC KEY-----\r\n"
            + "MIGJAoGBAKks62Itns2uU/dVZJ4kCkMinHgyeh/rdMD53a4Zu2a76OIJvdSZ8q4c\r\n"
            + "YTWvPj0giefVtMc7tV4c6AAw04jyIfmCTvcQUlHI+sspHxXDlQTagNoxcua29b5L\r\n"
            + "9MKO6Ok0LwF9rGgTywC1heNEulZz9ISn9FQDazJT+Bd9cnnorJRdAgMBAAE=\r\n"
            + "-----END RSA PUBLIC KEY-----\r\n";

    public static RSAPublicKey parsePEM(final String pem)
            throws IllegalArgumentException {

        // --- read PEM object
        final PemObject readPemObject;
        try (final PemReader reader = new PemReader(new StringReader(PEM))) {
            readPemObject = reader.readPemObject();
        } catch (final IOException e) {
            throw new IllegalArgumentException("Not a PEM object",e);
        }
        if (!readPemObject.getType().equalsIgnoreCase("RSA PUBLIC KEY")) {
            throw new IllegalArgumentException("Not a public key");
        }
        final byte[] pemContent = readPemObject.getContent();

        // --- create Bouncy Castle PKCS#1 public key
        final org.bouncycastle.asn1.pkcs.RSAPublicKey pkcs1PublicKey;
        try {
            pkcs1PublicKey = org.bouncycastle.asn1.pkcs.RSAPublicKey
                    .getInstance(pemContent);
        } catch (final Exception e) {
            throw new IllegalArgumentException(
                    "Could not parse BER PKCS#1 public key structure",e);
        }

        // --- convert to JCE RSAPublicKey
        final RSAPublicKeySpec spec = new RSAPublicKeySpec(
                pkcs1PublicKey.getModulus(),pkcs1PublicKey.getPublicExponent());
        final KeyFactory rsaKeyFact;
        try {
            rsaKeyFact = KeyFactory.getInstance("RSA");
        } catch (final NoSuchAlgorithmException e) {
            throw new IllegalStateException("RSA KeyFactory should be available",e);
        }
        try {
            return (RSAPublicKey) rsaKeyFact.generatePublic(spec);
        } catch (InvalidKeySpecException e) {
            throw new IllegalArgumentException(
                    "Invalid RSA public key,modulus and/or exponent invalid",e);
        }
    }

    public static void main(final String ... args) throws Exception {
        final RSAPublicKey publicKey = parsePEM(PEM);
        System.out.println(publicKey);
    }
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...