Search in sources :

Example 81 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project jaybird by FirebirdSQL.

the class Arc4EncryptionPlugin method createCipher.

private Cipher createCipher(int mode, byte[] key) throws SQLException {
    try {
        Cipher rc4Cipher = Cipher.getInstance("ARCFOUR");
        SecretKeySpec rc4Key = new SecretKeySpec(key, "ARCFOUR");
        rc4Cipher.init(mode, rc4Key);
        return rc4Cipher;
    } catch (NoSuchPaddingException | NoSuchAlgorithmException e) {
        throw new FbExceptionBuilder().nonTransientException(jb_cryptAlgorithmNotAvailable).messageParameter(getEncryptionIdentifier().toString()).cause(e).toFlatSQLException();
    } catch (InvalidKeyException e) {
        throw new FbExceptionBuilder().nonTransientException(jb_cryptInvalidKey).messageParameter(getEncryptionIdentifier().toString()).cause(e).toFlatSQLException();
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 82 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project raml-module-builder by folio-org.

the class AES method main.

public static void main(String[] args) throws Exception {
    String strDataToEncrypt = new String();
    try {
        SecretKey secretKey = generateSecretKey();
        String saveableSecretKey = convertSecretKeyToString(secretKey);
        strDataToEncrypt = "mypassword";
        System.out.println("original password " + strDataToEncrypt);
        String base64EncodedEnryptedPassword = encryptPasswordAsBase64(strDataToEncrypt, getSecretKeyObject(saveableSecretKey));
        System.out.println("Encrypted password generated using AES is " + base64EncodedEnryptedPassword);
        System.out.println("secret key as string: " + saveableSecretKey);
        String decodedPassword = decryptPassword(base64EncodedEnryptedPassword, getSecretKeyObject(saveableSecretKey));
        /* decode from the base64 string */
        System.out.println("decoded password " + decodedPassword);
    } catch (NoSuchAlgorithmException noSuchAlgo) {
        System.out.println(" No Such Algorithm exists " + noSuchAlgo);
    } catch (NoSuchPaddingException noSuchPad) {
        System.out.println(" No Such Padding exists " + noSuchPad);
    } catch (InvalidKeyException invalidKey) {
        System.out.println(" Invalid Key " + invalidKey);
    } catch (BadPaddingException badPadding) {
        System.out.println(" Bad Padding " + badPadding);
    } catch (IllegalBlockSizeException illegalBlockSize) {
        System.out.println(" Illegal Block Size " + illegalBlockSize);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException)

Example 83 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project substitution-schedule-parser by vertretungsplanme.

the class LoginHandler method handleLogin.

private String handleLogin(Executor executor, CookieStore cookieStore, boolean needsResponse) throws JSONException, IOException, CredentialInvalidException {
    if (auth == null)
        return null;
    if (!(auth instanceof UserPasswordCredential || auth instanceof PasswordCredential)) {
        throw new IllegalArgumentException("Wrong authentication type");
    }
    String login;
    String password;
    if (auth instanceof UserPasswordCredential) {
        login = ((UserPasswordCredential) auth).getUsername();
        password = ((UserPasswordCredential) auth).getPassword();
    } else {
        login = null;
        password = ((PasswordCredential) auth).getPassword();
    }
    JSONObject data = scheduleData.getData();
    JSONObject loginConfig = data.getJSONObject(LOGIN_CONFIG);
    String type = loginConfig.optString(PARAM_TYPE, "post");
    switch(type) {
        case "post":
            List<Cookie> cookieList = cookieProvider != null ? cookieProvider.getCookies(auth) : null;
            String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null);
            String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null);
            if (cookieList != null && !needsResponse && !(checkUrl == null && checkText != null)) {
                for (Cookie cookie : cookieList) cookieStore.addCookie(cookie);
                if (checkUrl != null && checkText != null) {
                    try {
                        String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
                        if (!response.contains(checkText)) {
                            return null;
                        }
                    } catch (HttpResponseException e) {
                        return null;
                    }
                } else {
                    return null;
                }
            }
            executor.clearCookies();
            Document preDoc = null;
            if (loginConfig.has(PARAM_PRE_URL)) {
                String preUrl = loginConfig.getString(PARAM_PRE_URL);
                String preHtml = executor.execute(Request.Get(preUrl)).returnContent().asString();
                preDoc = Jsoup.parse(preHtml);
            }
            String postUrl = loginConfig.getString(PARAM_URL);
            JSONObject loginData = loginConfig.getJSONObject(PARAM_DATA);
            List<NameValuePair> nvps = new ArrayList<>();
            String typo3Challenge = null;
            BigInteger typo3RsaN = null;
            BigInteger typo3RsaE = null;
            if (loginData.has("_hiddeninputs") && preDoc != null) {
                for (Element hidden : preDoc.select(loginData.getString("_hiddeninputs") + " input[type=hidden]")) {
                    if (loginData.has(hidden.attr("name")))
                        continue;
                    nvps.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value")));
                    if (hidden.attr("name").equals("challenge")) {
                        typo3Challenge = hidden.attr("value");
                    } else if (hidden.attr("name").equals("n") && hidden.attr("id").equals("rsa_n")) {
                        typo3RsaN = new BigInteger(hidden.attr("value"), 16);
                    } else if (hidden.attr("name").equals("e") && hidden.attr("id").equals("rsa_e")) {
                        typo3RsaE = new BigInteger(hidden.attr("value"), 16);
                    }
                }
            }
            for (String name : JSONObject.getNames(loginData)) {
                String value = loginData.getString(name);
                if (name.equals("_hiddeninputs"))
                    continue;
                switch(value) {
                    case "_login":
                        value = login;
                        break;
                    case "_password":
                        value = password;
                        break;
                    case "_password_md5":
                        value = DigestUtils.md5Hex(password);
                        break;
                    case "_password_md5_typo3":
                        value = DigestUtils.md5Hex(login + ":" + DigestUtils.md5Hex(password) + ":" + typo3Challenge);
                        break;
                    case "_password_rsa_typo3":
                        try {
                            final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                            if (typo3RsaE == null && typo3RsaN == null) {
                                String key = executor.execute(Request.Get(new URL(new URL(postUrl), "/index.php?eID=FrontendLoginRsaPublicKey").toString())).returnContent().asString();
                                typo3RsaN = new BigInteger(key.split(":")[0], 16);
                                typo3RsaE = new BigInteger(key.split(":")[1], 16);
                            }
                            cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(typo3RsaN, typo3RsaE)));
                            byte[] result = cipher.doFinal(password.getBytes());
                            value = "rsa:" + new Base64().encodeAsString(result);
                        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException | InvalidKeySpecException e) {
                            e.printStackTrace();
                        }
                        break;
                }
                nvps.add(new BasicNameValuePair(name, value));
            }
            Request request = Request.Post(postUrl);
            if (loginConfig.optBoolean("form-data", false)) {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                for (NameValuePair nvp : nvps) {
                    builder.addTextBody(nvp.getName(), nvp.getValue());
                }
                request.body(builder.build());
            } else {
                request.bodyForm(nvps, Charset.forName("UTF-8"));
            }
            String html = executor.execute(request).returnContent().asString();
            if (cookieProvider != null)
                cookieProvider.saveCookies(auth, cookieStore.getCookies());
            if (checkUrl != null && checkText != null) {
                try {
                    String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
                    if (response.contains(checkText))
                        throw new CredentialInvalidException();
                } catch (HttpResponseException e) {
                    throw new CredentialInvalidException();
                }
            } else if (checkText != null) {
                if (html.contains(checkText))
                    throw new CredentialInvalidException();
            }
            return html;
        case "basic":
            if (login == null)
                throw new IOException("wrong auth type");
            executor.auth(login, password);
            if (loginConfig.has(PARAM_URL)) {
                String url = loginConfig.getString(PARAM_URL);
                if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                    throw new CredentialInvalidException();
                }
            }
            break;
        case "ntlm":
            if (login == null)
                throw new IOException("wrong auth type");
            executor.auth(login, password, null, null);
            if (loginConfig.has(PARAM_URL)) {
                String url = loginConfig.getString(PARAM_URL);
                if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                    throw new CredentialInvalidException();
                }
            }
            break;
        case "fixed":
            String loginFixed = loginConfig.optString(PARAM_LOGIN, null);
            String passwordFixed = loginConfig.getString(PARAM_PASSWORD);
            if (!Objects.equals(loginFixed, login) || !Objects.equals(passwordFixed, password)) {
                throw new CredentialInvalidException();
            }
            break;
    }
    return null;
}
Also used : Base64(org.apache.commons.codec.binary.Base64) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) Element(org.jsoup.nodes.Element) PasswordCredential(me.vertretungsplan.objects.credential.PasswordCredential) UserPasswordCredential(me.vertretungsplan.objects.credential.UserPasswordCredential) ArrayList(java.util.ArrayList) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) HttpResponseException(org.apache.http.client.HttpResponseException) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) UserPasswordCredential(me.vertretungsplan.objects.credential.UserPasswordCredential) Document(org.jsoup.nodes.Document) URL(java.net.URL) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CredentialInvalidException(me.vertretungsplan.exception.CredentialInvalidException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) Cookie(org.apache.http.cookie.Cookie) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) Request(org.apache.http.client.fluent.Request) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) JSONObject(org.json.JSONObject) BigInteger(java.math.BigInteger) Cipher(javax.crypto.Cipher)

Example 84 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project braintree_android by braintree.

the class AuthorizationRequest method parseBrowserResponse.

@Override
public Result parseBrowserResponse(ContextInspector contextInspector, Uri uri) {
    String status = uri.getLastPathSegment();
    String payloadEnc = uri.getQueryParameter("payloadEnc");
    JSONObject payload;
    try {
        payload = new JSONObject(new String(Base64.decode(uri.getQueryParameter("payload"), Base64.DEFAULT)));
    } catch (NullPointerException | IllegalArgumentException | JSONException e) {
        payload = new JSONObject();
    }
    if (Uri.parse(getSuccessUrl()).getLastPathSegment().equals(status)) {
        if (!payload.has("msg_GUID")) {
            return new Result(new ResponseParsingException("Response incomplete"));
        }
        if (TextUtils.isEmpty(payloadEnc) || !isValidResponse(Json.optString(payload, "msg_GUID", ""))) {
            return new Result(new ResponseParsingException("Response invalid"));
        }
        try {
            JSONObject decryptedPayloadEnc = getDecryptedPayload(payloadEnc);
            String error = Json.optString(payload, "error", "");
            // the string 'null' is coming back in production
            if (!TextUtils.isEmpty(error) && !"null".equals(error)) {
                return new Result(new BrowserSwitchException(error));
            }
            return new Result(Json.optString(payload, "environment", ""), ResponseType.authorization_code, new JSONObject().put("code", decryptedPayloadEnc.getString("payment_code")), decryptedPayloadEnc.getString("email"));
        } catch (JSONException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException | InvalidKeyException | InvalidEncryptionDataException | IllegalArgumentException e) {
            return new Result(new ResponseParsingException(e));
        }
    } else if (Uri.parse(getCancelUrl()).getLastPathSegment().equals(status)) {
        String error = Json.optString(payload, "error", "");
        // the string 'null' is coming back in production
        if (!TextUtils.isEmpty(error) && !"null".equals(error)) {
            return new Result(new BrowserSwitchException(error));
        } else {
            return new Result();
        }
    } else {
        return new Result(new ResponseParsingException("Response uri invalid"));
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ResponseParsingException(com.paypal.android.sdk.onetouch.core.exception.ResponseParsingException) JSONException(org.json.JSONException) BrowserSwitchException(com.paypal.android.sdk.onetouch.core.exception.BrowserSwitchException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) JSONObject(org.json.JSONObject) InvalidEncryptionDataException(com.paypal.android.sdk.onetouch.core.exception.InvalidEncryptionDataException)

Example 85 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project skeleton-commons by skeleton-software-community.

the class StringEncoder method encode.

public static String encode(String plainText, String symmetricAlgorithm, byte[] key) {
    SecretKeySpec secretKey = new SecretKeySpec(key, CryptoUtils.getKeyAlgorithm(symmetricAlgorithm));
    try {
        Cipher cipher = Cipher.getInstance(symmetricAlgorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return Base64.encodeBase64URLSafeString(cipher.doFinal(plainText.getBytes()));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) {
        throw new CryptingException("Failed to encode " + plainText, e);
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) CryptingException(org.sklsft.commons.crypto.exception.CryptingException)

Aggregations

NoSuchPaddingException (javax.crypto.NoSuchPaddingException)259 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)237 InvalidKeyException (java.security.InvalidKeyException)216 Cipher (javax.crypto.Cipher)187 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)181 BadPaddingException (javax.crypto.BadPaddingException)180 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)119 SecretKeySpec (javax.crypto.spec.SecretKeySpec)91 IOException (java.io.IOException)83 IvParameterSpec (javax.crypto.spec.IvParameterSpec)66 SecretKey (javax.crypto.SecretKey)45 KeyStoreException (java.security.KeyStoreException)40 CertificateException (java.security.cert.CertificateException)40 UnrecoverableKeyException (java.security.UnrecoverableKeyException)35 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)30 UnsupportedEncodingException (java.io.UnsupportedEncodingException)27 NoSuchProviderException (java.security.NoSuchProviderException)27 GCMParameterSpec (javax.crypto.spec.GCMParameterSpec)18 FileNotFoundException (java.io.FileNotFoundException)16 SecureRandom (java.security.SecureRandom)16