java.security.InvalidKeyException Java Examples

The following examples show how to use java.security.InvalidKeyException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestCipherKeyWrapperTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException,
        InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException {
    for (String alg : PBE_ALGORITHM_AR) {
        String baseAlgo = alg.split("/")[0].toUpperCase();
        // only run the tests on longer key lengths if unlimited version
        // of JCE jurisdiction policy files are installed

        if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE
                && (baseAlgo.endsWith("TRIPLEDES") || alg
                        .endsWith("AES_256"))) {
            out.println("keyStrength > 128 within " + alg
                    + " will not run under global policy");
            continue;
        }
        SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
        SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover"
                .toCharArray()));
        wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true);
    }
}
 
Example #2
Source File: SignatureDSA.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
    throws XMLSignatureException {
    if (!(privateKey instanceof PrivateKey)) {
        String supplied = privateKey.getClass().getName();
        String needed = PrivateKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example #3
Source File: DSAPublicKey.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Make a DSA public key out of a public key and three parameters.
 * The p, q, and g parameters may be null, but if so, parameters will need
 * to be supplied from some other source before this key can be used in
 * cryptographic operations.  PKIX RFC2459bis explicitly allows DSA public
 * keys without parameters, where the parameters are provided in the
 * issuer's DSA public key.
 *
 * @param y the actual key bits
 * @param p DSA parameter p, may be null if all of p, q, and g are null.
 * @param q DSA parameter q, may be null if all of p, q, and g are null.
 * @param g DSA parameter g, may be null if all of p, q, and g are null.
 */
public DSAPublicKey(BigInteger y, BigInteger p, BigInteger q,
                    BigInteger g)
throws InvalidKeyException {
    this.y = y;
    algid = new AlgIdDSA(p, q, g);

    try {
        byte[] keyArray = new DerValue(DerValue.tag_Integer,
                           y.toByteArray()).toByteArray();
        setKey(new BitArray(keyArray.length*8, keyArray));
        encode();
    } catch (IOException e) {
        throw new InvalidKeyException("could not DER encode y: " +
                                      e.getMessage());
    }
}
 
Example #4
Source File: SecKFTranslateTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public MyOwnSecKey(byte[] key1, int offset, String algo)
        throws InvalidKeyException {
    algorithm = algo;
    if (algo.equalsIgnoreCase("DES")) {
        keySize = 8;
    } else if (algo.equalsIgnoreCase("DESede")) {
        keySize = 24;
    } else {
        throw new InvalidKeyException(
                "Inappropriate key format and algorithm");
    }

    if (key1 == null || key1.length - offset < keySize) {
        throw new InvalidKeyException("Wrong key size");
    }
    key = new byte[keySize];
    System.arraycopy(key, offset, key, 0, keySize);
}
 
Example #5
Source File: SignatureECDSA.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/** @inheritDoc */
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
    if (!(privateKey instanceof PrivateKey)) {
        String supplied = privateKey.getClass().getName();
        String needed = PrivateKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initSign((PrivateKey) privateKey);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example #6
Source File: TestCipherKeyWrapperTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException,
        InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException {
    for (String alg : PBE_ALGORITHM_AR) {
        String baseAlgo = alg.split("/")[0].toUpperCase();
        // only run the tests on longer key lengths if unlimited version
        // of JCE jurisdiction policy files are installed

        if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE
                && (baseAlgo.endsWith("TRIPLEDES") || alg
                        .endsWith("AES_256"))) {
            out.println("keyStrength > 128 within " + alg
                    + " will not run under global policy");
            continue;
        }
        SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
        SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover"
                .toCharArray()));
        wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true);
    }
}
 
Example #7
Source File: X509Key.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj instanceof Key == false) {
        return false;
    }
    try {
        byte[] thisEncoded = this.getEncodedInternal();
        byte[] otherEncoded;
        if (obj instanceof X509Key) {
            otherEncoded = ((X509Key)obj).getEncodedInternal();
        } else {
            otherEncoded = ((Key)obj).getEncoded();
        }
        return Arrays.equals(thisEncoded, otherEncoded);
    } catch (InvalidKeyException e) {
        return false;
    }
}
 
Example #8
Source File: DESKeyGenerator.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates the DES key.
 *
 * @return the new DES key
 */
protected SecretKey engineGenerateKey() {
    DESKey desKey = null;

    if (this.random == null) {
        this.random = SunJCE.getRandom();
    }

    try {
        byte[] key = new byte[DESKeySpec.DES_KEY_LEN];
        do {
            this.random.nextBytes(key);
            setParityBit(key, 0);
        } while (DESKeySpec.isWeak(key, 0));
        desKey = new DESKey(key);
    } catch (InvalidKeyException e) {
        // this is never thrown
    }

    return desKey;
}
 
Example #9
Source File: TestAESWrapOids.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    for (DataTuple dataTuple : DATA) {
        int maxAllowedKeyLength = getMaxAllowedKeyLength(
                dataTuple.algorithm);
        boolean supportedKeyLength =
                maxAllowedKeyLength >= dataTuple.keyLength;

        try {
            runTest(dataTuple, supportedKeyLength);
            System.out.println("passed");
        } catch (InvalidKeyException ike) {
            if (supportedKeyLength) {
                throw new RuntimeException(String.format(
                        "The key length %d is supported, but test failed.",
                        dataTuple.keyLength), ike);
            } else {
                System.out.printf(
                        "Catch expected InvalidKeyException "
                                + "due to the key length %d is greater "
                                + "than max supported key length %d%n",
                        dataTuple.keyLength, maxAllowedKeyLength);
            }
        }
    }
}
 
Example #10
Source File: ConfigMapper.java    From update4j with Apache License 2.0 6 votes vote down vote up
public void verifySignature(PublicKey key) {
    if (signature == null) {
        throw new SecurityException("No signature in configuration root node.");
    }

    try {
        Signature sign = Signature.getInstance("SHA256with" + key.getAlgorithm());
        sign.initVerify(key);
        sign.update(getChildrenXml().getBytes(StandardCharsets.UTF_8));

        if (!sign.verify(Base64.getDecoder().decode(signature))) {
            throw new SecurityException("Signature verification failed.");
        }

    } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) {
        throw new SecurityException(e);
    }
}
 
Example #11
Source File: OpenSSLPKCS5CipherProvider.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, String password, byte[] salt, boolean encryptMode)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    if (encryptionMethod == null) {
        throw new IllegalArgumentException("The encryption method must be specified");
    }

    if (StringUtils.isEmpty(password)) {
        throw new IllegalArgumentException("Encryption with an empty password is not supported");
    }

    validateSalt(encryptionMethod, salt);

    String algorithm = encryptionMethod.getAlgorithm();
    String provider = encryptionMethod.getProvider();

    // Initialize secret key from password
    final PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
    final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm, provider);
    SecretKey tempKey = factory.generateSecret(pbeKeySpec);

    final PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, getIterationCount());
    Cipher cipher = Cipher.getInstance(algorithm, provider);
    cipher.init(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, tempKey, parameterSpec);
    return cipher;
}
 
Example #12
Source File: TestCipherKeyWrapperTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException,
        InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException {
    for (String alg : PBE_ALGORITHM_AR) {
        String baseAlgo = alg.split("/")[0].toUpperCase();
        // only run the tests on longer key lengths if unlimited version
        // of JCE jurisdiction policy files are installed

        if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE
                && (baseAlgo.endsWith("TRIPLEDES") || alg
                        .endsWith("AES_256"))) {
            out.println("keyStrength > 128 within " + alg
                    + " will not run under global policy");
            continue;
        }
        SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
        SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover"
                .toCharArray()));
        wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true);
    }
}
 
Example #13
Source File: X509Key.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj instanceof Key == false) {
        return false;
    }
    try {
        byte[] thisEncoded = this.getEncodedInternal();
        byte[] otherEncoded;
        if (obj instanceof X509Key) {
            otherEncoded = ((X509Key)obj).getEncodedInternal();
        } else {
            otherEncoded = ((Key)obj).getEncoded();
        }
        return Arrays.equals(thisEncoded, otherEncoded);
    } catch (InvalidKeyException e) {
        return false;
    }
}
 
Example #14
Source File: KeyStore.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the private key for the keystore entry.
 */
void setPrivateKey(RSAPrivateCrtKey key)
    throws InvalidKeyException, KeyStoreException
{
    byte[] modulusBytes = key.getModulus().toByteArray();

    // Adjust key length due to sign bit
    int keyBitLength = (modulusBytes[0] == 0)
        ? (modulusBytes.length - 1) * 8
        : modulusBytes.length * 8;

    byte[] keyBlob = generatePrivateKeyBlob(
        keyBitLength,
        modulusBytes,
        key.getPublicExponent().toByteArray(),
        key.getPrivateExponent().toByteArray(),
        key.getPrimeP().toByteArray(),
        key.getPrimeQ().toByteArray(),
        key.getPrimeExponentP().toByteArray(),
        key.getPrimeExponentQ().toByteArray(),
        key.getCrtCoefficient().toByteArray());

    privateKey = storePrivateKey(Objects.requireNonNull(keyBlob),
        "{" + UUID.randomUUID().toString() + "}", keyBitLength);
}
 
Example #15
Source File: X509Key.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct X.509 subject public key from a DER value.  If
 * the runtime environment is configured with a specific class for
 * this kind of key, a subclass is returned.  Otherwise, a generic
 * X509Key object is returned.
 *
 * <P>This mechanism gurantees that keys (and algorithms) may be
 * freely manipulated and transferred, without risk of losing
 * information.  Also, when a key (or algorithm) needs some special
 * handling, that specific need can be accomodated.
 *
 * @param in the DER-encoded SubjectPublicKeyInfo value
 * @exception IOException on data format errors
 */
public static PublicKey parse(DerValue in) throws IOException
{
    AlgorithmId     algorithm;
    PublicKey       subjectKey;

    if (in.tag != DerValue.tag_Sequence)
        throw new IOException("corrupt subject key");

    algorithm = AlgorithmId.parse(in.data.getDerValue());
    try {
        subjectKey = buildX509Key(algorithm,
                                  in.data.getUnalignedBitString());

    } catch (InvalidKeyException e) {
        throw new IOException("subject key, " + e.getMessage(), e);
    }

    if (in.data.available() != 0)
        throw new IOException("excess subject key");
    return subjectKey;
}
 
Example #16
Source File: KeyStoreHelper.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the given byte[] data against the signature, using the
 * public key with which this helper was initialised and the algorithm
 * MD5 with RSA.
 *
 * @param data the original data that was signed
 * @param signature the provided signature
 *
 * @return true in case the signature matches, false otherwise.
 *
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public boolean checkDataWithPublicKey(final String publicKeyAlias,
                                      final byte[] data,
                                      final byte[] signature) throws KeyStoreException,
                                                             NoSuchAlgorithmException,
                                                             InvalidKeyException,
                                                             SignatureException {
    if( pubKeyStore == null ) {
        throw new RuntimeException( "Key store with public key not configured. Please configure it properly before using signed serialization." );
    }
    Certificate cert = pubKeyStore.getCertificate( publicKeyAlias );
    if( cert == null ) {
        throw new RuntimeException( "Public certificate for key '"+publicKeyAlias+"' not found in the configured key store. Impossible to deserialize the object." );
    }
    Signature sig = Signature.getInstance( "MD5withRSA" );
    sig.initVerify( cert.getPublicKey() );
    sig.update( data );
    return sig.verify( signature );
}
 
Example #17
Source File: DesMacCksumType.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Decrypts keyed checksum.
 * @param enc_cksum the buffer for encrypted checksum.
 * @param key the key.
 * @return the checksum.
 *
 * @modified by Yanni Zhang, 12/08/99.
 */
private byte[] decryptKeyedChecksum(byte[] enc_cksum, byte[] key) throws KrbCryptoException {
    byte[] new_key = new byte[keySize()];
    System.arraycopy(key, 0, new_key, 0, key.length);
    for (int i = 0; i < new_key.length; i++)
    new_key[i] = (byte)(new_key[i] ^ 0xf0);
    //check for weak keys
    try {
        if (DESKeySpec.isWeak(new_key, 0)) {
            new_key[7] = (byte)(new_key[7] ^ 0xF0);
        }
    } catch (InvalidKeyException ex) {
        // swallow, since it should never happen
    }
    byte[] ivec = new byte[new_key.length];
    byte[] cksum = new byte[enc_cksum.length];
    Des.cbc_encrypt(enc_cksum, cksum, new_key, ivec, false);
    return cksum;
}
 
Example #18
Source File: RC2Crypt.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void init(boolean decrypting, String algorithm, byte[] key)
        throws InvalidKeyException {
    int keyLength = key.length;
    if (effectiveKeyBits == 0) {
        effectiveKeyBits = keyLength << 3;
    }

    checkKey(algorithm, keyLength);

    // key buffer, the L[] byte array from the spec
    byte[] expandedKeyBytes = new byte[128];

    // place key into key buffer
    System.arraycopy(key, 0, expandedKeyBytes, 0, keyLength);

    // first loop
    int t = expandedKeyBytes[keyLength - 1];
    for (int i = keyLength; i < 128; i++) {
        t = PI_TABLE[(t + expandedKeyBytes[i - keyLength]) & 0xff];
        expandedKeyBytes[i] = (byte)t;
    }

    int t8 = (effectiveKeyBits + 7) >> 3;
    int tm = 0xff >> (-effectiveKeyBits & 7);

    // second loop, reduce search space to effective key bits
    t = PI_TABLE[expandedKeyBytes[128 - t8] & tm];
    expandedKeyBytes[128 - t8] = (byte)t;
    for (int i = 127 - t8; i >= 0; i--) {
        t = PI_TABLE[t ^ (expandedKeyBytes[i + t8] & 0xff)];
        expandedKeyBytes[i] = (byte)t;
    }

    // byte to short conversion, little endian (copy into K[])
    for (int i = 0, j = 0; i < 64; i++, j += 2) {
        t =  (expandedKeyBytes[j    ] & 0xff)
          + ((expandedKeyBytes[j + 1] & 0xff) << 8);
        expandedKey[i] = t;
    }
}
 
Example #19
Source File: PBKDF2Translate.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * The test case scenario implemented in the method: - derive Key1 for the
 * given PBKDF2 algorithm - create my own secret Key2 as an instance of a
 * class implements PBEKey - translate Key2 - check if the key value of the
 * translated key and Key1 are the same.
 *
 * @return true if the test case passed; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 */
public boolean testMyOwnSecretKey()
        throws NoSuchAlgorithmException, InvalidKeySpecException,
        InvalidKeyException {
    SecretKey key1 = getSecretKeyForPBKDF2(algoToTest);
    SecretKey key2 = getMyOwnSecretKey();

    // Is it actually the same?
    if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
        System.err.println("We shouldn't be here. The key1 and key2 values "
                + "in its primary encoding format have to be the same!");
        return false;
    }

    // Translate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
    SecretKey key3 = skf.translateKey(key2);

    // Check if it still the same after translation
    if (!Arrays.equals(key1.getEncoded(), key3.getEncoded())) {
        System.err.println("testMyOwnSecretKey test case failed: the key1 "
                + "and key3 values in its primary encoding format are not "
                + "the same for " + algoToTest + "algorithm.");
        return false;
    }

    return true;
}
 
Example #20
Source File: WrongAAD.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private Cipher createCipher(int mode, AlgorithmParameters params)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER);
    if (params != null) {
        cipher.init(mode, key, params);
    } else {
        cipher.init(mode, key);
    }
    return cipher;
}
 
Example #21
Source File: PDFSignatureInfoParser.java    From pdf-sign-check with MIT License 5 votes vote down vote up
/**
 * Checks whether given X.509 certificate is self-signed.
 */
private static boolean isSelfSigned(X509Certificate cert) throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException {
    try {
        // Try to verify certificate signature with its own public key
        PublicKey key = cert.getPublicKey();
        cert.verify(key);
        return true;
    } catch (SignatureException | InvalidKeyException sigEx) {
        return false;
    }
}
 
Example #22
Source File: WrongAAD.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private Cipher createCipher(int mode, AlgorithmParameters params)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER);
    if (params != null) {
        cipher.init(mode, key, params);
    } else {
        cipher.init(mode, key);
    }
    return cipher;
}
 
Example #23
Source File: Offsets.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static Offsets init(String provider, String algorithm)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, SignatureException {
    // fill the cleartext data with random bytes
    byte[] cleartext = new byte[100];
    RandomFactory.getRandom().nextBytes(cleartext);

    // NONEwith requires input to be of 20 bytes
    int size = algorithm.contains("NONEwith") ? 20 : 100;

    // create signature instance
    Signature signature = Signature.getInstance(algorithm, provider);

    String keyAlgo;
    int keySize = 2048;
    if (algorithm.contains("RSA")) {
        keyAlgo = "RSA";
    } else if (algorithm.contains("ECDSA")) {
        keyAlgo = "EC";
        keySize = 256;
    } else if (algorithm.contains("DSA")) {
        keyAlgo = "DSA";
        if (algorithm.startsWith("SHAwith") ||
                algorithm.startsWith("SHA1with")) {
            keySize = 1024;
        }
    } else {
        throw new RuntimeException("Test doesn't support this signature "
                + "algorithm: " + algorithm);
    }

    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo, provider);
    kpg.initialize(keySize);
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubkey = kp.getPublic();
    PrivateKey privkey = kp.getPrivate();

    return new Offsets(signature, pubkey, privkey, size, cleartext);
}
 
Example #24
Source File: CICOSkipTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
CipherGenerator(String algo) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, InvalidKeyException,
        NoSuchPaddingException, InvalidKeySpecException {
    // Do initialization
    byte[] salt = TestUtilities.generateBytes(IV_LENGTH);
    int iterCnt = 6;
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.split("/")[0]);
    SecretKey key = skf
            .generateSecret(new PBEKeySpec(PASSWD.toCharArray()));
    AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iterCnt);
    initCiphers(algo, key, aps);
}
 
Example #25
Source File: PFSecurityUtils.java    From PFLockScreen-Android with Apache License 2.0 5 votes vote down vote up
private void initDecodeCipher(Cipher cipher, String alias) throws PFSecurityException {
    try {
        final KeyStore keyStore = loadKeyStore();
        final PrivateKey key  = (PrivateKey) keyStore.getKey(alias, null);
        cipher.init(Cipher.DECRYPT_MODE, key);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException
            | InvalidKeyException e) {
        e.printStackTrace();
        throw  new PFSecurityException(
                "Error init decode Cipher: " + e.getMessage(),
                PFSecurityUtilsErrorCodes.ERROR_INIT_DECODE_CIPHER
        );
    }

}
 
Example #26
Source File: DESKeyGenerator.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generates the DES key.
 *
 * @return the new DES key
 */
protected SecretKey engineGenerateKey() {
    DESKey desKey = null;

    if (this.random == null) {
        this.random = SunJCE.getRandom();
    }

    try {
        byte[] key = new byte[DESKeySpec.DES_KEY_LEN];
        do {
            this.random.nextBytes(key);
            setParityBit(key, 0);
        } while (DESKeySpec.isWeak(key, 0));
        desKey = new DESKey(key);
    } catch (InvalidKeyException e) {
        // this is never thrown
    }

    return desKey;
}
 
Example #27
Source File: KeyStoreHelper.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
private static byte[] decrypt(String alias, byte[] data) {
    try {
        PrivateKey privateKey = getPrivateKey(alias);
        if (privateKey == null) return null;
        Cipher cipher = Cipher.getInstance(SecurityConstants.CIPHER_RSA_ECB_PKCS1);

        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
            IllegalBlockSizeException | BadPaddingException ex) {
        Timber.e(ex);
        return null;
    }
}
 
Example #28
Source File: SecKFTranslateTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
SecretKey intSecurityKey(AlgorithmParameterSpec[] spec)
        throws InvalidKeyException {
    int keyLength = 8;
    byte[] keyVal = new byte[keyLength];
    new SecureRandom().nextBytes(keyVal);
    SecretKey key1 = new MyOwnSecKey(keyVal, 0, this.toString());
    return key1;
}
 
Example #29
Source File: Cryptography.java    From zap-android with MIT License 5 votes vote down vote up
public void addPinActiveKey() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, InvalidAlgorithmParameterException, NoSuchProviderException, InvalidKeyException, NoSuchPaddingException, UnrecoverableEntryException {
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE_NAME);
    keyStore.load(null);

    if (!keyStore.containsAlias(KEY_PIN_ACTIVE)) {
        initValidKeys(KEY_PIN_ACTIVE);
    }
}
 
Example #30
Source File: PBMacBuffer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests Mac.update(ByteBuffer input) method. Three test cases are
 * performed: - large ByteBuffer test case to test if the update() method
 * process a large ByteBuffer correctly; - empty ByteBuffer test case to
 * test if the update() method process an empty ByteBuffer correctly; - NULL
 * ByteBuffer test case to test if the update() method throws expected
 * IllegalArgumentException exception.
 *
 * @param theMacAlgo PBMAC algorithm to test
 * @param thePBKDF2Algo PBKDF2 algorithm to test
 * @return true - test passed; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws InvalidKeySpecException
 * @see javax.crypto.Mac
 */
protected boolean doTest(String theMacAlgo, String thePBKDF2Algo)
        throws NoSuchAlgorithmException, InvalidKeyException,
        InvalidKeySpecException {
    // obtain a SecretKey using PBKDF2
    SecretKey key = getSecretKey(thePBKDF2Algo);

    // Instantiate Mac object and init it with a SecretKey
    Mac theMac = Mac.getInstance(theMacAlgo);
    theMac.init(key);

    // Do large ByteBuffer test case
    if (!largeByteBufferTest(theMac)) {
        System.out.println("Large ByteBuffer test case failed.");
        return false;
    }

    // Do empty ByteBuffer test case
    if (!emptyByteBufferTest(theMac)) {
        System.out.println("Empty ByteBuffer test case failed.");
        return false;
    }

    // Do null ByteBuffer test case
    if (!nullByteBufferTest(theMac)) {
        System.out.println("NULL ByteBuffer test case failed.");
        return false;
    }

    return true;
}