微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

公钥/私钥加密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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐