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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: X509Key.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Calculates a hash code value for the object. Objects
 * which are equal will also have the same hashcode.
 */
public int hashCode() {
    try {
        byte[] b1 = getEncodedInternal();
        int r = b1.length;
        for (int i = 0; i < b1.length; i++) {
            r += (b1[i] & 0xff) * 37;
        }
        return r;
    } catch (InvalidKeyException e) {
        // should not happen
        return 0;
    }
}
 
Example #19
Source File: WebAuthnCryptography.java    From android-webauthn-authenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Perform a signature over an arbitrary byte array.
 *
 * @param sig        Signature object with which to perform the signature, or null to create it
 *                   on the fly.
 * @param privateKey The private key with which to sign.
 * @param data       The data to be signed.
 * @return A byte array representing the signature in ASN.1 DER Ecdsa-Sig-Value format.
 * @throws VirgilException
 */
public byte[] performSignature(PrivateKey privateKey, byte[] data, Signature sig) throws VirgilException {
    try {
        if (sig == null) {
            sig = Signature.getInstance("SHA256withECDSA");
            sig.initSign(privateKey);
        }
        sig.update(data);
        return sig.sign();
    } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) {
        throw new VirgilException("couldn't perform signature: " + e.toString());
    }
}
 
Example #20
Source File: Sm4Util.java    From littleca with Apache License 2.0 5 votes vote down vote up
public static byte[] encrypt_Cbc_Padding(byte[] key, byte[] iv, byte[] data)
    throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
    NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
    InvalidAlgorithmParameterException {
    Cipher cipher = generateCbcCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.ENCRYPT_MODE, key, iv);
    return cipher.doFinal(data);
}
 
Example #21
Source File: CipherLite.java    From markdown-image-kit with MIT License 5 votes vote down vote up
/**
 * Returns the inverse of the current {@link CipherLite}.
 */
CipherLite createInverse() throws InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException,
        NoSuchPaddingException, InvalidAlgorithmParameterException {
    int inversedMode;
    if (cipherMode == Cipher.DECRYPT_MODE)
        inversedMode = Cipher.ENCRYPT_MODE;
    else if (cipherMode == Cipher.ENCRYPT_MODE)
        inversedMode = Cipher.DECRYPT_MODE;
    else
        throw new UnsupportedOperationException();
    return scheme.createCipherLite(secreteKey, cipher.getIV(),
            inversedMode, cipher.getProvider());
}
 
Example #22
Source File: CertificateGenerator.java    From NetBare with MIT License 5 votes vote down vote up
public KeyStore generateServer(String commonName, JKS jks,
                                      Certificate caCert, PrivateKey caPrivKey)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        IOException, OperatorCreationException, CertificateException,
        InvalidKeyException, SignatureException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(SERVER_KEY_SIZE);

    X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject();
    BigInteger serial = BigInteger.valueOf(randomSerial());
    X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
    name.addRDN(BCStyle.CN, commonName);
    name.addRDN(BCStyle.O, jks.certOrganisation());
    name.addRDN(BCStyle.OU, jks.certOrganizationalUnitName());
    X500Name subject = name.build();

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE,
            new Date(System.currentTimeMillis() + ONE_DAY), subject, keyPair.getPublic());
    builder.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(keyPair.getPublic()));
    builder.addExtension(Extension.basicConstraints, false,
            new BasicConstraints(false));
    builder.addExtension(Extension.subjectAlternativeName, false,
            new DERSequence(new GeneralName(GeneralName.dNSName, commonName)));

    X509Certificate cert = signCertificate(builder, caPrivKey);

    cert.checkValidity(new Date());
    cert.verify(caCert.getPublicKey());

    KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType());
    result.load(null, null);
    Certificate[] chain = { cert, caCert };
    result.setKeyEntry(jks.alias(), keyPair.getPrivate(), jks.password(), chain);
    return result;
}
 
Example #23
Source File: SyntheticPasswordCrypto.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static byte[] decrypt(SecretKey key, byte[] blob)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    if (blob == null) {
        return null;
    }
    byte[] iv = Arrays.copyOfRange(blob, 0, PROFILE_KEY_IV_SIZE);
    byte[] ciphertext = Arrays.copyOfRange(blob, PROFILE_KEY_IV_SIZE, blob.length);
    Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
            + KeyProperties.BLOCK_MODE_GCM + "/" + KeyProperties.ENCRYPTION_PADDING_NONE);
    cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
    return cipher.doFinal(ciphertext);
}
 
Example #24
Source File: SignatureECDSA.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/** @inheritDoc */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {

    if (!(publicKey instanceof PublicKey)) {
        String supplied = publicKey.getClass().getName();
        String needed = PublicKey.class.getName();
        Object exArgs[] = { supplied, needed };

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

    try {
        this.signatureAlgorithm.initVerify((PublicKey) publicKey);
    } catch (InvalidKeyException ex) {
        // reinstantiate Signature object to work around bug in JDK
        // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
        Signature sig = this.signatureAlgorithm;
        try {
            this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
        } catch (Exception e) {
            // this shouldn't occur, but if it does, restore previous
            // Signature
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
            }
            this.signatureAlgorithm = sig;
        }
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example #25
Source File: V3Certificate.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException,
        NoSuchAlgorithmException, InvalidKeyException, CertificateException,
        NoSuchProviderException, SignatureException {

    boolean success = true;

    success &= test("RSA", "SHA256withRSA", 2048);
    success &= test("DSA", "SHA256withDSA", 2048);
    success &= test("EC", "SHA256withECDSA", 384);

    if (!success) {
        throw new RuntimeException("At least one test case failed");
    }
}
 
Example #26
Source File: KeyUtil.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns whether the key is valid or not.
 * <P>
 * Note that this method is only apply to DHPublicKey at present.
 *
 * @param  publicKey
 *         the key object, cannot be null
 *
 * @throws NullPointerException if {@code publicKey} is null
 * @throws InvalidKeyException if {@code publicKey} is invalid
 */
public static final void validate(Key key)
        throws InvalidKeyException {
    if (key == null) {
        throw new NullPointerException(
            "The key to be validated cannot be null");
    }

    if (key instanceof DHPublicKey) {
        validateDHPublicKey((DHPublicKey)key);
    }
}
 
Example #27
Source File: DOMHMACSignatureMethod.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
boolean verify(Key key, SignedInfo si, byte[] sig,
               XMLValidateContext context)
    throws InvalidKeyException, SignatureException, XMLSignatureException
{
    if (key == null || si == null || sig == null) {
        throw new NullPointerException();
    }
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("key must be SecretKey");
    }
    if (hmac == null) {
        try {
            hmac = Mac.getInstance(getJCAAlgorithm());
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    if (outputLengthSet && outputLength < getDigestLength()) {
        throw new XMLSignatureException
            ("HMACOutputLength must not be less than " + getDigestLength());
    }
    hmac.init((SecretKey)key);
    ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
    byte[] result = hmac.doFinal();

    return MessageDigest.isEqual(sig, result);
}
 
Example #28
Source File: EncryptTool.java    From FastAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * Hmac 加密模板
 *
 * @param data      数据
 * @param key       秘钥
 * @param algorithm 加密算法
 * @return 密文字节数组
 */
private static byte[] hmacTemplate(final byte[] data, final byte[] key, final String algorithm) {
    if (data == null || data.length == 0 || key == null || key.length == 0) return null;
    try {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(secretKey);
        return mac.doFinal(data);
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #29
Source File: Sm4Util.java    From littleca with Apache License 2.0 5 votes vote down vote up
public static byte[] decrypt_Cbc_Padding(byte[] key, byte[] iv, byte[] cipherText)
    throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
    NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
    InvalidAlgorithmParameterException {
    Cipher cipher = generateCbcCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.DECRYPT_MODE, key, iv);
    return cipher.doFinal(cipherText);
}
 
Example #30
Source File: SM4Util.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
public static byte[] decrypt_CBC_NoPadding(byte[] key, byte[] iv, byte[] cipherText)
        throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
        InvalidAlgorithmParameterException {
    Cipher cipher = generateCBCCipher(ALGORITHM_NAME_CBC_NOPADDING, Cipher.DECRYPT_MODE, key, iv);
    return cipher.doFinal(cipherText);
}