Search in sources :

Example 76 with Cipher

use of javax.crypto.Cipher in project sling by apache.

the class TopologyRequestValidator method decrypt.

/**
     * Decrypt the body.
     *
     * @param jsonArray the encrypted payload
     * @return the decrypted payload.
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeySpecException
     * @throws InvalidAlgorithmParameterException
     * @throws JSONException
     */
private String decrypt(JsonArray jsonArray) throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, getCiperKey(Base64.decodeBase64(jsonArray.getString(0).getBytes("UTF-8"))), new IvParameterSpec(Base64.decodeBase64(jsonArray.getString(1).getBytes("UTF-8"))));
    return new String(cipher.doFinal(Base64.decodeBase64(jsonArray.getString(2).getBytes("UTF-8"))));
}
Also used : IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher)

Example 77 with Cipher

use of javax.crypto.Cipher in project robovm by robovm.

the class CipherInputStreamTest method testSkip.

public void testSkip() throws Exception {
    Cipher cipher = Cipher.getInstance("DES");
    cipher.init(Cipher.DECRYPT_MODE, key);
    InputStream in = new CipherInputStream(new ByteArrayInputStream(cipherText), cipher);
    assertTrue(in.skip(5) > 0);
}
Also used : CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Cipher(javax.crypto.Cipher)

Example 78 with Cipher

use of javax.crypto.Cipher in project robovm by robovm.

the class CipherInputStreamTest method testCipherInputStream_TruncatedInput_Failure.

public void testCipherInputStream_TruncatedInput_Failure() throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(new byte[16], "AES"), new IvParameterSpec(new byte[16]));
    InputStream is = new CipherInputStream(new ByteArrayInputStream(new byte[31]), cipher);
    is.read(new byte[4]);
    is.close();
}
Also used : CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher)

Example 79 with Cipher

use of javax.crypto.Cipher in project robovm by robovm.

the class CipherTest method testCipher_updateAAD_AfterInit_Failure.

public void testCipher_updateAAD_AfterInit_Failure() throws Exception {
    Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(new byte[128 / 8], "AES"));
    try {
        c.updateAAD((byte[]) null);
        fail("should not be able to call updateAAD with null input");
    } catch (IllegalArgumentException expected) {
    }
    try {
        c.updateAAD((ByteBuffer) null);
        fail("should not be able to call updateAAD with null input");
    } catch (IllegalArgumentException expected) {
    }
    try {
        c.updateAAD(null, 0, 8);
        fail("should not be able to call updateAAD with null input");
    } catch (IllegalArgumentException expected) {
    }
    try {
        c.updateAAD(new byte[8], -1, 7);
        fail("should not be able to call updateAAD with invalid offset");
    } catch (IllegalArgumentException expected) {
    }
    try {
        c.updateAAD(new byte[8], 0, -1);
        fail("should not be able to call updateAAD with negative length");
    } catch (IllegalArgumentException expected) {
    }
    try {
        c.updateAAD(new byte[8], 0, 8 + 1);
        fail("should not be able to call updateAAD with too large length");
    } catch (IllegalArgumentException expected) {
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) Cipher(javax.crypto.Cipher)

Example 80 with Cipher

use of javax.crypto.Cipher in project robovm by robovm.

the class ServerHandshakeImpl method unwrap.

/**
     * Proceses inbound handshake messages
     * @param bytes
     */
@Override
public void unwrap(byte[] bytes) {
    io_stream.append(bytes);
    while (io_stream.available() > 0) {
        int handshakeType;
        int length;
        io_stream.mark();
        try {
            handshakeType = io_stream.read();
            length = io_stream.readUint24();
            if (io_stream.available() < length) {
                io_stream.reset();
                return;
            }
            switch(handshakeType) {
                case // CLIENT_HELLO
                1:
                    if (clientHello != null && this.status != FINISHED) {
                        // Client hello has been received during handshake
                        unexpectedMessage();
                        return;
                    }
                    // if protocol planed to send Hello Request message
                    // - cancel this demand.
                    needSendHelloRequest = false;
                    clientHello = new ClientHello(io_stream, length);
                    if (nonBlocking) {
                        delegatedTasks.add(new DelegatedTask(new Runnable() {

                            public void run() {
                                processClientHello();
                            }
                        }, this));
                        return;
                    }
                    processClientHello();
                    break;
                case //    CLIENT CERTIFICATE
                11:
                    if (isResuming || certificateRequest == null || serverHelloDone == null || clientCert != null) {
                        unexpectedMessage();
                        return;
                    }
                    clientCert = new CertificateMessage(io_stream, length);
                    if (clientCert.certs.length == 0) {
                        if (parameters.getNeedClientAuth()) {
                            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE: no client certificate received");
                        }
                    } else {
                        String authType = clientCert.getAuthType();
                        try {
                            parameters.getTrustManager().checkClientTrusted(clientCert.certs, authType);
                        } catch (CertificateException e) {
                            fatalAlert(AlertProtocol.BAD_CERTIFICATE, "Untrusted Client Certificate ", e);
                        }
                        session.peerCertificates = clientCert.certs;
                    }
                    break;
                case // CERTIFICATE_VERIFY
                15:
                    if (isResuming || clientKeyExchange == null || clientCert == null || //client certificate
                    clientKeyExchange.isEmpty() || // parameters
                    certificateVerify != null || changeCipherSpecReceived) {
                        unexpectedMessage();
                        return;
                    }
                    certificateVerify = new CertificateVerify(io_stream, length);
                    String authType = clientCert.getAuthType();
                    DigitalSignature ds = new DigitalSignature(authType);
                    ds.init(clientCert.certs[0]);
                    byte[] md5_hash = null;
                    byte[] sha_hash = null;
                    if ("RSA".equals(authType)) {
                        md5_hash = io_stream.getDigestMD5withoutLast();
                        sha_hash = io_stream.getDigestSHAwithoutLast();
                    } else if ("DSA".equals(authType)) {
                        sha_hash = io_stream.getDigestSHAwithoutLast();
                    // The Signature should be empty in case of anonymous signature algorithm:
                    // } else if ("DH".equals(authType)) {
                    }
                    ds.setMD5(md5_hash);
                    ds.setSHA(sha_hash);
                    if (!ds.verifySignature(certificateVerify.signedHash)) {
                        fatalAlert(AlertProtocol.DECRYPT_ERROR, "DECRYPT ERROR: CERTIFICATE_VERIFY incorrect signature");
                    }
                    break;
                case // CLIENT_KEY_EXCHANGE
                16:
                    if (isResuming || serverHelloDone == null || clientKeyExchange != null || (clientCert == null && parameters.getNeedClientAuth())) {
                        unexpectedMessage();
                        return;
                    }
                    if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
                        clientKeyExchange = new ClientKeyExchange(io_stream, length, serverHello.server_version[1] == 1, true);
                        Cipher c = null;
                        try {
                            c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                            c.init(Cipher.UNWRAP_MODE, privKey);
                            preMasterSecret = c.unwrap(clientKeyExchange.exchange_keys, "preMasterSecret", Cipher.SECRET_KEY).getEncoded();
                            // check preMasterSecret:
                            if (preMasterSecret.length != 48 || preMasterSecret[0] != clientHello.client_version[0] || preMasterSecret[1] != clientHello.client_version[1]) {
                                // incorrect preMasterSecret
                                // prevent an attack (see TLS 1.0 spec., 7.4.7.1.)
                                preMasterSecret = new byte[48];
                                parameters.getSecureRandom().nextBytes(preMasterSecret);
                            }
                        } catch (Exception e) {
                            fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
                        }
                    } else {
                        // diffie hellman key exchange
                        clientKeyExchange = new ClientKeyExchange(io_stream, length, serverHello.server_version[1] == 1, false);
                        if (clientKeyExchange.isEmpty()) {
                            // TODO check that client cert. DH params
                            // matched server cert. DH params
                            // client cert. contains fixed DH parameters
                            preMasterSecret = ((DHPublicKey) clientCert.certs[0].getPublicKey()).getY().toByteArray();
                        } else {
                            try {
                                KeyFactory kf = KeyFactory.getInstance("DH");
                                KeyAgreement agreement = KeyAgreement.getInstance("DH");
                                PublicKey clientPublic = kf.generatePublic(new DHPublicKeySpec(new BigInteger(1, clientKeyExchange.exchange_keys), serverKeyExchange.par1, serverKeyExchange.par2));
                                agreement.init(privKey);
                                agreement.doPhase(clientPublic, true);
                                preMasterSecret = agreement.generateSecret();
                            } catch (Exception e) {
                                fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
                                return;
                            }
                        }
                    }
                    computerMasterSecret();
                    break;
                case // FINISHED
                20:
                    if (!isResuming && !changeCipherSpecReceived) {
                        unexpectedMessage();
                        return;
                    }
                    clientFinished = new Finished(io_stream, length);
                    verifyFinished(clientFinished.getData());
                    session.context = parameters.getServerSessionContext();
                    parameters.getServerSessionContext().putSession(session);
                    if (!isResuming) {
                        sendChangeCipherSpec();
                    } else {
                        session.lastAccessedTime = System.currentTimeMillis();
                        status = FINISHED;
                    }
                    break;
                default:
                    unexpectedMessage();
                    return;
            }
        } catch (IOException e) {
            // io stream dosn't contain complete handshake message
            io_stream.reset();
            return;
        }
    }
}
Also used : DHPublicKey(javax.crypto.interfaces.DHPublicKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BigInteger(java.math.BigInteger) Cipher(javax.crypto.Cipher) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec) KeyAgreement(javax.crypto.KeyAgreement) KeyFactory(java.security.KeyFactory)

Aggregations

Cipher (javax.crypto.Cipher)1531 SecretKeySpec (javax.crypto.spec.SecretKeySpec)516 SecretKey (javax.crypto.SecretKey)377 IvParameterSpec (javax.crypto.spec.IvParameterSpec)368 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)349 InvalidKeyException (java.security.InvalidKeyException)257 IOException (java.io.IOException)202 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)202 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)196 BadPaddingException (javax.crypto.BadPaddingException)183 GeneralSecurityException (java.security.GeneralSecurityException)161 SecretKeyFactory (javax.crypto.SecretKeyFactory)149 Key (java.security.Key)148 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)134 SecureRandom (java.security.SecureRandom)105 PrivateKey (java.security.PrivateKey)93 PublicKey (java.security.PublicKey)86 UnsupportedEncodingException (java.io.UnsupportedEncodingException)84 PBEKeySpec (javax.crypto.spec.PBEKeySpec)82 KeyGenerator (javax.crypto.KeyGenerator)78