Search code examples
javaandroidencryptionspongycastle

RSA using SpongyCastle


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.


Solution

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