Java examples for Security:Key
decrypt By Private Key
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.security.KeyStore; import java.security.PrivateKey; import javax.crypto.Cipher; public class Main { public static final String KEY_STORE = "JKS"; private static final int MAX_DECRYPT_BLOCK = 128; public static byte[] decryptByPrivateKey(byte[] encryptedData, String keyStorePath, String alias, String password) throws Exception { PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password); Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);//from w w w .j ava2 s. c o m } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } private static PrivateKey getPrivateKey(String keyStorePath, String alias, String password) throws Exception { KeyStore keyStore = getKeyStore(keyStorePath, password); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); return privateKey; } private static KeyStore getKeyStore(String keyStorePath, String password) throws Exception { FileInputStream in = new FileInputStream(keyStorePath); KeyStore keyStore = KeyStore.getInstance(KEY_STORE); keyStore.load(in, password.toCharArray()); in.close(); return keyStore; } }