Java examples for Security:RSA
RSA decrypt
import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; import java.security.KeyFactory; import java.security.Signature; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class Main{ public byte[] decrypt(byte[] secret) { if (privateKey == null) { throw new RuntimeException("private key is null."); }/*w w w .ja v a 2 s . co m*/ try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); int size = privateKey.getModulus().bitLength() / 8; ByteArrayOutputStream baos = new ByteArrayOutputStream( (secret.length + size - 12) / (size - 11) * size); int left = 0; for (int i = 0; i < secret.length;) { left = secret.length - i; if (left > size) { cipher.update(secret, i, size); i += size; } else { cipher.update(secret, i, left); i += left; } baos.write(cipher.doFinal()); } return baos.toByteArray(); } catch (Exception e) { throw new RuntimeException(e); } } public static byte[] decrypt(byte[] secret, byte[] privateKey) { return new RsaHelper(null, privateKey).decrypt(secret); } }