RSA using SpongyCastle

做~自己de王妃 提交于 2019-12-18 14:02:09

问题


My knowledge of encryption is very basic, so apologies for any ignorance on my part.

Within an Android app I am currently trying to mimic the execution of this command using the SpongyCastle library and standard java.security libs:

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

It should be noted that the reading/writing to and from files in the command are not going to be implemented and I have my public key (i.e. test.pub) as a Base64 encoded string base64key in my code.

I have attempted the following but am certain it does not work:

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

I know this is way off, but am not sure where to turn. Any help would be appreciated.


回答1:


This was eventually solved using the following methods:

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


来源:https://stackoverflow.com/questions/22228711/rsa-using-spongycastle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!