Example usage for java.security InvalidKeyException InvalidKeyException

List of usage examples for java.security InvalidKeyException InvalidKeyException

Introduction

In this page you can find the example usage for java.security InvalidKeyException InvalidKeyException.

Prototype

public InvalidKeyException(Throwable cause) 

Source Link

Document

Creates an InvalidKeyException with the specified cause and a detail message of (cause==null ?

Usage

From source file:Main.java

@Deprecated
public static Cipher createCipher(int mode, String key) throws InvalidKeyException {
    throw new InvalidKeyException("This method is deprecated");
}

From source file:Main.java

/**
 *  @param bi non-negative/*from  w w w. j a v a  2 s  . c om*/
 *  @return array of exactly len bytes
 */
public static byte[] rectify(BigInteger bi, int len) throws InvalidKeyException {
    byte[] b = bi.toByteArray();
    if (b.length == len) {
        // just right
        return b;
    }
    if (b.length > len + 1)
        throw new InvalidKeyException("key too big (" + b.length + ") max is " + (len + 1));
    byte[] rv = new byte[len];
    if (b.length == 0)
        return rv;
    if ((b[0] & 0x80) != 0)
        throw new InvalidKeyException("negative");
    if (b.length > len) {
        // leading 0 byte
        if (b[0] != 0)
            throw new InvalidKeyException("key too big (" + b.length + ") max is " + len);
        System.arraycopy(b, 1, rv, 0, len);
    } else {
        // smaller
        System.arraycopy(b, 0, rv, len - b.length, b.length);
    }
    return rv;
}

From source file:org.cryptomator.crypto.aes256.AesSivCipherUtil.java

static byte[] sivEncrypt(byte[] aesKey, byte[] macKey, byte[] plaintext, byte[]... additionalData)
        throws InvalidKeyException {
    if (aesKey.length != 16 && aesKey.length != 24 && aesKey.length != 32) {
        throw new InvalidKeyException("Invalid aesKey length " + aesKey.length);
    }//w  ww .j av a 2  s. c  om

    final byte[] iv = s2v(macKey, plaintext, additionalData);

    final int numBlocks = (plaintext.length + 15) / 16;

    // clear out the 31st and 63rd (rightmost) bit:
    final byte[] ctr = Arrays.copyOf(iv, 16);
    ctr[8] = (byte) (ctr[8] & 0x7F);
    ctr[12] = (byte) (ctr[12] & 0x7F);
    final ByteBuffer ctrBuf = ByteBuffer.wrap(ctr);
    final long initialCtrVal = ctrBuf.getLong(8);

    final byte[] x = new byte[numBlocks * 16];
    final BlockCipher aes = new AESFastEngine();
    aes.init(true, new KeyParameter(aesKey));
    for (int i = 0; i < numBlocks; i++) {
        final long ctrVal = initialCtrVal + i;
        ctrBuf.putLong(8, ctrVal);
        aes.processBlock(ctrBuf.array(), 0, x, i * 16);
        aes.reset();
    }

    final byte[] ciphertext = xor(plaintext, x);

    return ArrayUtils.addAll(iv, ciphertext);
}

From source file:com.github.woki.payments.adyen.action.CSEUtil.java

static String encrypt(final Cipher aesCipher, final Cipher rsaCipher, final String plainText)
        throws BadPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, InvalidKeyException {
    SecretKey aesKey = aesKey(256);
    byte[] iv = iv(CSE_RANDOM, 12);
    aesCipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));
    byte[] encrypted = aesCipher.doFinal(plainText.getBytes());

    byte[] result = new byte[iv.length + encrypted.length];
    System.arraycopy(iv, 0, result, 0, iv.length);
    System.arraycopy(encrypted, 0, result, iv.length, encrypted.length);

    byte[] encryptedAESKey;
    try {/*w  ww  .j a  va  2s. com*/
        encryptedAESKey = rsaCipher.doFinal(aesKey.getEncoded());
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new InvalidKeyException(e.getMessage());
    }
    return String.format("%s%s%s%s%s%s", CSE_PREFIX, CSE_VERSION, CSE_SEPARATOR,
            Base64.encodeBase64String(encryptedAESKey), CSE_SEPARATOR, Base64.encodeBase64String(result));
}

From source file:nl.minvenj.pef.pseudo.IPPseudonymizer.java

private IPPseudonymizer(final String key, final int mask, final int bitCount) throws InvalidKeyException {
    try {//from  w w w  . ja va2 s. com
        _encrypter = new FFX(Hex.decodeHex(key.toCharArray()), RADIX);
    } catch (final DecoderException e) {
        throw new InvalidKeyException(key);
    }
    _bitCount = bitCount;
    _mask = mask;
    _changeBitCount = bitCount - mask;
}

From source file:com.github.woki.payments.adyen.action.CSEUtil.java

public static Cipher rsaCipher(final String cseKeyText) throws NoSuchPaddingException, NoSuchAlgorithmException,
        InvalidKeyException, InvalidKeySpecException, IllegalArgumentException {
    String[] cseKeyParts = cseKeyText.split("\\|");
    if (cseKeyParts.length != 2) {
        throw new InvalidKeyException("Invalid CSE Key: " + cseKeyText);
    }// w  w w.  j av a2 s .c o m
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    BigInteger keyComponent1, keyComponent2;
    try {
        keyComponent1 = new BigInteger(cseKeyParts[1].toLowerCase(Locale.getDefault()), 16);
        keyComponent2 = new BigInteger(cseKeyParts[0].toLowerCase(Locale.getDefault()), 16);
    } catch (NumberFormatException e) {
        throw new InvalidKeyException("Invalid CSE Key: " + cseKeyText);
    }
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(keyComponent1, keyComponent2);
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Cipher result = Cipher.getInstance("RSA/None/PKCS1Padding");
    result.init(Cipher.ENCRYPT_MODE, pubKey);
    return result;
}

From source file:org.seedstack.seed.crypto.internal.PasswordLookupTest.java

/**
 * Test method for {@link org.seedstack.seed.crypto.internal.PasswordLookup#lookup(java.lang.String)}.
 * //from  w ww.jav  a2 s  .  com
 * @throws Exception if an error occurred
 */
@Test(expected = RuntimeException.class)
public void testLookupStringWithInvalidKey(@Mocked final AbstractConfiguration configuration,
        @Mocked final EncryptionService service) throws Exception {
    final String toDecrypt = "essai crypting";
    final String cryptingString = DatatypeConverter.printHexBinary(toDecrypt.getBytes());

    new Expectations() {
        {
            service.decrypt(DatatypeConverter.parseHexBinary(cryptingString));
            result = new InvalidKeyException("dummy exception");
        }
    };
    PasswordLookup lookup = new PasswordLookup(configuration);
    Deencapsulation.setField(lookup, "encryptionService", service);
    lookup.lookup(cryptingString);
}

From source file:me.lazerka.gae.jersey.oauth2.facebook.TokenVerifierFacebookDebugToken.java

@Override
public FacebookUserPrincipal verify(String userAccessToken) throws IOException, InvalidKeyException {
    logger.trace("Requesting endpoint to validate token");

    DebugTokenResponse response = fetcher.fetchDebugToken(userAccessToken);

    if (!response.data.isValid) {
        throw new InvalidKeyException("Token invalid: " + response.data.error.message);
    }/*from w ww  . ja v  a2s  .c  om*/

    if (!appId.equals(response.data.appId)) {
        // Token is issued for another application.
        throw new InvalidKeyException("Wrong appId: " + response.data.appId);
    }

    DateTime now = nowProvider.get();
    if (now.getMillis() / 1000 > response.data.expiresAt) {
        throw new InvalidKeyException("Token expired: " + response.data.expiresAt);
    }

    if (response.data.userId == null || response.data.userId.isEmpty()) {
        throw new InvalidKeyException("No userId");
    }

    return new FacebookUserPrincipal(response.data.userId, null, null, response);
}

From source file:org.cryptomator.crypto.aes256.AesSivCipherUtil.java

static byte[] sivDecrypt(byte[] aesKey, byte[] macKey, byte[] ciphertext, byte[]... additionalData)
        throws DecryptFailedException, InvalidKeyException {
    if (aesKey.length != 16 && aesKey.length != 24 && aesKey.length != 32) {
        throw new InvalidKeyException("Invalid aesKey length " + aesKey.length);
    }/*from  w  ww  .j  a va 2  s. c  om*/

    final byte[] iv = Arrays.copyOf(ciphertext, 16);

    final byte[] actualCiphertext = Arrays.copyOfRange(ciphertext, 16, ciphertext.length);
    final int numBlocks = (actualCiphertext.length + 15) / 16;

    // clear out the 31st and 63rd (rightmost) bit:
    final byte[] ctr = Arrays.copyOf(iv, 16);
    ctr[8] = (byte) (ctr[8] & 0x7F);
    ctr[12] = (byte) (ctr[12] & 0x7F);
    final ByteBuffer ctrBuf = ByteBuffer.wrap(ctr);
    final long initialCtrVal = ctrBuf.getLong(8);

    final byte[] x = new byte[numBlocks * 16];
    final BlockCipher aes = new AESFastEngine();
    aes.init(true, new KeyParameter(aesKey));
    for (int i = 0; i < numBlocks; i++) {
        final long ctrVal = initialCtrVal + i;
        ctrBuf.putLong(8, ctrVal);
        aes.processBlock(ctrBuf.array(), 0, x, i * 16);
        aes.reset();
    }

    final byte[] plaintext = xor(actualCiphertext, x);

    final byte[] control = s2v(macKey, plaintext, additionalData);

    if (MessageDigest.isEqual(control, iv)) {
        return plaintext;
    } else {
        throw new DecryptFailedException("Authentication failed");
    }
}

From source file:DDTTestContext.java

/**
 * Construct an instance from a delimited string of the format key1=value1;key2=value2
 * @param delimitedString - the input (delimited) string
 * @param delim - the delimited string separating the key=value pairs - the default is ';'.
 *              If the actual delimiter is not the default then delimitedString has the first character that non-standard delim
 * @param validDelims - a coma-delimited string of valid delimiter - used only in the rare case of using non-standard delim
 *//*from   w  w  w.ja va 2 s  .  com*/
public DDTTestContext(String delimitedString, String delim, String validDelims) {

    // Parameters sanity check1 - all strings are not blank
    if (isBlank(delimitedString)) {
        return;
    }

    // Parameters sanity check2 - at least one instance of <key> "=" <value> exists
    if (!delimitedString.contains("=")) {
        return;
    }

    String actualDelim = delim;
    String actualStr = delimitedString;

    // Determine if the caller uses non standard delimiter.
    if (validDelims.contains(delimitedString.substring(0, 1))) {
        actualDelim = delimitedString.substring(0, 1);
        actualStr = delimitedString.substring(1);
    }

    String[] a1 = actualStr.split(actualDelim);
    for (int i = 0; i < a1.length; i++) {
        try {
            int idx = a1[i].indexOf("=");
            if (idx < 0) {
                throw new InvalidKeyException(
                        "'=' Delimiter not found in item " + (i + 1) + " of " + actualStr);
            }
            String key = a1[i].substring(0, idx);
            String value = a1[i].substring(idx + 1);

            if (isBlank(key)) {
                throw new InvalidKeyException("Empty key value in item " + (i + 1) + " of " + actualStr);
            }
            if (null != this.get(key.toLowerCase())) {
                throw new InvalidKeyException(
                        "Repeated key value of " + key + " in item " + (i + 1) + " of " + actualStr);
            }
            // store next & unique value (a2[1]) in hashtable using key of a2[0]
            this.put(key.toLowerCase(), value);
        } // try
        catch (InvalidKeyException e) {
            System.out.println(e.getMessage());
            return;
        }
    } // for loop
}