1

我的加密知识非常基础,因此对我的任何无知表示歉意。

在 Android 应用程序中,我目前正在尝试使用SpongyCastle 库和标准java.security库来模拟此命令的执行:

echo 'test' | openssl rsautl -encrypt -pubin -inkey test.pub | base64 > encrypted_file

应该注意的是,命令中文件的读取/写入不会被实现,并且我的公钥(即)在我的代码中test.pub作为 Base64 编码的字符串。base64key

我尝试了以下方法,但确信它不起作用:

static {
       Security.insertProviderAt(new BouncyCastleProvider(), 1);
      }

//...more code here

byte[] pka = Base64.decode(base64key);

X509EncodedKeySpec x = new X509EncodedKeySpec(pka);
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(x);

byte[] testToByte = "test".getBytes("UTF8"); 

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); 
keyGen.initialize(2048); 

Cipher cipher = Cipher.getInstance("RSA"); 
cipher.init(Cipher.ENCRYPT_MODE, publicKey); 

byte[] cipherText = cipher.doFinal(testToByte); 

String encrypted = Base64.encode((new String(cipherText, "UTF8").toString().getBytes()))

我知道这很遥远,但不知道该转向哪里。任何帮助,将不胜感激。

4

1 回答 1

3

最终使用以下方法解决了这个问题:

private void stripHeaders(){

    public_key = public_key.replace("-----BEGIN PUBLIC KEY-----", "");
    public_key = public_key.replace("-----END PUBLIC KEY-----", "");

}

public byte[] encryptWithPublicKey(String encrypt) throws Exception {
    byte[] message = encrypt.getBytes("UTF-8");
    stripHeaders(); 
    PublicKey apiPublicKey= getRSAPublicKeyFromString(); 
    Cipher rsaCipher = Cipher.getInstance("RSA/None/PKCS1Padding", "SC");
    rsaCipher.init(Cipher.ENCRYPT_MODE, apiPublicKey); 
    return rsaCipher.doFinal(message);
}

private PublicKey getRSAPublicKeyFromString() throws Exception{
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SC"); 
    byte[] publicKeyBytes = Base64.decode(public_key.getBytes("UTF-8"), Base64.DEFAULT); 
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes); 
    return keyFactory.generatePublic(x509KeySpec);
}
于 2014-03-10T11:53:41.390 回答