Java Examples for javax.crypto.SealedObject

The following java examples will help you to understand the usage of javax.crypto.SealedObject. These source code samples are taken from different open source projects.

Example 1
Project: JBossAS51-master  File: SRPRemoteServer.java View source code
public byte[] verify(String username, byte[] M1, Object auxChallenge, int sessionID) throws SecurityException, RemoteException {
    SRPSessionKey key = new SRPSessionKey(username, sessionID);
    boolean trace = log.isTraceEnabled();
    if (trace)
        log.trace("verify, " + key);
    SRPServerSession session = (SRPServerSession) sessionMap.get(key);
    if (session == null)
        throw new SecurityException("Failed to find active session for username: " + username);
    if (session.verify(M1) == false)
        throw new SecurityException("Failed to verify M1");
    /* If there is a auxChallenge have the verierStore verify the data
      */
    if (auxChallenge != null) {
        // See if this is an encrypted object
        if (auxChallenge instanceof SealedObject) {
            if (trace)
                log.trace("Decrypting sealed object");
            SRPParameters params = session.getParameters();
            Object challenge = null;
            try {
                byte[] skey = session.getSessionKey();
                Object tmpKey = CryptoUtil.createSecretKey(params.cipherAlgorithm, skey);
                challenge = CryptoUtil.accessSealedObject(params.cipherAlgorithm, tmpKey, params.cipherIV, auxChallenge);
            } catch (GeneralSecurityException e) {
                throw new RemoteException("Failed to access SealedObject", e);
            }
            auxChallenge = challenge;
        }
        if (trace)
            log.trace("Verifing aux challenge");
        this.verifierStore.verifyUserChallenge(username, auxChallenge);
    } else if (requireAuxChallenge == true) {
        throw new RemoteException("A non-null auxChallenge is required for verification");
    }
    // Inform the listener the user has been validated
    if (listener != null)
        listener.verifiedUser(key, session);
    if (trace)
        log.trace("verify, completed " + key);
    return session.getServerResponse();
}
Example 2
Project: JBossAS_5_1_EDG-master  File: SRPRemoteServer.java View source code
public byte[] verify(String username, byte[] M1, Object auxChallenge, int sessionID) throws SecurityException, RemoteException {
    SRPSessionKey key = new SRPSessionKey(username, sessionID);
    boolean trace = log.isTraceEnabled();
    if (trace)
        log.trace("verify, " + key);
    SRPServerSession session = (SRPServerSession) sessionMap.get(key);
    if (session == null)
        throw new SecurityException("Failed to find active session for username: " + username);
    if (session.verify(M1) == false)
        throw new SecurityException("Failed to verify M1");
    /* If there is a auxChallenge have the verierStore verify the data
      */
    if (auxChallenge != null) {
        // See if this is an encrypted object
        if (auxChallenge instanceof SealedObject) {
            if (trace)
                log.trace("Decrypting sealed object");
            SRPParameters params = session.getParameters();
            Object challenge = null;
            try {
                byte[] skey = session.getSessionKey();
                Object tmpKey = CryptoUtil.createSecretKey(params.cipherAlgorithm, skey);
                challenge = CryptoUtil.accessSealedObject(params.cipherAlgorithm, tmpKey, params.cipherIV, auxChallenge);
            } catch (GeneralSecurityException e) {
                throw new RemoteException("Failed to access SealedObject", e);
            }
            auxChallenge = challenge;
        }
        if (trace)
            log.trace("Verifing aux challenge");
        this.verifierStore.verifyUserChallenge(username, auxChallenge);
    } else if (requireAuxChallenge == true) {
        throw new RemoteException("A non-null auxChallenge is required for verification");
    }
    // Inform the listener the user has been validated
    if (listener != null)
        listener.verifiedUser(key, session);
    if (trace)
        log.trace("verify, completed " + key);
    return session.getServerResponse();
}
Example 3
Project: atlas-lb-master  File: SealedTest.java View source code
public TestResult perform() {
    try {
        KeyGenerator keyGen = KeyGenerator.getInstance("DES", provider);
        Key key = keyGen.generateKey();
        Cipher c = Cipher.getInstance("DES/ECB/PKCS5Padding", provider);
        c.init(Cipher.ENCRYPT_MODE, key);
        String object = "Hello world";
        SealedObject so = new SealedObject(object, c);
        c.init(Cipher.DECRYPT_MODE, key);
        Object o = so.getObject(c);
        if (!o.equals(object)) {
            return new SimpleTestResult(false, "Result object 1 not equal" + "orig: " + object + " res: " + o);
        }
        o = so.getObject(key);
        if (!o.equals(object)) {
            return new SimpleTestResult(false, "Result object 2 not equal" + "orig: " + object + " res: " + o);
        }
        o = so.getObject(key, provider);
        if (!o.equals(object)) {
            return new SimpleTestResult(false, "Result object 3 not equal" + "orig: " + object + " res: " + o);
        }
        return new SimpleTestResult(true, getName() + ": Okay");
    } catch (Exception e) {
        return new SimpleTestResult(false, getName() + ": failed excpetion - " + e.toString(), e);
    }
}
Example 4
Project: bc-java-master  File: ECIESTest.java View source code
private void sealedObjectTest() throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECIES");
    kpg.initialize(new ECGenParameterSpec("secp256r1"));
    KeyPair keyPair = kpg.generateKeyPair();
    Cipher cipher = Cipher.getInstance("ECIES");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
    String toEncrypt = "Hello";
    // Check that cipher works ok
    cipher.doFinal(toEncrypt.getBytes());
    // Using a SealedObject to encrypt the same string fails with a NullPointerException
    SealedObject sealedObject = new SealedObject(toEncrypt, cipher);
    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
    String result = (String) sealedObject.getObject(cipher);
    isTrue("result wrong", result.equals(toEncrypt));
    result = (String) sealedObject.getObject(keyPair.getPrivate());
    isTrue("result wrong", result.equals(toEncrypt));
}
Example 5
Project: irma_future_id-master  File: SealedTest.java View source code
public TestResult perform() {
    try {
        KeyGenerator keyGen = KeyGenerator.getInstance("DES", provider);
        Key key = keyGen.generateKey();
        Cipher c = Cipher.getInstance("DES/ECB/PKCS5Padding", provider);
        c.init(Cipher.ENCRYPT_MODE, key);
        String object = "Hello world";
        SealedObject so = new SealedObject(object, c);
        c.init(Cipher.DECRYPT_MODE, key);
        Object o = so.getObject(c);
        if (!o.equals(object)) {
            return new SimpleTestResult(false, "Result object 1 not equal" + "orig: " + object + " res: " + o);
        }
        o = so.getObject(key);
        if (!o.equals(object)) {
            return new SimpleTestResult(false, "Result object 2 not equal" + "orig: " + object + " res: " + o);
        }
        o = so.getObject(key, provider);
        if (!o.equals(object)) {
            return new SimpleTestResult(false, "Result object 3 not equal" + "orig: " + object + " res: " + o);
        }
        return new SimpleTestResult(true, getName() + ": Okay");
    } catch (Exception e) {
        return new SimpleTestResult(false, getName() + ": failed excpetion - " + e.toString(), e);
    }
}
Example 6
Project: JDEECo-master  File: KnowledgeEncryptorTest.java View source code
@Test
public void encryptValueSet_NoSecurityTest() throws KnowledgeNotFoundException {
    // given no security is used
    // when encryptValueSet() is called
    List<KnowledgeData> result = target.encryptValueSet(valueSet, localKnowledgeManager, metaData);
    // then data are not encrypted and not modified
    assertEquals(1, result.size());
    assertEquals(metaData, result.get(0).getMetaData());
    assertEquals(valueSet, result.get(0).getKnowledge());
    assertEquals(4, result.get(0).getAuthors().getKnowledgePaths().size());
    assertEquals("author_secured", result.get(0).getAuthors().getValue(RuntimeModelHelper.createKnowledgePath("secured")));
    assertNull(result.get(0).getAuthors().getValue(RuntimeModelHelper.createKnowledgePath("secured2")));
    for (KnowledgePath kp : result.get(0).getKnowledge().getKnowledgePaths()) {
        assertFalse(result.get(0).getKnowledge().getValue(kp) instanceof SealedObject);
    }
    for (KnowledgePath kp : result.get(0).getSecuritySet().getKnowledgePaths()) {
        assertFalse(result.get(0).getSecuritySet().getValue(kp) instanceof SealedObject);
    }
    assertNull(result.get(0).getMetaData().encryptedKey);
}
Example 7
Project: susurrus-android-app-master  File: Crypto.java View source code
/**
     * Encrypts an unencrypted serializable Object with AES.
     *
     * At first an AES-Session-Key is generated for encrypting the handed SealedObject. The AES-
     * Session-Key is wrapped with the user's publicKey. The wrapped-key can be used to decrypt
     * the SealedObject later.
     *
     * @param _unencryptedObj Serializable object.
     * @param _publicKey The user's publicKey.
     * @return An EncryptionModel with SealedObject and wrapped-Key.
     */
public static EncryptionModel encryptBytes(Serializable _unencryptedObj, PublicKey _publicKey) {
    // generate a random AES-key for encrypting the object's data
    SecretKey aesSessionKey;
    try {
        // generate key
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        SecureRandom randomNumbers = new SecureRandom();
        generator.init(256, randomNumbers);
        aesSessionKey = generator.generateKey();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
    // initiate the encryption cipher
    Cipher cipher;
    byte[] wrappedKey;
    try {
        // get a cipher object that implements the RSA transformation
        cipher = Cipher.getInstance(CRYPTO_ALGO);
        // initialize cipher with the public key. Use WRAP_MODE for wrapping the encrypted
        // AES-data with the handed public key.
        cipher.init(Cipher.WRAP_MODE, _publicKey);
        // wrap AES-key
        wrappedKey = cipher.wrap(aesSessionKey);
        // get a new cipher and use the wrapped AES-key for encryption
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, aesSessionKey);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        return null;
    } catch (InvalidKeyException e) {
        e.printStackTrace();
        return null;
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
        return null;
    }
    // use the cipher for encryption
    SealedObject encryptedObj;
    try {
        // creates a new SealedObject instance wrapping the specified object and sealing it
        // using the specified cipher.
        encryptedObj = new SealedObject(_unencryptedObj, cipher);
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
        return null;
    } catch (NullPointerException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return new EncryptionModel(encryptedObj, wrappedKey);
}
Example 8
Project: jdk7u-jdk-master  File: JceKeyStore.java View source code
/**
     * Loads the keystore from the given input stream.
     *
     * <p>If a password is given, it is used to check the integrity of the
     * keystore data. Otherwise, the integrity of the keystore is not checked.
     *
     * @param stream the input stream from which the keystore is loaded
     * @param password the (optional) password used to check the integrity of
     * the keystore.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data
     * @exception NoSuchAlgorithmException if the algorithm used to check
     * the integrity of the keystore cannot be found
     * @exception CertificateException if any of the certificates in the
     * keystore could not be loaded
     */
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    synchronized (entries) {
        DataInputStream dis;
        MessageDigest md = null;
        CertificateFactory cf = null;
        Hashtable cfs = null;
        ByteArrayInputStream bais = null;
        byte[] encoded = null;
        if (stream == null)
            return;
        if (password != null) {
            md = getPreKeyedHash(password);
            dis = new DataInputStream(new DigestInputStream(stream, md));
        } else {
            dis = new DataInputStream(stream);
        }
        // NOTE: don't pass dis to ois at this point or it'll fail to load
        // the keystore!!!
        ObjectInputStream ois = null;
        try {
            // Body format: see store method
            int xMagic = dis.readInt();
            int xVersion = dis.readInt();
            //   versions 1 and 2
            if (((xMagic != JCEKS_MAGIC) && (xMagic != JKS_MAGIC)) || ((xVersion != VERSION_1) && (xVersion != VERSION_2))) {
                throw new IOException("Invalid keystore format");
            }
            if (xVersion == VERSION_1) {
                cf = CertificateFactory.getInstance("X509");
            } else {
                // version 2
                cfs = new Hashtable(3);
            }
            entries.clear();
            int count = dis.readInt();
            for (int i = 0; i < count; i++) {
                int tag;
                String alias;
                tag = dis.readInt();
                if (tag == 1) {
                    // private-key entry
                    PrivateKeyEntry entry = new PrivateKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the private key
                    try {
                        entry.protectedKey = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Keysize too big");
                    }
                    dis.readFully(entry.protectedKey);
                    // read the certificate chain
                    int numOfCerts = dis.readInt();
                    try {
                        if (numOfCerts > 0) {
                            entry.chain = new Certificate[numOfCerts];
                        }
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Too many certificates in " + "chain");
                    }
                    for (int j = 0; j < numOfCerts; j++) {
                        if (xVersion == 2) {
                            // read the certificate type, and instantiate a
                            // certificate factory of that type (reuse
                            // existing factory if possible)
                            String certType = dis.readUTF();
                            if (cfs.containsKey(certType)) {
                                // reuse certificate factory
                                cf = (CertificateFactory) cfs.get(certType);
                            } else {
                                // create new certificate factory
                                cf = CertificateFactory.getInstance(certType);
                                // store the certificate factory so we can
                                // reuse it later
                                cfs.put(certType, cf);
                            }
                        }
                        // instantiate the certificate
                        try {
                            encoded = new byte[dis.readInt()];
                        } catch (OutOfMemoryError e) {
                            throw new IOException("Certificate too big");
                        }
                        dis.readFully(encoded);
                        bais = new ByteArrayInputStream(encoded);
                        entry.chain[j] = cf.generateCertificate(bais);
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 2) {
                    // trusted certificate entry
                    TrustedCertEntry entry = new TrustedCertEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the trusted certificate
                    if (xVersion == 2) {
                        // read the certificate type, and instantiate a
                        // certificate factory of that type (reuse
                        // existing factory if possible)
                        String certType = dis.readUTF();
                        if (cfs.containsKey(certType)) {
                            // reuse certificate factory
                            cf = (CertificateFactory) cfs.get(certType);
                        } else {
                            // create new certificate factory
                            cf = CertificateFactory.getInstance(certType);
                            // store the certificate factory so we can
                            // reuse it later
                            cfs.put(certType, cf);
                        }
                    }
                    try {
                        encoded = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Certificate too big");
                    }
                    dis.readFully(encoded);
                    bais = new ByteArrayInputStream(encoded);
                    entry.cert = cf.generateCertificate(bais);
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 3) {
                    // secret-key entry
                    SecretKeyEntry entry = new SecretKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the sealed key
                    try {
                        ois = new ObjectInputStream(dis);
                        entry.sealedKey = (SealedObject) ois.readObject();
                    // NOTE: don't close ois here since we are still
                    // using dis!!!
                    } catch (ClassNotFoundException cnfe) {
                        throw new IOException(cnfe.getMessage());
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else {
                    throw new IOException("Unrecognized keystore entry");
                }
            }
            /*
                 * If a password has been provided, we check the keyed digest
                 * at the end. If this check fails, the store has been tampered
                 * with
                 */
            if (password != null) {
                byte computed[], actual[];
                computed = md.digest();
                actual = new byte[computed.length];
                dis.readFully(actual);
                for (int i = 0; i < computed.length; i++) {
                    if (computed[i] != actual[i]) {
                        throw new IOException("Keystore was tampered with, or " + "password was incorrect");
                    }
                }
            }
        } finally {
            if (ois != null) {
                ois.close();
            } else {
                dis.close();
            }
        }
    }
}
Example 9
Project: ManagedRuntimeInitiative-master  File: JceKeyStore.java View source code
/**
     * Loads the keystore from the given input stream.
     *
     * <p>If a password is given, it is used to check the integrity of the
     * keystore data. Otherwise, the integrity of the keystore is not checked.
     *
     * @param stream the input stream from which the keystore is loaded
     * @param password the (optional) password used to check the integrity of
     * the keystore.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data
     * @exception NoSuchAlgorithmException if the algorithm used to check
     * the integrity of the keystore cannot be found
     * @exception CertificateException if any of the certificates in the
     * keystore could not be loaded
     */
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    synchronized (entries) {
        DataInputStream dis;
        MessageDigest md = null;
        CertificateFactory cf = null;
        Hashtable cfs = null;
        ByteArrayInputStream bais = null;
        byte[] encoded = null;
        if (stream == null)
            return;
        if (password != null) {
            md = getPreKeyedHash(password);
            dis = new DataInputStream(new DigestInputStream(stream, md));
        } else {
            dis = new DataInputStream(stream);
        }
        // NOTE: don't pass dis to ois at this point or it'll fail to load
        // the keystore!!!
        ObjectInputStream ois = null;
        try {
            // Body format: see store method
            int xMagic = dis.readInt();
            int xVersion = dis.readInt();
            //   versions 1 and 2
            if (((xMagic != JCEKS_MAGIC) && (xMagic != JKS_MAGIC)) || ((xVersion != VERSION_1) && (xVersion != VERSION_2))) {
                throw new IOException("Invalid keystore format");
            }
            if (xVersion == VERSION_1) {
                cf = CertificateFactory.getInstance("X509");
            } else {
                // version 2
                cfs = new Hashtable(3);
            }
            entries.clear();
            int count = dis.readInt();
            for (int i = 0; i < count; i++) {
                int tag;
                String alias;
                tag = dis.readInt();
                if (tag == 1) {
                    // private-key entry
                    PrivateKeyEntry entry = new PrivateKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the private key
                    try {
                        entry.protectedKey = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Keysize too big");
                    }
                    dis.readFully(entry.protectedKey);
                    // read the certificate chain
                    int numOfCerts = dis.readInt();
                    try {
                        if (numOfCerts > 0) {
                            entry.chain = new Certificate[numOfCerts];
                        }
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Too many certificates in " + "chain");
                    }
                    for (int j = 0; j < numOfCerts; j++) {
                        if (xVersion == 2) {
                            // read the certificate type, and instantiate a
                            // certificate factory of that type (reuse
                            // existing factory if possible)
                            String certType = dis.readUTF();
                            if (cfs.containsKey(certType)) {
                                // reuse certificate factory
                                cf = (CertificateFactory) cfs.get(certType);
                            } else {
                                // create new certificate factory
                                cf = CertificateFactory.getInstance(certType);
                                // store the certificate factory so we can
                                // reuse it later
                                cfs.put(certType, cf);
                            }
                        }
                        // instantiate the certificate
                        try {
                            encoded = new byte[dis.readInt()];
                        } catch (OutOfMemoryError e) {
                            throw new IOException("Certificate too big");
                        }
                        dis.readFully(encoded);
                        bais = new ByteArrayInputStream(encoded);
                        entry.chain[j] = cf.generateCertificate(bais);
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 2) {
                    // trusted certificate entry
                    TrustedCertEntry entry = new TrustedCertEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the trusted certificate
                    if (xVersion == 2) {
                        // read the certificate type, and instantiate a
                        // certificate factory of that type (reuse
                        // existing factory if possible)
                        String certType = dis.readUTF();
                        if (cfs.containsKey(certType)) {
                            // reuse certificate factory
                            cf = (CertificateFactory) cfs.get(certType);
                        } else {
                            // create new certificate factory
                            cf = CertificateFactory.getInstance(certType);
                            // store the certificate factory so we can
                            // reuse it later
                            cfs.put(certType, cf);
                        }
                    }
                    try {
                        encoded = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Certificate too big");
                    }
                    dis.readFully(encoded);
                    bais = new ByteArrayInputStream(encoded);
                    entry.cert = cf.generateCertificate(bais);
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 3) {
                    // secret-key entry
                    SecretKeyEntry entry = new SecretKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the sealed key
                    try {
                        ois = new ObjectInputStream(dis);
                        entry.sealedKey = (SealedObject) ois.readObject();
                    // NOTE: don't close ois here since we are still
                    // using dis!!!
                    } catch (ClassNotFoundException cnfe) {
                        throw new IOException(cnfe.getMessage());
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else {
                    throw new IOException("Unrecognized keystore entry");
                }
            }
            /*
                 * If a password has been provided, we check the keyed digest
                 * at the end. If this check fails, the store has been tampered
                 * with
                 */
            if (password != null) {
                byte computed[], actual[];
                computed = md.digest();
                actual = new byte[computed.length];
                dis.readFully(actual);
                for (int i = 0; i < computed.length; i++) {
                    if (computed[i] != actual[i]) {
                        throw new IOException("Keystore was tampered with, or " + "password was incorrect");
                    }
                }
            }
        } finally {
            if (ois != null) {
                ois.close();
            } else {
                dis.close();
            }
        }
    }
}
Example 10
Project: openjdk-master  File: JceKeyStore.java View source code
/**
     * Loads the keystore from the given input stream.
     *
     * <p>If a password is given, it is used to check the integrity of the
     * keystore data. Otherwise, the integrity of the keystore is not checked.
     *
     * @param stream the input stream from which the keystore is loaded
     * @param password the (optional) password used to check the integrity of
     * the keystore.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data
     * @exception NoSuchAlgorithmException if the algorithm used to check
     * the integrity of the keystore cannot be found
     * @exception CertificateException if any of the certificates in the
     * keystore could not be loaded
     */
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    synchronized (entries) {
        DataInputStream dis;
        MessageDigest md = null;
        CertificateFactory cf = null;
        Hashtable<String, CertificateFactory> cfs = null;
        ByteArrayInputStream bais = null;
        byte[] encoded = null;
        if (stream == null)
            return;
        if (password != null) {
            md = getPreKeyedHash(password);
            dis = new DataInputStream(new DigestInputStream(stream, md));
        } else {
            dis = new DataInputStream(stream);
        }
        // NOTE: don't pass dis to ois at this point or it'll fail to load
        // the keystore!!!
        ObjectInputStream ois = null;
        try {
            // Body format: see store method
            int xMagic = dis.readInt();
            int xVersion = dis.readInt();
            //   versions 1 and 2
            if (((xMagic != JCEKS_MAGIC) && (xMagic != JKS_MAGIC)) || ((xVersion != VERSION_1) && (xVersion != VERSION_2))) {
                throw new IOException("Invalid keystore format");
            }
            if (xVersion == VERSION_1) {
                cf = CertificateFactory.getInstance("X509");
            } else {
                // version 2
                cfs = new Hashtable<>(3);
            }
            entries.clear();
            int count = dis.readInt();
            for (int i = 0; i < count; i++) {
                int tag;
                String alias;
                tag = dis.readInt();
                if (tag == 1) {
                    // private-key entry
                    PrivateKeyEntry entry = new PrivateKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the private key
                    try {
                        entry.protectedKey = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Keysize too big");
                    }
                    dis.readFully(entry.protectedKey);
                    // read the certificate chain
                    int numOfCerts = dis.readInt();
                    try {
                        if (numOfCerts > 0) {
                            entry.chain = new Certificate[numOfCerts];
                        }
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Too many certificates in " + "chain");
                    }
                    for (int j = 0; j < numOfCerts; j++) {
                        if (xVersion == 2) {
                            // read the certificate type, and instantiate a
                            // certificate factory of that type (reuse
                            // existing factory if possible)
                            String certType = dis.readUTF();
                            if (cfs.containsKey(certType)) {
                                // reuse certificate factory
                                cf = cfs.get(certType);
                            } else {
                                // create new certificate factory
                                cf = CertificateFactory.getInstance(certType);
                                // store the certificate factory so we can
                                // reuse it later
                                cfs.put(certType, cf);
                            }
                        }
                        // instantiate the certificate
                        try {
                            encoded = new byte[dis.readInt()];
                        } catch (OutOfMemoryError e) {
                            throw new IOException("Certificate too big");
                        }
                        dis.readFully(encoded);
                        bais = new ByteArrayInputStream(encoded);
                        entry.chain[j] = cf.generateCertificate(bais);
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 2) {
                    // trusted certificate entry
                    TrustedCertEntry entry = new TrustedCertEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the trusted certificate
                    if (xVersion == 2) {
                        // read the certificate type, and instantiate a
                        // certificate factory of that type (reuse
                        // existing factory if possible)
                        String certType = dis.readUTF();
                        if (cfs.containsKey(certType)) {
                            // reuse certificate factory
                            cf = cfs.get(certType);
                        } else {
                            // create new certificate factory
                            cf = CertificateFactory.getInstance(certType);
                            // store the certificate factory so we can
                            // reuse it later
                            cfs.put(certType, cf);
                        }
                    }
                    try {
                        encoded = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Certificate too big");
                    }
                    dis.readFully(encoded);
                    bais = new ByteArrayInputStream(encoded);
                    entry.cert = cf.generateCertificate(bais);
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 3) {
                    // secret-key entry
                    SecretKeyEntry entry = new SecretKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the sealed key
                    try {
                        ois = new ObjectInputStream(dis);
                        entry.sealedKey = (SealedObject) ois.readObject();
                    // NOTE: don't close ois here since we are still
                    // using dis!!!
                    } catch (ClassNotFoundException cnfe) {
                        throw new IOException(cnfe.getMessage());
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else {
                    throw new IOException("Unrecognized keystore entry");
                }
            }
            /*
                 * If a password has been provided, we check the keyed digest
                 * at the end. If this check fails, the store has been tampered
                 * with
                 */
            if (password != null) {
                byte computed[], actual[];
                computed = md.digest();
                actual = new byte[computed.length];
                dis.readFully(actual);
                for (int i = 0; i < computed.length; i++) {
                    if (computed[i] != actual[i]) {
                        throw new IOException("Keystore was tampered with, or " + "password was incorrect", new UnrecoverableKeyException("Password verification failed"));
                    }
                }
            }
        } finally {
            if (ois != null) {
                ois.close();
            } else {
                dis.close();
            }
        }
    }
}
Example 11
Project: openjdk8-jdk-master  File: JceKeyStore.java View source code
/**
     * Loads the keystore from the given input stream.
     *
     * <p>If a password is given, it is used to check the integrity of the
     * keystore data. Otherwise, the integrity of the keystore is not checked.
     *
     * @param stream the input stream from which the keystore is loaded
     * @param password the (optional) password used to check the integrity of
     * the keystore.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data
     * @exception NoSuchAlgorithmException if the algorithm used to check
     * the integrity of the keystore cannot be found
     * @exception CertificateException if any of the certificates in the
     * keystore could not be loaded
     */
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    synchronized (entries) {
        DataInputStream dis;
        MessageDigest md = null;
        CertificateFactory cf = null;
        Hashtable<String, CertificateFactory> cfs = null;
        ByteArrayInputStream bais = null;
        byte[] encoded = null;
        if (stream == null)
            return;
        if (password != null) {
            md = getPreKeyedHash(password);
            dis = new DataInputStream(new DigestInputStream(stream, md));
        } else {
            dis = new DataInputStream(stream);
        }
        // NOTE: don't pass dis to ois at this point or it'll fail to load
        // the keystore!!!
        ObjectInputStream ois = null;
        try {
            // Body format: see store method
            int xMagic = dis.readInt();
            int xVersion = dis.readInt();
            //   versions 1 and 2
            if (((xMagic != JCEKS_MAGIC) && (xMagic != JKS_MAGIC)) || ((xVersion != VERSION_1) && (xVersion != VERSION_2))) {
                throw new IOException("Invalid keystore format");
            }
            if (xVersion == VERSION_1) {
                cf = CertificateFactory.getInstance("X509");
            } else {
                // version 2
                cfs = new Hashtable<String, CertificateFactory>(3);
            }
            entries.clear();
            int count = dis.readInt();
            for (int i = 0; i < count; i++) {
                int tag;
                String alias;
                tag = dis.readInt();
                if (tag == 1) {
                    // private-key entry
                    PrivateKeyEntry entry = new PrivateKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the private key
                    try {
                        entry.protectedKey = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Keysize too big");
                    }
                    dis.readFully(entry.protectedKey);
                    // read the certificate chain
                    int numOfCerts = dis.readInt();
                    try {
                        if (numOfCerts > 0) {
                            entry.chain = new Certificate[numOfCerts];
                        }
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Too many certificates in " + "chain");
                    }
                    for (int j = 0; j < numOfCerts; j++) {
                        if (xVersion == 2) {
                            // read the certificate type, and instantiate a
                            // certificate factory of that type (reuse
                            // existing factory if possible)
                            String certType = dis.readUTF();
                            if (cfs.containsKey(certType)) {
                                // reuse certificate factory
                                cf = cfs.get(certType);
                            } else {
                                // create new certificate factory
                                cf = CertificateFactory.getInstance(certType);
                                // store the certificate factory so we can
                                // reuse it later
                                cfs.put(certType, cf);
                            }
                        }
                        // instantiate the certificate
                        try {
                            encoded = new byte[dis.readInt()];
                        } catch (OutOfMemoryError e) {
                            throw new IOException("Certificate too big");
                        }
                        dis.readFully(encoded);
                        bais = new ByteArrayInputStream(encoded);
                        entry.chain[j] = cf.generateCertificate(bais);
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 2) {
                    // trusted certificate entry
                    TrustedCertEntry entry = new TrustedCertEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the trusted certificate
                    if (xVersion == 2) {
                        // read the certificate type, and instantiate a
                        // certificate factory of that type (reuse
                        // existing factory if possible)
                        String certType = dis.readUTF();
                        if (cfs.containsKey(certType)) {
                            // reuse certificate factory
                            cf = cfs.get(certType);
                        } else {
                            // create new certificate factory
                            cf = CertificateFactory.getInstance(certType);
                            // store the certificate factory so we can
                            // reuse it later
                            cfs.put(certType, cf);
                        }
                    }
                    try {
                        encoded = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Certificate too big");
                    }
                    dis.readFully(encoded);
                    bais = new ByteArrayInputStream(encoded);
                    entry.cert = cf.generateCertificate(bais);
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 3) {
                    // secret-key entry
                    SecretKeyEntry entry = new SecretKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the sealed key
                    try {
                        ois = new ObjectInputStream(dis);
                        entry.sealedKey = (SealedObject) ois.readObject();
                    // NOTE: don't close ois here since we are still
                    // using dis!!!
                    } catch (ClassNotFoundException cnfe) {
                        throw new IOException(cnfe.getMessage());
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else {
                    throw new IOException("Unrecognized keystore entry");
                }
            }
            /*
                 * If a password has been provided, we check the keyed digest
                 * at the end. If this check fails, the store has been tampered
                 * with
                 */
            if (password != null) {
                byte computed[], actual[];
                computed = md.digest();
                actual = new byte[computed.length];
                dis.readFully(actual);
                for (int i = 0; i < computed.length; i++) {
                    if (computed[i] != actual[i]) {
                        throw new IOException("Keystore was tampered with, or " + "password was incorrect");
                    }
                }
            }
        } finally {
            if (ois != null) {
                ois.close();
            } else {
                dis.close();
            }
        }
    }
}
Example 12
Project: chvote-1-0-master  File: BallotDecryptionController.java View source code
@Override
protected List<EncryptedBallotAndWrappedKey> call() throws Exception {
    // Need to create the stream here, so it'll be available to the executor thread
    try (InputStream encBallotsInputStream = Files.newInputStream(encryptedBallotsFile.toPath(), StandardOpenOption.READ)) {
        return (List<EncryptedBallotAndWrappedKey>) SafeObjectReader.safeReadObject(ArrayList.class, Arrays.asList(EncryptedBallotAndWrappedKey.class, SealedObject.class), maxObjects, maxBytes, encBallotsInputStream);
    }
}
Example 13
Project: geronimo-master  File: SimpleEncryption.java View source code
/**
     * Gets a String which contains the Base64-encoded form of the source,
     * encrypted with the known key.
     */
public static String encrypt(Serializable source) {
    try {
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.ENCRYPT_MODE, SECRET_KEY);
        SealedObject so = new SealedObject(source, c);
        ByteArrayOutputStream store = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(store);
        out.writeObject(so);
        out.close();
        byte[] data = store.toByteArray();
        byte[] textData = Base64.encode(data);
        return new String(textData, "US-ASCII");
    } catch (Exception e) {
        log.error("Unable to encrypt", e);
        return null;
    }
}
Example 14
Project: JamVM-PH-master  File: SessionImpl.java View source code
public void prepare(char[] passwd) throws SSLException {
    try {
        privateDataSalt = new byte[32];
        random.nextBytes(privateDataSalt);
        GnuPBEKey key = new GnuPBEKey(passwd, privateDataSalt, 1000);
        Cipher cipher = Cipher.getInstance("PBEWithHMacSHA256AndAES/OFB/PKCS7Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        sealedPrivateData = new SealedObject(privateData, cipher);
    } catch (IllegalBlockSizeException ibse) {
        throw new SSLException(ibse);
    } catch (InvalidKeyException ike) {
        throw new SSLException(ike);
    } catch (IOException ioe) {
        throw new SSLException(ioe);
    } catch (NoSuchAlgorithmException nsae) {
        throw new SSLException(nsae);
    } catch (NoSuchPaddingException nspe) {
        throw new SSLException(nspe);
    }
}
Example 15
Project: jftp-master  File: FavoritesManager.java View source code
/**
	 * Returns the list of favourite FTP sites. The list is generated by reading
	 * the serialized file, <code>FAV_FILE</code>.
	 * 
	 * @return List of favourite FTP sites.
	 * @exception IOException
	 *                if an IO error occurs while reading the file
	 * @exception ClassNotFoundException
	 *                We should never get this exception. If we get this, it
	 *                means that the software is not installed correctly.
	 */
public static List getFavorites() throws IOException, ClassNotFoundException, IllegalBlockSizeException, BadPaddingException {
    List favorites = new ArrayList();
    FileInputStream fin = null;
    ObjectInputStream in = null;
    try {
        checkFavFile();
        fin = new FileInputStream(FAV_FILE);
        if (fin.available() > 0) {
            in = new ObjectInputStream(fin);
            Object obj = in.readObject();
            if (obj instanceof List) {
                favorites = (List) obj;
                saveFavorites(favorites);
            } else {
                SealedObject so = (SealedObject) obj;
                favorites = (List) so.getObject(getCipher(Cipher.DECRYPT_MODE));
            }
        }
        return favorites;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException exp) {
        }
        try {
            if (fin != null) {
                fin.close();
            }
        } catch (IOException exp) {
        }
        in = null;
        fin = null;
    }
}
Example 16
Project: Offline3fAuth-master  File: ObjCrypter.java View source code
/** Encrypts the Serializable object with AES
     * @param plaintext the Serializable object to encrypt
     * @param password the password to use for encryption, if it's null or empty the default pass will be used instead
     * @return an encrypter String formatted as json containing the used cipher and the encrypted object
     */
public static String encryptAES(Serializable plaintext, String password) {
    try {
        final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
        final PBEKeySpec pbeKeySpec = new PBEKeySpec((password == null || password.equalsIgnoreCase("")) ? defaultPass : password.toCharArray());
        final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(AES_ALG);
        final SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
        final Cipher cipher = Cipher.getInstance(AES_ALG);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParamSpec);
        return gson.toJson(new SealedObject(plaintext, cipher));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 17
Project: picketbox-master  File: CryptoUtil.java View source code
public static Object createSealedObject(String cipherAlgorithm, Object key, byte[] cipherIV, Serializable data) throws GeneralSecurityException {
    Object sealedObject = null;
    try {
        javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(cipherAlgorithm);
        javax.crypto.SecretKey skey = (javax.crypto.SecretKey) key;
        if (cipherIV != null) {
            javax.crypto.spec.IvParameterSpec iv = new javax.crypto.spec.IvParameterSpec(cipherIV);
            cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, skey, iv);
        } else {
            cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, skey);
        }
        sealedObject = new javax.crypto.SealedObject(data, cipher);
    } catch (GeneralSecurityException e) {
        throw e;
    } catch (Throwable e) {
        throw PicketBoxMessages.MESSAGES.failedToCreateSealedObject(e);
    }
    return sealedObject;
}
Example 18
Project: android_libcore-master  File: SealedObjectTest.java View source code
/**
     * readObject(ObjectInputStream s) method testing. Tests if the
     * serialization/deserialization works correctly: object is serialized,
     * deserialized, the content od deserialized object equals to the content of
     * initial object.
     */
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "!Serialization", args = {})
public void testReadObject() throws Exception {
    String secret = "secret string";
    SealedObject so = new SealedObject(secret, new NullCipher());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(so);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    SealedObject so_des = (SealedObject) ois.readObject();
    assertEquals("The secret content of deserialized object " + "should be equal to the secret content of initial object", secret, so_des.getObject(new NullCipher()));
    assertEquals("The value returned by getAlgorithm() method of " + "deserialized object should be equal to the value returned " + "by getAlgorithm() method of initial object", so.getAlgorithm(), so_des.getAlgorithm());
}
Example 19
Project: open-mika-master  File: SealedObjectTest.java View source code
/**
     * readObject(ObjectInputStream s) method testing. Tests if the
     * serialization/deserialization works correctly: object is serialized,
     * deserialized, the content od deserialized object equals to the content of
     * initial object.
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "!Serialization",
        args = {}
    )
     */
public void testReadObject() throws Exception {
    String secret = "secret string";
    SealedObject so = new SealedObject(secret, new NullCipher());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(so);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    SealedObject so_des = (SealedObject) ois.readObject();
    assertEquals("The secret content of deserialized object " + "should be equal to the secret content of initial object", secret, so_des.getObject(new NullCipher()));
    assertEquals("The value returned by getAlgorithm() method of " + "deserialized object should be equal to the value returned " + "by getAlgorithm() method of initial object", so.getAlgorithm(), so_des.getAlgorithm());
}
Example 20
Project: classlib6-master  File: JceKeyStore.java View source code
/**
     * Loads the keystore from the given input stream.
     *
     * <p>If a password is given, it is used to check the integrity of the
     * keystore data. Otherwise, the integrity of the keystore is not checked.
     *
     * @param stream the input stream from which the keystore is loaded
     * @param password the (optional) password used to check the integrity of
     * the keystore.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data
     * @exception NoSuchAlgorithmException if the algorithm used to check
     * the integrity of the keystore cannot be found
     * @exception CertificateException if any of the certificates in the
     * keystore could not be loaded
     */
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    synchronized (entries) {
        DataInputStream dis;
        MessageDigest md = null;
        CertificateFactory cf = null;
        Hashtable cfs = null;
        ByteArrayInputStream bais = null;
        byte[] encoded = null;
        if (stream == null)
            return;
        if (password != null) {
            md = getPreKeyedHash(password);
            dis = new DataInputStream(new DigestInputStream(stream, md));
        } else {
            dis = new DataInputStream(stream);
        }
        // NOTE: don't pass dis to ois at this point or it'll fail to load
        // the keystore!!!
        ObjectInputStream ois = null;
        try {
            // Body format: see store method
            int xMagic = dis.readInt();
            int xVersion = dis.readInt();
            //   versions 1 and 2
            if (((xMagic != JCEKS_MAGIC) && (xMagic != JKS_MAGIC)) || ((xVersion != VERSION_1) && (xVersion != VERSION_2))) {
                throw new IOException("Invalid keystore format");
            }
            if (xVersion == VERSION_1) {
                cf = CertificateFactory.getInstance("X509");
            } else {
                // version 2
                cfs = new Hashtable(3);
            }
            entries.clear();
            int count = dis.readInt();
            for (int i = 0; i < count; i++) {
                int tag;
                String alias;
                tag = dis.readInt();
                if (tag == 1) {
                    // private-key entry
                    PrivateKeyEntry entry = new PrivateKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the private key
                    try {
                        entry.protectedKey = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Keysize too big");
                    }
                    dis.readFully(entry.protectedKey);
                    // read the certificate chain
                    int numOfCerts = dis.readInt();
                    try {
                        if (numOfCerts > 0) {
                            entry.chain = new Certificate[numOfCerts];
                        }
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Too many certificates in " + "chain");
                    }
                    for (int j = 0; j < numOfCerts; j++) {
                        if (xVersion == 2) {
                            // read the certificate type, and instantiate a
                            // certificate factory of that type (reuse
                            // existing factory if possible)
                            String certType = dis.readUTF();
                            if (cfs.containsKey(certType)) {
                                // reuse certificate factory
                                cf = (CertificateFactory) cfs.get(certType);
                            } else {
                                // create new certificate factory
                                cf = CertificateFactory.getInstance(certType);
                                // store the certificate factory so we can
                                // reuse it later
                                cfs.put(certType, cf);
                            }
                        }
                        // instantiate the certificate
                        try {
                            encoded = new byte[dis.readInt()];
                        } catch (OutOfMemoryError e) {
                            throw new IOException("Certificate too big");
                        }
                        dis.readFully(encoded);
                        bais = new ByteArrayInputStream(encoded);
                        entry.chain[j] = cf.generateCertificate(bais);
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 2) {
                    // trusted certificate entry
                    TrustedCertEntry entry = new TrustedCertEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the trusted certificate
                    if (xVersion == 2) {
                        // read the certificate type, and instantiate a
                        // certificate factory of that type (reuse
                        // existing factory if possible)
                        String certType = dis.readUTF();
                        if (cfs.containsKey(certType)) {
                            // reuse certificate factory
                            cf = (CertificateFactory) cfs.get(certType);
                        } else {
                            // create new certificate factory
                            cf = CertificateFactory.getInstance(certType);
                            // store the certificate factory so we can
                            // reuse it later
                            cfs.put(certType, cf);
                        }
                    }
                    try {
                        encoded = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Certificate too big");
                    }
                    dis.readFully(encoded);
                    bais = new ByteArrayInputStream(encoded);
                    entry.cert = cf.generateCertificate(bais);
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 3) {
                    // secret-key entry
                    SecretKeyEntry entry = new SecretKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the sealed key
                    try {
                        ois = new ObjectInputStream(dis);
                        entry.sealedKey = (SealedObject) ois.readObject();
                    // NOTE: don't close ois here since we are still
                    // using dis!!!
                    } catch (ClassNotFoundException cnfe) {
                        throw new IOException(cnfe.getMessage());
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else {
                    throw new IOException("Unrecognized keystore entry");
                }
            }
            /*
                 * If a password has been provided, we check the keyed digest
                 * at the end. If this check fails, the store has been tampered
                 * with
                 */
            if (password != null) {
                byte computed[], actual[];
                computed = md.digest();
                actual = new byte[computed.length];
                dis.readFully(actual);
                for (int i = 0; i < computed.length; i++) {
                    if (computed[i] != actual[i]) {
                        throw new IOException("Keystore was tampered with, or " + "password was incorrect");
                    }
                }
            }
        } finally {
            if (ois != null) {
                ois.close();
            } else {
                dis.close();
            }
        }
    }
}
Example 21
Project: ikvm-openjdk-master  File: JceKeyStore.java View source code
/**
     * Loads the keystore from the given input stream.
     *
     * <p>If a password is given, it is used to check the integrity of the
     * keystore data. Otherwise, the integrity of the keystore is not checked.
     *
     * @param stream the input stream from which the keystore is loaded
     * @param password the (optional) password used to check the integrity of
     * the keystore.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data
     * @exception NoSuchAlgorithmException if the algorithm used to check
     * the integrity of the keystore cannot be found
     * @exception CertificateException if any of the certificates in the
     * keystore could not be loaded
     */
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    synchronized (entries) {
        DataInputStream dis;
        MessageDigest md = null;
        CertificateFactory cf = null;
        Hashtable cfs = null;
        ByteArrayInputStream bais = null;
        byte[] encoded = null;
        if (stream == null)
            return;
        if (password != null) {
            md = getPreKeyedHash(password);
            dis = new DataInputStream(new DigestInputStream(stream, md));
        } else {
            dis = new DataInputStream(stream);
        }
        // NOTE: don't pass dis to ois at this point or it'll fail to load
        // the keystore!!!
        ObjectInputStream ois = null;
        try {
            // Body format: see store method
            int xMagic = dis.readInt();
            int xVersion = dis.readInt();
            //   versions 1 and 2
            if (((xMagic != JCEKS_MAGIC) && (xMagic != JKS_MAGIC)) || ((xVersion != VERSION_1) && (xVersion != VERSION_2))) {
                throw new IOException("Invalid keystore format");
            }
            if (xVersion == VERSION_1) {
                cf = CertificateFactory.getInstance("X509");
            } else {
                // version 2
                cfs = new Hashtable(3);
            }
            entries.clear();
            int count = dis.readInt();
            for (int i = 0; i < count; i++) {
                int tag;
                String alias;
                tag = dis.readInt();
                if (tag == 1) {
                    // private-key entry
                    PrivateKeyEntry entry = new PrivateKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the private key
                    try {
                        entry.protectedKey = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Keysize too big");
                    }
                    dis.readFully(entry.protectedKey);
                    // read the certificate chain
                    int numOfCerts = dis.readInt();
                    try {
                        if (numOfCerts > 0) {
                            entry.chain = new Certificate[numOfCerts];
                        }
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Too many certificates in " + "chain");
                    }
                    for (int j = 0; j < numOfCerts; j++) {
                        if (xVersion == 2) {
                            // read the certificate type, and instantiate a
                            // certificate factory of that type (reuse
                            // existing factory if possible)
                            String certType = dis.readUTF();
                            if (cfs.containsKey(certType)) {
                                // reuse certificate factory
                                cf = (CertificateFactory) cfs.get(certType);
                            } else {
                                // create new certificate factory
                                cf = CertificateFactory.getInstance(certType);
                                // store the certificate factory so we can
                                // reuse it later
                                cfs.put(certType, cf);
                            }
                        }
                        // instantiate the certificate
                        try {
                            encoded = new byte[dis.readInt()];
                        } catch (OutOfMemoryError e) {
                            throw new IOException("Certificate too big");
                        }
                        dis.readFully(encoded);
                        bais = new ByteArrayInputStream(encoded);
                        entry.chain[j] = cf.generateCertificate(bais);
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 2) {
                    // trusted certificate entry
                    TrustedCertEntry entry = new TrustedCertEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the trusted certificate
                    if (xVersion == 2) {
                        // read the certificate type, and instantiate a
                        // certificate factory of that type (reuse
                        // existing factory if possible)
                        String certType = dis.readUTF();
                        if (cfs.containsKey(certType)) {
                            // reuse certificate factory
                            cf = (CertificateFactory) cfs.get(certType);
                        } else {
                            // create new certificate factory
                            cf = CertificateFactory.getInstance(certType);
                            // store the certificate factory so we can
                            // reuse it later
                            cfs.put(certType, cf);
                        }
                    }
                    try {
                        encoded = new byte[dis.readInt()];
                    } catch (OutOfMemoryError e) {
                        throw new IOException("Certificate too big");
                    }
                    dis.readFully(encoded);
                    bais = new ByteArrayInputStream(encoded);
                    entry.cert = cf.generateCertificate(bais);
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else if (tag == 3) {
                    // secret-key entry
                    SecretKeyEntry entry = new SecretKeyEntry();
                    // read the alias
                    alias = dis.readUTF();
                    // read the (entry creation) date
                    entry.date = new Date(dis.readLong());
                    // read the sealed key
                    try {
                        ois = new ObjectInputStream(dis);
                        entry.sealedKey = (SealedObject) ois.readObject();
                    // NOTE: don't close ois here since we are still
                    // using dis!!!
                    } catch (ClassNotFoundException cnfe) {
                        throw new IOException(cnfe.getMessage());
                    }
                    // Add the entry to the list
                    entries.put(alias, entry);
                } else {
                    throw new IOException("Unrecognized keystore entry");
                }
            }
            /*
                 * If a password has been provided, we check the keyed digest
                 * at the end. If this check fails, the store has been tampered
                 * with
                 */
            if (password != null) {
                byte computed[], actual[];
                computed = md.digest();
                actual = new byte[computed.length];
                dis.readFully(actual);
                for (int i = 0; i < computed.length; i++) {
                    if (computed[i] != actual[i]) {
                        throw new IOException("Keystore was tampered with, or " + "password was incorrect");
                    }
                }
            }
        } finally {
            if (ois != null) {
                ois.close();
            } else {
                dis.close();
            }
        }
    }
}
Example 22
Project: CoursesPortlet-master  File: SecureRequestCredentials.java View source code
/**
     * @return The password, will fail if attempting this on an object deserialized from another server.
     */
public char[] getPassword() {
    final Cipher cipher = getCipher(username, Cipher.DECRYPT_MODE);
    try {
        return (char[]) this.sealedPassword.getObject(cipher);
    } catch (IllegalBlockSizeException e) {
        throw new Error("Failed to decrypt SealedObject. " + SecureRequestCredentials.class.getSimpleName() + " will not work", e);
    } catch (BadPaddingException e) {
        throw new Error("Failed to decrypt SealedObject. " + SecureRequestCredentials.class.getSimpleName() + " will not work", e);
    } catch (IOException e) {
        throw new Error("Failed to decrypt SealedObject. " + SecureRequestCredentials.class.getSimpleName() + " will not work", e);
    } catch (ClassNotFoundException e) {
        throw new Error("Failed to decrypt SealedObject. " + SecureRequestCredentials.class.getSimpleName() + " will not work", e);
    }
}
Example 23
Project: android-15-master  File: SealedObjectTest.java View source code
/**
     * readObject(ObjectInputStream s) method testing. Tests if the
     * serialization/deserialization works correctly: object is serialized,
     * deserialized, the content od deserialized object equals to the content of
     * initial object.
     */
public void testReadObject() throws Exception {
    String secret = "secret string";
    SealedObject so = new SealedObject(secret, new NullCipher());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(so);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    SealedObject so_des = (SealedObject) ois.readObject();
    assertEquals("The secret content of deserialized object " + "should be equal to the secret content of initial object", secret, so_des.getObject(new NullCipher()));
    assertEquals("The value returned by getAlgorithm() method of " + "deserialized object should be equal to the value returned " + "by getAlgorithm() method of initial object", so.getAlgorithm(), so_des.getAlgorithm());
}
Example 24
Project: android-libcore64-master  File: SealedObjectTest.java View source code
/**
     * readObject(ObjectInputStream s) method testing. Tests if the
     * serialization/deserialization works correctly: object is serialized,
     * deserialized, the content od deserialized object equals to the content of
     * initial object.
     */
public void testReadObject() throws Exception {
    String secret = "secret string";
    SealedObject so = new SealedObject(secret, new NullCipher());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(so);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    SealedObject so_des = (SealedObject) ois.readObject();
    assertEquals("The secret content of deserialized object " + "should be equal to the secret content of initial object", secret, so_des.getObject(new NullCipher()));
    assertEquals("The value returned by getAlgorithm() method of " + "deserialized object should be equal to the value returned " + "by getAlgorithm() method of initial object", so.getAlgorithm(), so_des.getAlgorithm());
}
Example 25
Project: android-sdk-sources-for-api-level-23-master  File: SealedObjectTest.java View source code
/**
     * readObject(ObjectInputStream s) method testing. Tests if the
     * serialization/deserialization works correctly: object is serialized,
     * deserialized, the content od deserialized object equals to the content of
     * initial object.
     */
public void testReadObject() throws Exception {
    String secret = "secret string";
    SealedObject so = new SealedObject(secret, new NullCipher());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(so);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    SealedObject so_des = (SealedObject) ois.readObject();
    assertEquals("The secret content of deserialized object " + "should be equal to the secret content of initial object", secret, so_des.getObject(new NullCipher()));
    assertEquals("The value returned by getAlgorithm() method of " + "deserialized object should be equal to the value returned " + "by getAlgorithm() method of initial object", so.getAlgorithm(), so_des.getAlgorithm());
}
Example 26
Project: android_platform_libcore-master  File: SealedObjectTest.java View source code
/**
     * readObject(ObjectInputStream s) method testing. Tests if the
     * serialization/deserialization works correctly: object is serialized,
     * deserialized, the content od deserialized object equals to the content of
     * initial object.
     */
public void testReadObject() throws Exception {
    String secret = "secret string";
    SealedObject so = new SealedObject(secret, new NullCipher());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(so);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    SealedObject so_des = (SealedObject) ois.readObject();
    assertEquals("The secret content of deserialized object " + "should be equal to the secret content of initial object", secret, so_des.getObject(new NullCipher()));
    assertEquals("The value returned by getAlgorithm() method of " + "deserialized object should be equal to the value returned " + "by getAlgorithm() method of initial object", so.getAlgorithm(), so_des.getAlgorithm());
}
Example 27
Project: ARTPart-master  File: SealedObjectTest.java View source code
/**
     * readObject(ObjectInputStream s) method testing. Tests if the
     * serialization/deserialization works correctly: object is serialized,
     * deserialized, the content od deserialized object equals to the content of
     * initial object.
     */
public void testReadObject() throws Exception {
    String secret = "secret string";
    SealedObject so = new SealedObject(secret, new NullCipher());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(so);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    SealedObject so_des = (SealedObject) ois.readObject();
    assertEquals("The secret content of deserialized object " + "should be equal to the secret content of initial object", secret, so_des.getObject(new NullCipher()));
    assertEquals("The value returned by getAlgorithm() method of " + "deserialized object should be equal to the value returned " + "by getAlgorithm() method of initial object", so.getAlgorithm(), so_des.getAlgorithm());
}
Example 28
Project: ISAcreator-master  File: UserProfileManager.java View source code
public static void saveUserProfiles() {
    //.sup extension -> secure user profiles
    String userProfileLocation = ISAcreatorProperties.getProperty("isacreator.userProfileLocation");
    System.out.println("User profile location: " + userProfileLocation);
    File f = new File(userProfileLocation.equals("") ? USER_PROFILE_FILENAME : userProfileLocation + File.separator + USER_PROFILE_FILENAME);
    log.info("Saving user profile to: " + f.getAbsolutePath());
    EncryptedObject eo = new EncryptedObject();
    try {
        eo.generateKey("eamonniscool");
        // we convert to an ArrayList since this is Serializable, but a Generic List is not!
        updateUserProfileInformation(getCurrentUser());
        SealedObject so = eo.encryptObject((ArrayList) getUserProfiles());
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
        oos.writeObject(so);
        oos.close();
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        log.error(e.getMessage());
    } catch (IllegalBlockSizeException e) {
        log.error(e.getMessage());
    } catch (InvalidKeyException e) {
        log.error(e.getMessage());
    } catch (InvalidKeySpecException e) {
        log.error(e.getMessage());
    } catch (NoSuchPaddingException e) {
        log.error(e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 29
Project: property-db-master  File: SealedObjectTest.java View source code
/**
     * readObject(ObjectInputStream s) method testing. Tests if the
     * serialization/deserialization works correctly: object is serialized,
     * deserialized, the content od deserialized object equals to the content of
     * initial object.
     */
public void testReadObject() throws Exception {
    String secret = "secret string";
    SealedObject so = new SealedObject(secret, new NullCipher());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(so);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    SealedObject so_des = (SealedObject) ois.readObject();
    assertEquals("The secret content of deserialized object " + "should be equal to the secret content of initial object", secret, so_des.getObject(new NullCipher()));
    assertEquals("The value returned by getAlgorithm() method of " + "deserialized object should be equal to the value returned " + "by getAlgorithm() method of initial object", so.getAlgorithm(), so_des.getAlgorithm());
}
Example 30
Project: robovm-master  File: SealedObjectTest.java View source code
/**
     * readObject(ObjectInputStream s) method testing. Tests if the
     * serialization/deserialization works correctly: object is serialized,
     * deserialized, the content od deserialized object equals to the content of
     * initial object.
     */
public void testReadObject() throws Exception {
    String secret = "secret string";
    SealedObject so = new SealedObject(secret, new NullCipher());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(so);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
    SealedObject so_des = (SealedObject) ois.readObject();
    assertEquals("The secret content of deserialized object " + "should be equal to the secret content of initial object", secret, so_des.getObject(new NullCipher()));
    assertEquals("The value returned by getAlgorithm() method of " + "deserialized object should be equal to the value returned " + "by getAlgorithm() method of initial object", so.getAlgorithm(), so_des.getAlgorithm());
}
Example 31
Project: teiid-designer-master  File: BasicCryptor.java View source code
public synchronized Object unsealObject(Object object) throws CryptoException {
    if (useSealedObject) {
        if (!(object instanceof SealedObject)) {
            return object;
        }
        SealedObject so = (SealedObject) object;
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            if (cl != classLoader) {
                Thread.currentThread().setContextClassLoader(BasicCryptor.class.getClassLoader());
            }
            return so.getObject(decryptCipher);
        } catch (Exception e) {
            try {
                initDecryptCipher();
            } catch (CryptoException err) {
            }
            throw new CryptoException(Messages.gs(Messages.TEIID.TEIID10006, e.getClass().getName(), e.getMessage()));
        } finally {
            Thread.currentThread().setContextClassLoader(cl);
        }
    }
    if (!(object instanceof byte[])) {
        return object;
    }
    byte[] bytes = (byte[]) object;
    bytes = decrypt(bytes);
    try {
        ObjectInputStream ois = new ObjectInputStreamWithClassloader(new ByteArrayInputStream(bytes), classLoader);
        return ois.readObject();
    } catch (Exception e) {
        throw new CryptoException(Messages.gs(Messages.TEIID.TEIID10006, e.getClass().getName(), e.getMessage()));
    }
}
Example 32
Project: teiid-master  File: BasicCryptor.java View source code
public synchronized Object unsealObject(Object object) throws CryptoException {
    if (useSealedObject) {
        if (!(object instanceof SealedObject)) {
            return object;
        }
        SealedObject so = (SealedObject) object;
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            if (cl != classLoader) {
                Thread.currentThread().setContextClassLoader(BasicCryptor.class.getClassLoader());
            }
            return so.getObject(decryptCipher);
        } catch (Exception e) {
            try {
                initDecryptCipher();
            } catch (CryptoException err) {
            }
            throw new CryptoException(CorePlugin.Event.TEIID10006, CorePlugin.Util.gs(CorePlugin.Event.TEIID10006, e.getClass().getName(), e.getMessage()));
        } finally {
            Thread.currentThread().setContextClassLoader(cl);
        }
    }
    if (!(object instanceof byte[])) {
        return object;
    }
    byte[] bytes = (byte[]) object;
    bytes = decrypt(bytes);
    try {
        ObjectInputStream ois = new ObjectInputStreamWithClassloader(new ByteArrayInputStream(bytes), classLoader);
        return ois.readObject();
    } catch (Exception e) {
        throw new CryptoException(CorePlugin.Event.TEIID10006, CorePlugin.Util.gs(CorePlugin.Event.TEIID10006, e.getClass().getName(), e.getMessage()));
    }
}
Example 33
Project: ranger-master  File: RangerKeyStore.java View source code
private SealedObject sealKey(Key key, char[] password) throws Exception {
    // Create SecretKey
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndTripleDES");
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
    pbeKeySpec.clearPassword();
    // Generate random bytes + set up the PBEParameterSpec
    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[8];
    random.nextBytes(salt);
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);
    // Seal the Key
    Cipher cipher = Cipher.getInstance("PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeSpec);
    return new RangerSealedObject(key, cipher);
}