从公钥.pem格式加密rsa android

时间:2017-08-09 18:18:12

标签: android encryption rsa

我已经在许多stackoverflows帖子中徘徊,但仍然无法弄清楚我的代码有什么问题。

public class KripAsim {
String hasil;

public String encrypt(String text) {
    try {

        String PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvCNqSslgCndo8vfNrkXFDLXmst024Oi8D7LEiJFjYBva4kBKKISe8rKp58kCLLHjv90RN+Dy2KWcf0eFkKaqc3zILBI99JhV1z8TFOzmt5dfgW6fD1ucBfsK6pWxK84DddyOqKldwHlReqjuDHT2jLue51vpXaCa12WV5bMnGsfy3vZKnp699YCguqRpTR1MijZ9pz8WqldrR0a/DCaq5YxZ7lvjwuWIodQy3S3XRHAaeaUrFHFFLumzXAGuP447oRYR0p+1qsy8+wOtrsGm8m8bMg+C1XGMblkODtOFHz3wtrRZ5OwzgEm7J7odmSX8mSYBZYLcnUVqIFRsQkZLiwIDAQAB";

        byte [] decoded = Base64.decode(PUBLIC_KEY,Base64.NO_WRAP);
        KeyFactory keyFac = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);

        PublicKey pubkey = keyFac.generatePublic(keySpec);

        Cipher rsa;
        rsa = Cipher.getInstance("RSA");
        rsa.init(Cipher.ENCRYPT_MODE, pubkey);
        hasil = Base64.encodeToString(rsa.doFinal(text.getBytes("UTF-8")),Base64.NO_WRAP);
        return hasil;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return hasil;

}
}

它返回null。请帮忙。提前谢谢

1 个答案:

答案 0 :(得分:0)

PublicKey pubkey = keyFac.generatePublic(keySpec);会抛出InvalidKeySpecException,因为如果您应该提供PKCS8EncodedKeySpec,则错误地提供了X509EncodedKeySpec

您还应该在Cipher.getInstance()方法中完全指定转换字符串。从您的代码中获取的以下片段说明了这一点:

byte[] decoded = Base64.decode(PUBLIC_KEY, Base64.DEFAULT);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded);

PublicKey pubkey = KeyFactory.getInstance("RSA").generatePublic(keySpec);
Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPwithSHA-256andMGF1Padding");
rsa.init(Cipher.ENCRYPT_MODE, pubkey);
String hasil = Base64.encodeToString(rsa.doFinal(text.getBytes("UTF-8")),
                                     Base64.NO_WRAP);
return hasil;

最后,您应该避免直接使用RSA加密数据。正确的方法是使用hybrid encryption方案,其中数据使用分组密码加密,例如在GCM模式下使用随机生成的AES密钥进行加密,然后使用RSA对此密钥进行加密。有很多这方面的例子供参考。