Example usage for org.bouncycastle.util Arrays copyOf

List of usage examples for org.bouncycastle.util Arrays copyOf

Introduction

In this page you can find the example usage for org.bouncycastle.util Arrays copyOf.

Prototype

public static BigInteger[] copyOf(BigInteger[] original, int newLength) 

Source Link

Usage

From source file:org.sejda.sambox.pdmodel.encryption.StandardSecurityHandler.java

License:Apache License

/**
 * Check if a plaintext password is the user password.
 *
 * @param password The plaintext password.
 * @param user The u entry of the encryption dictionary.
 * @param owner The o entry of the encryption dictionary.
 * @param permissions The permissions set in the PDF.
 * @param id The document id used for encryption.
 * @param encRevision The revision of the encryption algorithm.
 * @param length The length of the encryption key.
 * @param encryptMetadata The encryption metadata
 *
 * @return true If the plaintext password is the user password.
 *
 * @throws IOException If there is an error accessing data.
 *//*from ww  w  .j  a v a  2  s .  c  o  m*/
public boolean isUserPassword(byte[] password, byte[] user, byte[] owner, int permissions, byte[] id,
        int encRevision, int length, boolean encryptMetadata) throws IOException {
    if (encRevision == 2) {
        byte[] passwordBytes = computeUserPassword(password, owner, permissions, id, encRevision, length,
                encryptMetadata);
        return Arrays.equals(user, passwordBytes);
    } else if (encRevision == 3 || encRevision == 4) {
        byte[] passwordBytes = computeUserPassword(password, owner, permissions, id, encRevision, length,
                encryptMetadata);
        // compare first 16 bytes only
        return Arrays.equals(Arrays.copyOf(user, 16), Arrays.copyOf(passwordBytes, 16));
    } else if (encRevision == 6 || encRevision == 5) {
        byte[] truncatedPassword = truncate127(password);

        byte[] uHash = new byte[32];
        byte[] uValidationSalt = new byte[8];
        System.arraycopy(user, 0, uHash, 0, 32);
        System.arraycopy(user, 32, uValidationSalt, 0, 8);

        byte[] hash;
        if (encRevision == 5) {
            hash = computeSHA256(truncatedPassword, uValidationSalt, null);
        } else {
            hash = computeHash2A(truncatedPassword, uValidationSalt, null);
        }

        return Arrays.equals(hash, uHash);
    } else {
        throw new IOException("Unknown Encryption Revision " + encRevision);
    }
}

From source file:org.spout.api.lighting.ByteArrayCuboidLightBuffer.java

License:Open Source License

public ByteArrayCuboidLightBuffer(ByteArrayCuboidLightBuffer buffer) {
    this(buffer.getManagerId(), buffer.baseX, buffer.baseY, buffer.baseZ, buffer.sizeX, buffer.sizeY,
            buffer.sizeZ, buffer.data == null ? null : Arrays.copyOf(buffer.data, buffer.data.length));
}

From source file:org.spout.api.lighting.ByteArrayCuboidLightBuffer.java

License:Open Source License

@Override
public byte[] serialize() {
    return Arrays.copyOf(data, data.length);
}

From source file:uk.ac.ebi.enaega.uploadclient.UploadClientUDT.java

@Override
public void run() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    ByteArrayOutputStream baos = null; // PGP
    MessageDigest crypt_digest = null; // PGP
    OutputStream literalOut = null, encOut = null, compressedOut = null; // PGP
    int DEFAULT_BUFFER_SIZE = 65 * 1024; // PGP
    PGPEncryptedDataGenerator encryptedDataGenerator = null; // PGP
    PGPCompressedDataGenerator compressedDataGenerator = null; // PGP
    PGPLiteralDataGenerator literalDataGenerator = null; // PGP

    if (this.pgKey != null) { // EGA: Encrypt file
        try {//w w w.j a v a 2  s.c  o m
            Security.addProvider(new BouncyCastleProvider());
            baos = new ByteArrayOutputStream(2 * DEFAULT_BUFFER_SIZE); // Write to memory!
            try {
                crypt_digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Encrypted Data Generator -- needs unlimited Security Policy
            encryptedDataGenerator = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, true,
                    new SecureRandom(), "BC");
            try {
                encryptedDataGenerator.addMethod(this.pgKey);
                encOut = encryptedDataGenerator.open(baos, new byte[DEFAULT_BUFFER_SIZE]);
            } catch (NoSuchProviderException ex) {
                Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
            } catch (PGPException ex) {
                Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Compression
            compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
            compressedOut = compressedOut = new BufferedOutputStream(compressedDataGenerator.open(encOut));

            // Literal Data Generator and Output Stream
            literalDataGenerator = new PGPLiteralDataGenerator();
            literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, fileName, new Date(),
                    new byte[DEFAULT_BUFFER_SIZE]); // 1<<16                                
        } catch (Throwable t) {
            JOptionPane.showMessageDialog(new JFrame(),
                    "Can't instantiate cipher key.\nBe sure to have JCE Unlimited Strength Security Policy installed.",
                    "Cipher Key Problem", JOptionPane.ERROR_MESSAGE);
            String[] failure = { "Cipher Issues" };
            return;
            //return failure;
        }
    }

    // Upload the stream.
    // Transfer! Start by accepting aconnection initiated by the server
    UnifiedSocket dataSocket = null;

    // Upload the stream.
    long c = 0;
    System.out.println("1 getting " + dataHost.toString() + "   " + hostPort);
    try {
        //                    dataSocket = pasvServer.getMatching( dataHost, hostPort );
        dataSocket = getSocket_timeout(); //getSocket();
        //if (dataSocket == null) dataSocket = getSocket_timeout();
        if (dataSocket == null)
            throw new ConnectException();
        System.out.println("2");

        // Skips.
        inputStream.skip(streamOffset);
        // Opens the data transfer connection.
        dataTransferOutputStream = dataSocket.getOutputStream(); // TCP or UDT - automatically

        // Listeners. Initialize to offset!
        if (listener != null) {
            listener.started();
            int large = 0, small = 0;
            large = (int) (offset / Integer.MAX_VALUE); // times the size of largest int
            small = (int) (offset % Integer.MAX_VALUE); // remainder
            for (int iu = 0; iu < large; iu++)
                listener.transferred(Integer.MAX_VALUE);
            listener.transferred(small);
        }
        long tot = 0;
        int idx = 0; // Update the table model
        if (mm != null) { // For Table Updates
            idx = mm.getCur();
            mm.setValueAt("0%", idx, 5);
            tot = mm.getSize();
        }

        String line = communication.readFTPReply().toString();
        System.out.println("Server Reply (STOR test.txt): " + line);

        // Let's do it!
        if (tp == TYPE_TEXTUAL) { // ------------------------------------- TEXT DATA ------------------
            char[] buffer = new char[SEND_AND_RECEIVE_BUFFER_SIZE];
            byte[] bbuffer = new byte[SEND_AND_RECEIVE_BUFFER_SIZE];
            int l, l_tot = 0;
            long cnt = 0, cnt_ = 0;
            long block_cnt = 0, block_cnt_pre = 0;
            long flush_point = 1048576L * 10L;
            long pre_flush_point = 1048576L * 9L;

            Reader reader = new InputStreamReader(inputStream);
            Writer writer = new OutputStreamWriter(dataTransferOutputStream, charSet);

            MessageDigest digest = null; // calculate checksum of incoming data stream
            try {
                digest = MessageDigest.getInstance("MD5"); // get the hash algorithm
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
            }

            long dt_file = System.currentTimeMillis(), dt_upd = System.currentTimeMillis(); // time before upload
            while ((l = reader.read(buffer)) != -1) { // The actual data transfer loop -------------------
                System.arraycopy(buffer, 0, bbuffer, 0, l);
                digest.update(bbuffer, 0, l); // Calculate MD5 for TCP stream

                if (this.pgKey != null) { // Cipher - write to mem buffer first, to enable MD5
                    literalOut.write(bbuffer, 0, l);
                    literalOut.flush();
                    byte[] buffer_ = baos.toByteArray();
                    crypt_digest.update(buffer_);
                    char[] buffer__ = new char[buffer_.length];
                    System.arraycopy(buffer_, l_tot, buffer__, 0, buffer_.length);
                    cnt += buffer_.length;
                    cnt_ += buffer_.length;
                    block_cnt += buffer_.length;
                    block_cnt_pre += buffer_.length;
                    writer.write(buffer__);
                    baos.reset();
                } else { // Write directly to socket
                    cnt += buffer.length;
                    cnt_ += buffer.length;
                    block_cnt += buffer.length;
                    block_cnt_pre += buffer.length;
                    writer.write(buffer, 0, l);
                }
                if ((block_cnt_pre / pre_flush_point) > 0) {
                    block_cnt_pre = 0;
                    writer.flush();
                }
                //writer.flush();

                if (listener != null) {
                    listener.transferred(l);
                    if (l > 0) { // l = bytes, dt_file = milliseconds
                        dt_upd = System.currentTimeMillis() - dt_upd;
                        double rate = (((double) (l)) / (((double) (dt_upd)))) * 1000.0; // bytes/s
                        if (rate > 0) {
                            String sd = size_display((long) (rate));
                            if (sd != null && sd.length() > 0)
                                listener.setText(size_display((long) (rate)) + "/s");
                        }
                        dt_upd = System.currentTimeMillis();
                    }
                }

                if (mm != null && tot != 0) {
                    l_tot += l;
                    double pct = (double) l_tot / (double) tot;
                    int i_pct = (int) Math.floor(pct * 100);
                    String s_pct = String.valueOf(i_pct) + "%";
                    mm.setValueAt(s_pct, idx, 5);
                }
            }

            // Get a representation of the MD5 digest (checksum)
            byte[] md5sum = digest.digest();
            result = "";
            for (int i = 0; i < md5sum.length; i++)
                result += Integer.toString((md5sum[i] & 0xff) + 0x100, 16).substring(1);

        } else if (tp == TYPE_BINARY) { // ------------------------------ BINARY DATA ---------------------
            System.out.println("Binary Transfer");
            long cnt = 0, cnt_ = 0;
            long block_cnt = 0, block_cnt_pre = 0;
            long flush_point = 1048576L * 10L;
            long pre_flush_point = 1048576L * 9L;
            int bufsze = 250 * (UDPEndPoint.DATAGRAM_SIZE - 24);
            byte[] buffer = new byte[bufsze];

            int l;
            long l_tot = 0;

            MessageDigest digest = null; // calculate checksum of incoming data stream
            try {
                digest = MessageDigest.getInstance("MD5"); // get the hash algorithm
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Actual transfer identical between TCP and UDT
            long dt_file = System.currentTimeMillis(), dt_upd = System.currentTimeMillis(); // time before upload
            CircularBuffer cb = new CircularBuffer(bufsze + (20 * (UDPEndPoint.DATAGRAM_SIZE - 24)));

            System.out.println("Actual Send Loop starts");
            while ((l = inputStream.read(buffer)) != -1) { // The actual data transfer loop -------------------
                if (this.pgKey != null) { // PGP Key present - encrypted Stream
                    literalOut.write(buffer, 0, l); // Write to mem buffer - this is the encryption
                    literalOut.flush();
                    byte[] buffer_ = baos.toByteArray(); // retrieve that buffer
                    crypt_digest.update(buffer_); // update crypto MD5
                    c += buffer_.length;
                    cb.put(buffer_); // Write into circular buffer                                                
                    baos.reset(); // empty mem buffer
                } else {
                    c += l; //buffer.length; // only what was read!
                    cb.put(Arrays.copyOf(buffer, l)); // Write into circular buffer
                }

                // Send the data in packet-sized portions from circular buffer temp structure
                while (cb.getSize() > (UDPEndPoint.DATAGRAM_SIZE - 24)) {
                    byte[] sendbuf = new byte[(UDPEndPoint.DATAGRAM_SIZE - 24)];
                    sendbuf = cb.get(sendbuf.length);

                    cnt += sendbuf.length;
                    cnt_ += sendbuf.length;
                    block_cnt += sendbuf.length;
                    block_cnt_pre += sendbuf.length;
                    dataTransferOutputStream.write(sendbuf, 0, sendbuf.length); // buffer, 0, l

                    if ((block_cnt_pre / pre_flush_point) > 0) {
                        block_cnt_pre = 0;
                        ((UDTOutputStream) dataTransferOutputStream).pre_flush();
                    }

                    if ((block_cnt / flush_point) > 0) {
                        block_cnt = 0;
                        dataTransferOutputStream.flush();
                    }
                }

                digest.update(buffer, 0, l); // Calculate plain text MD5 for TCP stream

                if (listener != null) {
                    listener.transferred(l); // Update total-progress bar
                    if (l > 0) { // l = bytes, dt_file = milliseconds
                        dt_upd = System.currentTimeMillis() - dt_upd;
                        double rate = (((double) (l)) / (((double) (dt_upd)))) * 1000.0; // bytes/s
                        if (rate > 0) {
                            String sd = size_display((long) (rate));
                            if (sd != null && sd.length() > 0)
                                listener.setText(size_display((long) (rate)) + "/s");
                        }
                        dt_upd = System.currentTimeMillis();
                    }
                }

                if (mm != null && tot != 0) { // Update in-table progress bar
                    l_tot += l;
                    double pct = (double) l_tot / (double) tot;
                    int i_pct = (int) Math.floor(pct * 100);
                    String s_pct = String.valueOf(i_pct) + "%";
                    mm.setValueAt(s_pct, idx, 5);
                }
            } // Input stream completely read ---
            if (cb.getSize() > 0) { // Flush the buffer at the end - MD5s already complete at this point
                byte[] sendbuf = new byte[cb.getSize()];
                sendbuf = cb.get(sendbuf.length);
                dataTransferOutputStream.write(sendbuf, 0, sendbuf.length);
            }

            // Get a representation of the MD5 digest (checksum) plain file
            byte[] md5sum = digest.digest();
            result = "";
            for (int i = 0; i < md5sum.length; i++)
                result += Integer.toString((md5sum[i] & 0xff) + 0x100, 16).substring(1);
        }

        // Upload loop complete. Close PGP streams, if used (produces extra data)
        if (this.pgKey != null) {
            literalOut.close();
            literalDataGenerator.close();
            // Close all other streams
            compressedOut.close();
            compressedDataGenerator.close();
            encOut.close();
            encryptedDataGenerator.close();
            byte[] buffer_ = baos.toByteArray(); // retrieve that buffer
            crypt_digest.update(buffer_); // update crypto MD5
            dataTransferOutputStream.write(buffer_); // Write cipher data to socket
            dataTransferOutputStream.flush();
            baos.close();

            // Get a representation of the MD5 digest (checksum) cipher file
            byte[] md5sum = crypt_digest.digest();
            result1 = "";
            for (int i = 0; i < md5sum.length; i++)
                result1 += Integer.toString((md5sum[i] & 0xff) + 0x100, 16).substring(1);
        }

        dataTransferOutputStream.flush();
    } catch (Throwable e) {
        if (listener != null) {
            listener.aborted();
        }
        try {
            throw new FTPDataTransferException("I/O error in data transfer", e);
        } catch (FTPDataTransferException ex) {
            Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
        }
    } finally {
        // Closing stream and data connection.
        if (dataTransferOutputStream != null) {
            try {
                dataTransferOutputStream.flush();
                dataTransferOutputStream.close();
            } catch (Throwable t) {
                ;
            }
        }
        try {
            dataSocket.close();
        } catch (Throwable t) {
            ;
        }
        // Set to null the instance-level input stream.
        dataTransferOutputStream = null;
        // Consume the result reply of the transfer.
        FTPReply readFTPReply = null;
        try {
            readFTPReply = communication.readFTPReply();
        } catch (Throwable ex) {
            Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(readFTPReply.toString());
        // Change the operation status.
    }

}

From source file:us.eharning.atomun.keygen.internal.spi.bip0032.BouncyCastleBIP0032NodeProcessor.java

License:Apache License

/**
 * Convert the Base58+checksum encoded string into a BIP0032 node.
 *
 * @param serialized//  www. j  a v  a2  s . co m
 *         encoded string to decode.
 *
 * @return BIP0032 node represented by the serialized string.
 *
 * @throws ValidationException
 *         if the data is not a valid encoded BIP0032 node.
 */
@Override
public BIP0032Node importNode(String serialized) throws ValidationException {
    byte[] data = Base58.decodeWithChecksum(serialized);
    if (data.length != 78) {
        throw new ValidationException("Invalid extended key value");
    }
    byte[] type = Arrays.copyOf(data, 4);
    boolean hasPrivate;
    if (Arrays.areEqual(type, xprv) || Arrays.areEqual(type, tprv)) {
        hasPrivate = true;
    } else if (Arrays.areEqual(type, xpub) || Arrays.areEqual(type, tpub)) {
        hasPrivate = false;
    } else {
        throw new ValidationException("Invalid magic number for an extended key");
    }
    int depth = data[4] & 0xff;
    int parent = getInt32(data, 5);
    int sequence = getInt32(data, 9);
    byte[] chainCode = Arrays.copyOfRange(data, 13, 13 + 32);
    byte[] pubOrPriv = Arrays.copyOfRange(data, 13 + 32, data.length);
    ECKey key;
    if (hasPrivate) {
        key = ECKeyFactory.getInstance().fromSecretExponent(new BigInteger(1, pubOrPriv), true);
    } else {
        key = ECKeyFactory.getInstance().fromEncodedPublicKey(pubOrPriv, true);
    }
    return new BIP0032Node(key, chainCode, depth, parent, sequence);
}

From source file:Utils.bytes.Bytes.java

public Bytes copy() {
    return new Bytes(Arrays.copyOf(bytes, bytes.length));
}

From source file:Utils.bytes.Bytes.java

public void splice(int from, int to) {
    byte[] first = Arrays.copyOf(bytes, from);
    byte[] second = Arrays.copyOfRange(bytes, to, this.bytes.length);

    this.bytes = Arrays.concatenate(first, second);
}

From source file:Utils.bytes.Bytes.java

public void trim(int length) {
    this.bytes = Arrays.copyOf(bytes, length);
}