1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
private static PrivateKey getPrivateKey() throws Exception { KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey prvK = kf .generatePrivate(new PKCS8EncodedKeySpec(FileUtils.readFileToByteArray(new File("prv.xx")))); return prvK; }
public static byte [] rsaPrivateKeyEncrypt(byte [] inputBytes) throws Exception { return rsaPrivateKeyCrypt(inputBytes,true); }
public static byte [] rsaPrivateKeyDecrypt(byte [] inputBytes) throws Exception { return rsaPrivateKeyCrypt(inputBytes,false); }
public static byte [] rsaPublicKeyDecrypt(byte [] inputBytes) throws Exception { return rsaPublicKeyCrypt(inputBytes, false); }
public static byte [] rsaPublicKeyEncrypt(byte [] inputBytes) throws Exception { return rsaPublicKeyCrypt(inputBytes, true); }
private static byte [] rsaPublicKeyCrypt(byte [] inputBytes ,boolean forEncryption) throws Exception { return rsaCrypt(inputBytes,forEncryption,true); }
private static byte [] rsaPrivateKeyCrypt(byte [] inputBytes ,boolean forEncryption) throws Exception { return rsaCrypt(inputBytes,forEncryption,false); }
private static byte [] rsaCrypt(byte [] inputBytes,boolean forEncryption,boolean isPublicKey) throws Exception { final int MAX_BLOCK = 128; AsymmetricKeyParameter param =null; if(isPublicKey) { param = PublicKeyFactory.createKey(getPublicKey().getEncoded()); } else { param = PrivateKeyFactory.createKey(getPrivateKey().getEncoded()); } AsymmetricBlockCipher eng = new RSAEngine(); eng.init(forEncryption, param); return blockLoop(inputBytes,eng,MAX_BLOCK ); }
private static byte [] blockLoop(byte [] inputArray,AsymmetricBlockCipher engine,int maxBlockSize) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); int arrayLen = inputArray.length; int offset = 0; byte [] tempCache =null; int looptime = 0; while((arrayLen - offset )>0) { int prcoessLen = (arrayLen - offset > maxBlockSize ) ? maxBlockSize : (arrayLen - offset); tempCache = engine.processBlock(inputArray, offset, prcoessLen); out.write(tempCache, 0, tempCache.length); looptime++; offset= looptime * maxBlockSize; } byte[] outArray = out.toByteArray(); out.close(); return outArray; }
|