Java Code Examples for javax.crypto.Cipher#DECRYPT_MODE
The following examples show how to use
javax.crypto.Cipher#DECRYPT_MODE .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GXDLMSSecureClient.java From gurux.dlms.java with GNU General Public License v2.0 | 6 votes |
public static Cipher getCipher(final boolean encrypt, final byte[] kek) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { GXByteBuffer iv = new GXByteBuffer(); // iv.set(IV); // iv.set(p.getSystemTitle()); // iv.setUInt32(p.getInvocationCounter()); SecretKeySpec eks = new SecretKeySpec(kek, "AES"); Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); int mode; if (encrypt) { mode = Cipher.ENCRYPT_MODE; } else { mode = Cipher.DECRYPT_MODE; } c.init(mode, eks, new GCMParameterSpec(12 * 8, iv.array())); return c; }
Example 2
Source File: CipherSpi.java From ripple-lib-java with ISC License | 6 votes |
protected int engineGetOutputSize( int inputLen) { if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + inputLen + 20; /* SHA1 MAC size */ } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() + inputLen - 20; } else { throw new IllegalStateException("cipher not initialised"); } }
Example 3
Source File: GXSecure.java From gurux.dlms.java with GNU General Public License v2.0 | 6 votes |
private static Cipher getCipher(final AesGcmParameter p, final boolean encrypt) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { GXByteBuffer iv = new GXByteBuffer(); iv.set(p.getSystemTitle()); iv.setUInt32(p.getInvocationCounter()); SecretKeySpec eks = new SecretKeySpec(p.getBlockCipherKey(), "AES"); Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); int mode; if (encrypt) { mode = Cipher.ENCRYPT_MODE; } else { mode = Cipher.DECRYPT_MODE; } c.init(mode, eks, new GCMParameterSpec(12 * 8, iv.array())); return c; }
Example 4
Source File: EncryptionUtil.java From Hive2Hive with MIT License | 6 votes |
/** * Encrypts or decrypts using AES. Note that this method uses the native method and has an upper limit for * the key size. If the size is too large, use {@link IStrongAESEncryption} instead. */ private static byte[] processAESCiphering(boolean forEncrypting, byte[] data, SecretKey key, byte[] initVector, String securityProvider) throws GeneralSecurityException { IvParameterSpec ivSpec = new IvParameterSpec(initVector); SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", securityProvider); int encryptMode = forEncrypting ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE; cipher.init(encryptMode, keySpec, ivSpec); // process ciphering byte[] output = new byte[cipher.getOutputSize(data.length)]; int bytesProcessed1 = cipher.update(data, 0, data.length, output, 0); int bytesProcessed2 = cipher.doFinal(output, bytesProcessed1); byte[] result = new byte[bytesProcessed1 + bytesProcessed2]; System.arraycopy(output, 0, result, 0, result.length); return result; }
Example 5
Source File: RSAUtils.java From unimall with Apache License 2.0 | 5 votes |
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) { int maxBlock = 0; //最大块 if (opmode == Cipher.DECRYPT_MODE) { maxBlock = keySize / 8; } else { maxBlock = keySize / 8 - 11; } ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] buff; int i = 0; try { while (datas.length > offSet) { if (datas.length - offSet > maxBlock) { //可以调用以下的doFinal()方法完成加密或解密数据: buff = cipher.doFinal(datas, offSet, maxBlock); } else { buff = cipher.doFinal(datas, offSet, datas.length - offSet); } out.write(buff, 0, buff.length); i++; offSet = i * maxBlock; } } catch (Exception e) { throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e); } byte[] resultDatas = out.toByteArray(); IOUtils.closeQuietly(out); return resultDatas; }
Example 6
Source File: SecureEncryptor.java From CogniCrypt with Eclipse Public License 2.0 | 5 votes |
public byte[] decryptData(byte[] ciphertext, javax.crypto.SecretKey key) { byte[] ivBytes = new byte[16]; byte[] data = new byte[ciphertext.length - ivBytes.length]; System.arraycopy(ciphertext, 0, ivBytes, 0, ivBytes.length); System.arraycopy(ciphertext, ivBytes.length, data, 0, data.length); int mode = Cipher.DECRYPT_MODE; byte[] res = null; CrySLCodeGenerator.getInstance().includeClass("javax.crypto.spec.IvParameterSpec").addParameter(ivBytes, "iv").includeClass("javax.crypto.Cipher") .addParameter(mode, "encmode").addParameter(data, "plainText").addParameter(key, "key").addReturnObject(res).generate(); return res; }
Example 7
Source File: GCMCipherLite.java From cos-java-sdk-v5 with MIT License | 5 votes |
private final byte[] doFinal0(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (doneFinal) { if (securityViolated) throw new SecurityException(); if (Cipher.DECRYPT_MODE == getCipherMode()) return finalBytes == null ? null : finalBytes.clone(); // final bytes must have been previously computed via encryption int finalDataLen = finalBytes.length - tagLen; if (inputLen == finalDataLen) return finalBytes.clone(); if (inputLen < finalDataLen) { if (inputLen + currentCount == outputByteCount) { int from = finalBytes.length - tagLen - inputLen; return Arrays.copyOfRange(finalBytes, from, finalBytes.length); } } throw new IllegalStateException("Inconsistent re-rencryption"); } doneFinal = true; // compute final bytes for the first time finalBytes = super.doFinal(input, inputOffset, inputLen); if (finalBytes == null) return null; // only possible for decryption outputByteCount += checkMax(finalBytes.length - tagLen); return finalBytes.clone(); }
Example 8
Source File: GCMCipherLite.java From ibm-cos-sdk-java with Apache License 2.0 | 5 votes |
GCMCipherLite(Cipher cipher, SecretKey secreteKey, int cipherMode) { super(cipher, ContentCryptoScheme.AES_GCM, secreteKey, cipherMode); tagLen = cipherMode == Cipher.ENCRYPT_MODE ? TAG_LENGTH : 0; if (cipherMode != Cipher.ENCRYPT_MODE && cipherMode != Cipher.DECRYPT_MODE) { throw new IllegalArgumentException(); } }
Example 9
Source File: RSAUtils.java From AthenaServing with Apache License 2.0 | 5 votes |
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) { int maxBlock = 0; if (opmode == Cipher.DECRYPT_MODE) { maxBlock = keySize / 8; } else { maxBlock = keySize / 8 - 11; } ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] buff; int i = 0; try { while (datas.length > offSet) { if (datas.length - offSet > maxBlock) { buff = cipher.doFinal(datas, offSet, maxBlock); } else { buff = cipher.doFinal(datas, offSet, datas.length - offSet); } out.write(buff, 0, buff.length); i++; offSet = i * maxBlock; } } catch (Exception e) { throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e); } byte[] resultDatas = out.toByteArray(); IOUtils.closeQuietly(out); return resultDatas; }
Example 10
Source File: AesCipherDataSource.java From TelePlus-Android with GNU General Public License v2.0 | 5 votes |
@Override public long open(DataSpec dataSpec) throws IOException { long dataLength = upstream.open(dataSpec); long nonce = CryptoUtil.getFNV64Hash(dataSpec.key); cipher = new AesFlushingCipher(Cipher.DECRYPT_MODE, secretKey, nonce, dataSpec.absoluteStreamPosition); return dataLength; }
Example 11
Source File: GCMCipherLite.java From markdown-image-kit with MIT License | 5 votes |
private final byte[] doFinal0(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (doneFinal) { if (securityViolated) throw new SecurityException(); if (Cipher.DECRYPT_MODE == getCipherMode()) return finalBytes == null ? null : finalBytes.clone(); // final bytes must have been previously computed via encryption int finalDataLen = finalBytes.length - tagLen; if (inputLen == finalDataLen) return finalBytes.clone(); if (inputLen < finalDataLen) { if (inputLen + currentCount == outputByteCount) { int from = finalBytes.length - tagLen - inputLen; return Arrays.copyOfRange(finalBytes, from, finalBytes.length); } } throw new IllegalStateException("Inconsistent re-rencryption"); } doneFinal = true; // compute final bytes for the first time finalBytes = super.doFinal(input, inputOffset, inputLen); if (finalBytes == null) return null; // only possible for decryption outputByteCount += checkMax(finalBytes.length - tagLen); return finalBytes.clone(); }
Example 12
Source File: ExprEncrypt.java From skUtilities with GNU General Public License v3.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public boolean init(Expression<?>[] e, int i, Kleenean k, SkriptParser.ParseResult p) { if (p.mark == 0) { ty = Cipher.ENCRYPT_MODE; } else { ty = Cipher.DECRYPT_MODE; } str = (Expression<String>) e[0]; cipher = (Expression<String>) e[1]; key = (Expression<String>) e[2]; return true; }
Example 13
Source File: FrameDecryptionHandler.java From aws-encryption-sdk-java with Apache License 2.0 | 5 votes |
/** * Construct a decryption handler for decrypting bytes stored in frames. * * @param customerMasterKey * the master key to use when unwrapping the data key encoded in * the ciphertext. */ public FrameDecryptionHandler(final SecretKey decryptionKey, final short nonceLen, final CryptoAlgorithm cryptoAlgo, final byte[] messageId, final int frameLen) { decryptionKey_ = decryptionKey; nonceLen_ = nonceLen; cryptoAlgo_ = cryptoAlgo; messageId_ = messageId; frameSize_ = frameLen; cipherHandler_ = new CipherHandler(decryptionKey_, Cipher.DECRYPT_MODE, cryptoAlgo_); }
Example 14
Source File: SecureEncryptor.java From CogniCrypt with Eclipse Public License 2.0 | 5 votes |
public java.lang.String decrypt(java.lang.String ciphertext, javax.crypto.SecretKey key) throws IOException { byte[] ciphertextString = Base64.getDecoder().decode(ciphertext); byte[] ivBytes = new byte[key.getEncoded().length]; byte[] data = new byte[ciphertextString.length - ivBytes.length]; System.arraycopy(ciphertextString, 0, ivBytes, 0, ivBytes.length); System.arraycopy(ciphertextString, ivBytes.length, data, 0, data.length); int mode = Cipher.DECRYPT_MODE; byte[] res = null; CrySLCodeGenerator.getInstance().includeClass("javax.crypto.spec.IvParameterSpec").addParameter(ivBytes, "iv").includeClass("javax.crypto.Cipher") .addParameter(mode, "encmode").addParameter(data, "plainText").addParameter(key, "key").addReturnObject(res).generate(); return new String(res, StandardCharsets.UTF_8); }
Example 15
Source File: IESCipher.java From RipplePower with Apache License 2.0 | 4 votes |
public int engineGetOutputSize(int inputLen) { int len1, len2, len3; len1 = engine.getMac().getMacSize(); if (key != null) { len2 = 1 + 2 * (((ECKey)key).getParameters().getCurve().getFieldSize() + 7) / 8; } else { throw new IllegalStateException("cipher not initialised"); } if (engine.getCipher() == null) { len3 = inputLen; } else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen); } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2); } else { throw new IllegalStateException("cipher not initialised"); } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + len1 + len2 + len3; } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() - len1 - len2 + len3; } else { throw new IllegalStateException("cipher not initialised"); } }
Example 16
Source File: HookCryptoImpl.java From Introspy-Android with GNU General Public License v2.0 | 4 votes |
public void execute(Object... args) { // let's not care about init since we are hooking // the key class already // BUT it can be useful to get a state of the mode // if needed later if (_resources != null) { try { _lastCipher = (Cipher) _resources; // get the mode Integer mode = _lastMode = (Integer) args[0]; String smode; switch (mode) { case Cipher.DECRYPT_MODE: smode = "DECRYPT_MODE"; break; case Cipher.ENCRYPT_MODE: smode = "ENCRYPT_MODE"; break; default: smode = "???"; } _logBasicInfo(); String out = "-> Mode: " + smode; // get the key Key key = (Key) args[1]; String skey = ""; if (key != null) { skey = _getReadableByteArr(key.getEncoded()); out += ", Key format: " + key.getFormat() + ", Key: [" + skey + "]"; } _logParameter("Mode", smode); _logParameter("Key", skey); _logParameter("Key Format", key.getFormat()); _logFlush_I(out); } catch (Exception e) { Log.w(_TAG_ERROR, "Error in Intro_CRYPTO: " + e); } } }
Example 17
Source File: CryptoUtils.java From cxf with Apache License 2.0 | 4 votes |
private static byte[] processBytes(byte[] bytes, Key secretKey, KeyProperties keyProps, int mode) throws SecurityException { boolean compressionSupported = keyProps != null && keyProps.isCompressionSupported(); if (compressionSupported && mode == Cipher.ENCRYPT_MODE) { bytes = CompressionUtils.deflate(bytes, false); } try { Cipher c = initCipher(secretKey, keyProps, mode); byte[] result = new byte[0]; int blockSize = keyProps != null ? keyProps.getBlockSize() : -1; if (secretKey instanceof SecretKey && blockSize == -1) { result = c.doFinal(bytes); } else { if (blockSize == -1) { if (JavaUtils.isJava8Before161()) { blockSize = secretKey instanceof PublicKey ? 117 : 128; } else { //the default block size is 256 when use private key under java9 blockSize = secretKey instanceof PublicKey ? 117 : 256; } } boolean updateRequired = keyProps != null && keyProps.getAdditionalData() != null; int offset = 0; for (; offset + blockSize < bytes.length; offset += blockSize) { byte[] next = !updateRequired ? c.doFinal(bytes, offset, blockSize) : c.update(bytes, offset, blockSize); result = addToResult(result, next); } if (offset < bytes.length) { result = addToResult(result, c.doFinal(bytes, offset, bytes.length - offset)); } else { result = addToResult(result, c.doFinal()); } } if (compressionSupported && mode == Cipher.DECRYPT_MODE) { result = IOUtils.readBytesFromStream(CompressionUtils.inflate(result, false)); } return result; } catch (Exception ex) { throw new SecurityException(ex); } }
Example 18
Source File: JCEIESCipher.java From BiglyBT with GNU General Public License v2.0 | 4 votes |
public void engineInit( int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { if (!(key instanceof IESKey)) { throw new InvalidKeyException("must be passed IE key"); } if (params == null && (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE)) { // // if nothing is specified we set up for a 128 bit mac, with // 128 bit derivation vectors. // byte[] d = new byte[16]; byte[] e = new byte[16]; if (random == null) { random = new SecureRandom(); } random.nextBytes(d); random.nextBytes(e); params = new IESParameterSpec(d, e, 128); } else if (!(params instanceof IESParameterSpec)) { throw new InvalidAlgorithmParameterException("must be passed IES parameters"); } IESKey ieKey = (IESKey)key; CipherParameters pubKey; CipherParameters privKey; if (ieKey.getPublic() instanceof JCEECPublicKey) { pubKey = ECUtil.generatePublicKeyParameter(ieKey.getPublic()); privKey = ECUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { pubKey = DHUtil.generatePublicKeyParameter(ieKey.getPublic()); privKey = DHUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } this.engineParams = (IESParameterSpec)params; IESParameters p = new IESParameters(engineParams.getDerivationV(), engineParams.getEncodingV(), engineParams.getMacKeySize()); this.state = opmode; buffer.reset(); switch (opmode) { case Cipher.ENCRYPT_MODE: case Cipher.WRAP_MODE: cipher.init(true, privKey, pubKey, p); break; case Cipher.DECRYPT_MODE: case Cipher.UNWRAP_MODE: cipher.init(false, privKey, pubKey, p); break; default: System.out.println("eeek!"); } }
Example 19
Source File: IESCipher.java From ripple-lib-java with ISC License | 4 votes |
public int engineGetOutputSize(int inputLen) { int len1, len2, len3; len1 = engine.getMac().getMacSize(); if (key != null) { len2 = 1 + 2 * (((ECKey)key).getParameters().getCurve().getFieldSize() + 7) / 8; } else { throw new IllegalStateException("cipher not initialised"); } if (engine.getCipher() == null) { len3 = inputLen; } else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen); } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2); } else { throw new IllegalStateException("cipher not initialised"); } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + len1 + len2 + len3; } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() - len1 - len2 + len3; } else { throw new IllegalStateException("cipher not initialised"); } }
Example 20
Source File: ProtocolDecoderPHE.java From TorrentEngine with GNU General Public License v3.0 | 3 votes |
protected void setupCrypto() throws IOException { try{ //"HASH('keyA', S, SKEY)" if you're A //"HASH('keyB', S, SKEY)" if you're B SHA1Hasher hasher = new SHA1Hasher(); hasher.update( KEYA_IV ); hasher.update( secret_bytes ); hasher.update( shared_secret ); byte[] a_key = hasher.getDigest(); hasher = new SHA1Hasher(); hasher.update( KEYB_IV ); hasher.update( secret_bytes ); hasher.update( shared_secret ); byte[] b_key = hasher.getDigest(); SecretKeySpec secret_key_spec_a = new SecretKeySpec( a_key, RC4_STREAM_ALG ); SecretKeySpec secret_key_spec_b = new SecretKeySpec( b_key, RC4_STREAM_ALG ); write_cipher = new TransportCipher( RC4_STREAM_CIPHER, Cipher.ENCRYPT_MODE, outbound?secret_key_spec_a:secret_key_spec_b ); read_cipher = new TransportCipher( RC4_STREAM_CIPHER, Cipher.DECRYPT_MODE, outbound?secret_key_spec_b:secret_key_spec_a ); }catch( Throwable e ){ e.printStackTrace(); throw( new IOException( Debug.getNestedExceptionMessage(e))); } }