Java Code Examples for java.util.Arrays#copyOfRange()
The following examples show how to use
java.util.Arrays#copyOfRange() .
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: Crypto.java From divide with Apache License 2.0 | 6 votes |
public static byte[] decrypt(byte[] encryptedMessage, PrivateKey privateKey) { try { // Read the symmetric key from the encrypted message (and its length) int length = byteArrayToInt(Arrays.copyOf(encryptedMessage,4)); byte[] wrappedKey = Arrays.copyOfRange(encryptedMessage,4,4+length); // Decrypt the symmetric key Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING"); cipher.init(Cipher.UNWRAP_MODE, privateKey); Key symmetricKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); // Decrypt the message and return it cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, symmetricKey); return cipher.doFinal(Arrays.copyOfRange(encryptedMessage,4+length,encryptedMessage.length)); } catch (GeneralSecurityException exception) { exception.printStackTrace(); return null; } }
Example 2
Source File: HiveTest.java From pxf with Apache License 2.0 | 6 votes |
private void prepareManyPartitionedData() throws Exception { if (hiveManyPartitionsTable != null) return; hiveManyPartitionsTable = new HiveTable(HIVE_MANY_PARTITIONED_TABLE, new String[]{"t1 STRING"}); String[] partitionedColumns = Arrays.copyOfRange(HIVE_TYPES_COLS, 1, HIVE_TYPES_COLS.length); hiveManyPartitionsTable.setPartitionedBy(partitionedColumns); hive.createTableAndVerify(hiveManyPartitionsTable); hive.runQuery("SET hive.exec.dynamic.partition = true"); hive.runQuery("SET hive.exec.dynamic.partition.mode = nonstrict"); hive.runQuery("SET hive.stats.autogather = false"); // Insert into table using dynamic partitioning. // Some of the fields are NULL so they will be inserted into the default partition. hive.insertDataToPartition(hiveTypesTable, hiveManyPartitionsTable, new String[]{"t2", "num1", "dub1", "dec1", "tm", "r", "bg", "b", "tn", "sml", "dt", "vc1", "c1", "bin"}, new String[]{"*"}); }
Example 3
Source File: NTLM.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
byte[] readBytes(int offset, int len) throws NTLMException { try { return Arrays.copyOfRange(internal, offset, offset + len); } catch (ArrayIndexOutOfBoundsException ex) { throw new NTLMException(NTLMException.PACKET_READ_ERROR, "Input message incorrect size"); } }
Example 4
Source File: IntArrayData.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
@Override public ArrayData slice(final long from, final long to) { final long start = from < 0 ? (from + length()) : from; final long newLength = to - start; return new IntArrayData(Arrays.copyOfRange(array, (int)from, (int)to), (int)newLength); }
Example 5
Source File: TypeIdGenerator.java From jblink with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static long hashTid (String s) { try { MessageDigest md = MessageDigest.getInstance ("SHA-1"); md.update (s.getBytes ("UTF-8")); byte [] bits = Arrays.copyOfRange (md.digest (), 0, 8); return (new BigInteger (bits)).longValue (); } catch (Exception e) { return 0; } }
Example 6
Source File: MnemonicCode.java From ontology-java-sdk with GNU Lesser General Public License v3.0 | 5 votes |
public static String encryptMnemonicCodesStr(String mnemonicCodesStr, String password, String address) throws Exception { if(mnemonicCodesStr == null || mnemonicCodesStr.equals("") || password==null || password.equals("")||address==null||address.equals("")){ throw new SDKException(ErrorCode.ParamError); } int N = 4096; int r = 8; int p = 8; int dkLen = 64; byte[] addresshashTmp = Digest.sha256(Digest.sha256(address.getBytes())); byte[] salt = Arrays.copyOfRange(addresshashTmp, 0, 4); byte[] derivedkey = SCrypt.generate(password.getBytes(StandardCharsets.UTF_8), salt, N, r, p, dkLen); password = null; byte[] derivedhalf2 = new byte[32]; byte[] iv = new byte[16]; System.arraycopy(derivedkey, 0, iv, 0, 16); System.arraycopy(derivedkey, 32, derivedhalf2, 0, 32); SecretKeySpec skeySpec = new SecretKeySpec(derivedhalf2, "AES"); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv)); byte[] encryptedkey = cipher.doFinal(mnemonicCodesStr.getBytes()); mnemonicCodesStr = null; return new String(Base64.getEncoder().encode(encryptedkey)); }
Example 7
Source File: NIOSocketHandler.java From ISO8583-Message-Client-java with MIT License | 5 votes |
public byte[] sendMessageSync(ByteBuffer buffer, int length) throws IOException { if(sslHandler != null) { byte[] data = sendMessageSyncOverSsl(buffer); return Arrays.copyOfRange(data,(length>0)?(length):(0),data.length); } else{ myAppData.clear(); myAppData.put(buffer.array()); myAppData.flip(); while(myAppData.hasRemaining()) { socketChannel.write(myAppData); } myAppData.clear(); myAppData.compact(); myAppData.flip(); int r; do{ r = socketChannel.read(myAppData); } while (myAppData.remaining() >=0 && r == 0); if(myAppData.position() > length) return Arrays.copyOfRange(myAppData.array(),(length>0)?(length):(0),myAppData.position()); return new byte[0]; } }
Example 8
Source File: GPCrypto.java From openjavacard-tools with GNU Lesser General Public License v3.0 | 5 votes |
private static byte[] mac_des_3des(GPKey key, byte[] text, int offset, int length, byte[] iv) { try { // get ciphers Cipher cipherA = Cipher.getInstance(DES3_CBC_NOPAD); Cipher cipherB = Cipher.getInstance(DES_CBC_NOPAD); // get keys (truncated version for DES) SecretKey keyA = key.getSecretKey(GPKeyCipher.DES3); SecretKey keyB = key.getSecretKey(GPKeyCipher.DES); // IV for final round depends on whether we have previous rounds byte[] finalIV = iv; // pre-final rounds if (length > 8) { // long messages get all but the last block hashed using DES cipherB.init(Cipher.ENCRYPT_MODE, keyB, new IvParameterSpec(iv)); byte[] partial = cipherB.doFinal(text, offset, length - 8); // and use the output from that as the IV for the 3DES final round finalIV = Arrays.copyOfRange(partial, partial.length - 8, partial.length); } // final round cipherA.init(Cipher.ENCRYPT_MODE, keyA, new IvParameterSpec(finalIV)); byte[] finalCipher = cipherA.doFinal(text, (offset + length) - 8, 8); // copy result and return return Arrays.copyOfRange(finalCipher, finalCipher.length - 8, finalCipher.length); } catch (Exception e) { throw new RuntimeException("MAC computation failed", e); } }
Example 9
Source File: Main.java From java-market-maker with Apache License 2.0 | 5 votes |
private static char[] readPassphrase() throws IOException { System.out.println("Private key passphrase (will be echoed):"); final char[] input = new char[100]; final int read = new InputStreamReader(System.in, StandardCharsets.US_ASCII).read(input); checkState(read != 100, "Input too long"); final char[] keyPassword = Arrays.copyOfRange(input, 0, read - 1); // -1 because we don't want \n Arrays.fill(input, (char) 5); return keyPassword; }
Example 10
Source File: BinaryReadOnlyData.java From Angelia-core with GNU General Public License v3.0 | 5 votes |
/** * Reads an array of NBT objects, which is prefixed by its own length (in the * form of a varint) * * @return Parsed NBT array * @throws EndOfPacketException Thrown if data is invalid */ public NBTCompound[] readNBTArray() throws EndOfPacketException { int length = readVarInt(); NBTCompound[] result = new NBTCompound[length]; for (int i = 0; i < length; i++) { NBTParser parser = new NBTParser(Arrays.copyOfRange(data, dataPointer, data.length)); result[i] = parser.parse(); dataPointer += parser.getLength(); } return result; }
Example 11
Source File: EcUtil.java From wycheproof with Apache License 2.0 | 5 votes |
/** * Decompress a point on an elliptic curve. * * @param bytes The compressed point. Its representation is z || x where z is 2+lsb(y) and x is * using a unsigned fixed length big-endian representation. * @param ecParams the specification of the curve. Only Weierstrass curves over prime order fields * are implemented. */ public static ECPoint decompressPoint(byte[] bytes, ECParameterSpec ecParams) throws GeneralSecurityException { EllipticCurve ec = ecParams.getCurve(); ECField field = ec.getField(); if (!(field instanceof ECFieldFp)) { throw new GeneralSecurityException("Only curves over prime order fields are supported"); } BigInteger p = ((java.security.spec.ECFieldFp) field).getP(); int expectedLength = 1 + (p.bitLength() + 7) / 8; if (bytes.length != expectedLength) { throw new GeneralSecurityException("compressed point has wrong length"); } boolean lsb; switch (bytes[0]) { case 2: lsb = false; break; case 3: lsb = true; break; default: throw new GeneralSecurityException("Invalid format"); } BigInteger x = new BigInteger(1, Arrays.copyOfRange(bytes, 1, bytes.length)); if (x.compareTo(BigInteger.ZERO) == -1 || x.compareTo(p) != -1) { throw new GeneralSecurityException("x is out of range"); } // Compute rhs == x^3 + a x + b (mod p) BigInteger rhs = x.multiply(x).add(ec.getA()).multiply(x).add(ec.getB()).mod(p); BigInteger y = modSqrt(rhs, p); if (lsb != y.testBit(0)) { y = p.subtract(y).mod(p); } return new ECPoint(x, y); }
Example 12
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 13
Source File: NTLM.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
byte[] readSecurityBuffer(int offset) throws NTLMException { int pos = readInt(offset+4); if (pos == 0) return null; try { return Arrays.copyOfRange( internal, pos, pos + readShort(offset)); } catch (ArrayIndexOutOfBoundsException ex) { throw new NTLMException(NTLMException.PACKET_READ_ERROR, "Input message incorrect size"); } }
Example 14
Source File: RX64IOPacket.java From xbee-java with Mozilla Public License 2.0 | 5 votes |
/** * Creates an new {@code RX64IOPacket} object from the given payload. * * @param payload The API frame payload. It must start with the frame type * corresponding to a RX64 Address IO packet ({@code 0x82}). * The byte array must be in {@code OperatingMode.API} mode. * * @return Parsed RX64 Address IO packet. * * @throws IllegalArgumentException if {@code payload[0] != APIFrameType.RX_64.getValue()} or * if {@code payload.length < }{@value #MIN_API_PAYLOAD_LENGTH} or * if {@code rssi < 0} or * if {@code rssi > 255} or * if {@code receiveOptions < 0} or * if {@code receiveOptions > 255}. * @throws NullPointerException if {@code payload == null}. */ public static RX64IOPacket createPacket(byte[] payload) { if (payload == null) throw new NullPointerException("RX64 Address IO packet payload cannot be null."); // 1 (Frame type) + 8 (64-bit address) + 1 (RSSI) + 1 (receive options) if (payload.length < MIN_API_PAYLOAD_LENGTH) throw new IllegalArgumentException("Incomplete RX64 Address IO packet."); if ((payload[0] & 0xFF) != APIFrameType.RX_IO_64.getValue()) throw new IllegalArgumentException("Payload is not a RX64 Address IO packet."); // payload[0] is the frame type. int index = 1; // 8 bytes of 64-bit address. XBee64BitAddress sourceAddress64 = new XBee64BitAddress(Arrays.copyOfRange(payload, index, index + 8)); index = index + 8; // Received Signal Strength Indicator byte. int rssi = payload[index] & 0xFF; index = index + 1; // Received Options byte. int receiveOptions = payload[index] & 0xFF; index = index + 1; // Get data. byte[] data = null; if (index < payload.length) data = Arrays.copyOfRange(payload, index, payload.length); return new RX64IOPacket(sourceAddress64, rssi, receiveOptions, data); }
Example 15
Source File: MethodHandleImpl.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 4 votes |
/** Factory method: Collect or filter selected argument(s). */ static MethodHandle makeCollectArguments(MethodHandle target, MethodHandle collector, int collectArgPos, boolean retainOriginalArgs) { MethodType targetType = target.type(); // (a..., c, [b...])=>r MethodType collectorType = collector.type(); // (b...)=>c int collectArgCount = collectorType.parameterCount(); Class<?> collectValType = collectorType.returnType(); int collectValCount = (collectValType == void.class ? 0 : 1); MethodType srcType = targetType // (a..., [b...])=>r .dropParameterTypes(collectArgPos, collectArgPos+collectValCount); if (!retainOriginalArgs) { // (a..., b...)=>r srcType = srcType.insertParameterTypes(collectArgPos, collectorType.parameterList()); } // in arglist: [0: ...keep1 | cpos: collect... | cpos+cacount: keep2... ] // out arglist: [0: ...keep1 | cpos: collectVal? | cpos+cvcount: keep2... ] // out(retain): [0: ...keep1 | cpos: cV? coll... | cpos+cvc+cac: keep2... ] // Now build a LambdaForm. MethodType lambdaType = srcType.invokerType(); Name[] names = arguments(2, lambdaType); final int collectNamePos = names.length - 2; final int targetNamePos = names.length - 1; Name[] collectorArgs = Arrays.copyOfRange(names, 1 + collectArgPos, 1 + collectArgPos + collectArgCount); names[collectNamePos] = new Name(collector, (Object[]) collectorArgs); // Build argument array for the target. // Incoming LF args to copy are: [ (mh) headArgs collectArgs tailArgs ]. // Output argument array is [ headArgs (collectVal)? (collectArgs)? tailArgs ]. Name[] targetArgs = new Name[targetType.parameterCount()]; int inputArgPos = 1; // incoming LF args to copy to target int targetArgPos = 0; // fill pointer for targetArgs int chunk = collectArgPos; // |headArgs| System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk); inputArgPos += chunk; targetArgPos += chunk; if (collectValType != void.class) { targetArgs[targetArgPos++] = names[collectNamePos]; } chunk = collectArgCount; if (retainOriginalArgs) { System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk); targetArgPos += chunk; // optionally pass on the collected chunk } inputArgPos += chunk; chunk = targetArgs.length - targetArgPos; // all the rest System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk); assert(inputArgPos + chunk == collectNamePos); // use of rest of input args also names[targetNamePos] = new Name(target, (Object[]) targetArgs); LambdaForm form = new LambdaForm("collect", lambdaType.parameterCount(), names); return SimpleMethodHandle.make(srcType, form); }
Example 16
Source File: ApkSigningPayload.java From walle with Apache License 2.0 | 4 votes |
public byte[] getByteBuffer() { final byte[] array = buffer.array(); final int arrayOffset = buffer.arrayOffset(); return Arrays.copyOfRange(array, arrayOffset + buffer.position(), arrayOffset + buffer.limit()); }
Example 17
Source File: LocalLyricsFragment.java From QuickLyric with GNU General Public License v3.0 | 4 votes |
public void showScanDialog() { final String[] values = getResources().getStringArray(R.array.URI_values); CharSequence[] items = Arrays .copyOfRange(getResources().getStringArray(R.array.URI_labels), 0, values.length); AlertDialog.Builder choiceBuilder = new AlertDialog.Builder(getActivity()); AlertDialog choiceDialog = choiceBuilder .setTitle(R.string.content_providers_title) .setSingleChoiceItems(items, -1, (choiceDialog1, i) -> { if (values[i].equals("Spotify")) { AlertDialog.Builder spotifyChoiceBuilder = new AlertDialog.Builder(getActivity()); spotifyChoiceBuilder.setSingleChoiceItems(R.array.spotify_options, -1, (dialog, which) -> { switch (which) { case 1: Spotify.getPlaylistTracks(getActivity()); dialog.dismiss(); choiceDialog1.dismiss(); break; case 0: Spotify.getUserTracks(getActivity()); dialog.dismiss(); choiceDialog1.dismiss(); break; } }).show(); return; } else { if (!PermissionsChecker.requestPermission(getActivity(), "android.permission.READ_EXTERNAL_STORAGE", 0, LocalLyricsFragment.REQUEST_CODE)) return; } int failureMsg = R.string.scan_error_no_content; final Uri contentProvider = Uri.parse(values[i]); String[] projection = new String[]{"artist", "title"}; String selection = ""; Cursor countCursor = null; try { countCursor = getActivity().getContentResolver() .query(contentProvider, projection, selection, null, null); } catch (SecurityException ignored) { ignored.printStackTrace(); failureMsg = R.string.gmusic_import_securityException; } if (countCursor == null || countCursor.getCount() == 0) { choiceDialog1.cancel(); Toast.makeText(getActivity(), getString(failureMsg), Toast.LENGTH_LONG) .show(); return; } int count = countCursor.getCount(); final int time = (int) Math.ceil(count / 360f); countCursor.close(); choiceDialog1.dismiss(); String prompt = getResources() .getQuantityString(R.plurals.scan_dialog, count); AlertDialog.Builder confirmDialog = new AlertDialog.Builder(getActivity()); confirmDialog .setTitle(R.string.warning) .setMessage(String.format(prompt, count, time)) .setPositiveButton(android.R.string.ok, (dialogInterface, i1) -> { Intent scanInfo = new Intent(getActivity(), BatchDownloaderService.class); scanInfo.putExtra("uri", contentProvider); getActivity().startService(scanInfo); }) .setNegativeButton(android.R.string.cancel, null) .create().show(); }) .create(); choiceDialog.show(); }
Example 18
Source File: DelegatingMethodHandle.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
/** Create a LF which simply reinvokes a target of the given basic type. */ static LambdaForm makeReinvokerForm(MethodHandle target, int whichCache, Object constraint, String debugString, boolean forceInline, NamedFunction getTargetFn, NamedFunction preActionFn) { MethodType mtype = target.type().basicType(); boolean customized = (whichCache < 0 || mtype.parameterSlotCount() > MethodType.MAX_MH_INVOKER_ARITY); boolean hasPreAction = (preActionFn != null); LambdaForm form; if (!customized) { form = mtype.form().cachedLambdaForm(whichCache); if (form != null) return form; } final int THIS_DMH = 0; final int ARG_BASE = 1; final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); int nameCursor = ARG_LIMIT; final int PRE_ACTION = hasPreAction ? nameCursor++ : -1; final int NEXT_MH = customized ? -1 : nameCursor++; final int REINVOKE = nameCursor++; LambdaForm.Name[] names = LambdaForm.arguments(nameCursor - ARG_LIMIT, mtype.invokerType()); assert(names.length == nameCursor); names[THIS_DMH] = names[THIS_DMH].withConstraint(constraint); Object[] targetArgs; if (hasPreAction) { names[PRE_ACTION] = new LambdaForm.Name(preActionFn, names[THIS_DMH]); } if (customized) { targetArgs = Arrays.copyOfRange(names, ARG_BASE, ARG_LIMIT, Object[].class); names[REINVOKE] = new LambdaForm.Name(target, targetArgs); // the invoker is the target itself } else { names[NEXT_MH] = new LambdaForm.Name(getTargetFn, names[THIS_DMH]); targetArgs = Arrays.copyOfRange(names, THIS_DMH, ARG_LIMIT, Object[].class); targetArgs[0] = names[NEXT_MH]; // overwrite this MH with next MH names[REINVOKE] = new LambdaForm.Name(mtype, targetArgs); } form = new LambdaForm(debugString, ARG_LIMIT, names, forceInline); if (!customized) { form = mtype.form().setCachedLambdaForm(whichCache, form); } return form; }
Example 19
Source File: TritVector.java From qupla with Apache License 2.0 | 4 votes |
public byte[] trits() { return Arrays.copyOfRange(vector.buffer, offset, offset + size()); }
Example 20
Source File: Id3Decoder.java From Telegram-FOSS with GNU General Public License v2.0 | 3 votes |
/** * Copies the specified range of an array, or returns a zero length array if the range is invalid. * * @param data The array from which to copy. * @param from The start of the range to copy (inclusive). * @param to The end of the range to copy (exclusive). * @return The copied data, or a zero length array if the range is invalid. */ private static byte[] copyOfRangeIfValid(byte[] data, int from, int to) { if (to <= from) { // Invalid or zero length range. return Util.EMPTY_BYTE_ARRAY; } return Arrays.copyOfRange(data, from, to); }