Example usage for java.security NoSuchAlgorithmException NoSuchAlgorithmException

List of usage examples for java.security NoSuchAlgorithmException NoSuchAlgorithmException

Introduction

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

Prototype

public NoSuchAlgorithmException(Throwable cause) 

Source Link

Document

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

Usage

From source file:org.opensc.pkcs11.spi.PKCS11CipherSpi.java

@Override
protected void engineSetMode(String engineMode) throws NoSuchAlgorithmException {
    if (!engineMode.equals("ECB"))
        throw new NoSuchAlgorithmException("Only ECB mode is supported.");
}

From source file:org.opensc.pkcs11.spi.PKCS11KeyStoreSpi.java

@Override
public void engineStore(OutputStream arg0, char[] arg1)
        throws IOException, NoSuchAlgorithmException, CertificateException {
    throw new NoSuchAlgorithmException("PKCS11 key store does not support a store operation.");
}

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

/**
 * Test method for/*from ww w .  j  a  v a2 s  .c om*/
 * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createEncryptionService(org.seedstack.seed.crypto.internal.KeyStoreDefinition, org.seedstack.seed.crypto.internal.CertificateDefinition)}
 * . Test a {@link NoSuchAlgorithmException} if keystore can not be loaded.
 *
 * @throws Exception if an error occurred
 */
@Test(expected = RuntimeException.class)
public void testCreateEncryptionServiceWithKeystoreAlgorithmException(
        @Mocked final KeyStoreDefinition keyStoreDefinition,
        @Mocked final CertificateDefinition certificateDefinition, @Mocked final KeyStore keyStore,
        @Mocked final FileInputStream file,
        @SuppressWarnings("unused") @Mocked final EncryptionServiceImpl asymetricCrypting) throws Exception {
    new Expectations() {
        final String pathToKeystore = "pathToKeystore";
        final String password = "password";

        {
            keyStoreDefinition.getPath();
            returns(pathToKeystore);

            KeyStore.getInstance(KeyStore.getDefaultType());
            returns(keyStore);

            new FileInputStream(pathToKeystore);
            result = file;

            keyStoreDefinition.getPassword();
            returns(password);

            keyStore.load(file, password.toCharArray());
            result = new NoSuchAlgorithmException("dummy exception");
        }
    };

    EncryptionServiceFactory factory = new EncryptionServiceFactory();
    factory.createEncryptionService(keyStoreDefinition, certificateDefinition);

}

From source file:org.signserver.module.xades.signer.XAdESSignerUnitTest.java

private static MockedCryptoToken generateToken(final KeyType keyType) throws Exception {
    final KeyPair signerKeyPair;
    final String signatureAlgorithm;

    switch (keyType) {
    case RSA:/*from  w w w  . j  a  v  a  2 s .co m*/
        signerKeyPair = CryptoUtils.generateRSA(1024);
        signatureAlgorithm = "SHA1withRSA";
        break;
    case DSA:
        signerKeyPair = CryptoUtils.generateDSA(1024);
        signatureAlgorithm = "SHA1withDSA";
        break;
    case ECDSA:
        signerKeyPair = CryptoUtils.generateEcCurve("prime256v1");
        signatureAlgorithm = "SHA1withECDSA";
        break;
    default:
        throw new NoSuchAlgorithmException("Invalid key algorithm");
    }

    final Certificate[] certChain = new Certificate[] {
            new JcaX509CertificateConverter().getCertificate(new CertBuilder().setSelfSignKeyPair(signerKeyPair)
                    .setNotBefore(new Date(MockedTimeStampTokenProvider.TIMESTAMP))
                    .setSignatureAlgorithm(signatureAlgorithm).build()) };
    final Certificate signerCertificate = certChain[0];
    return new MockedCryptoToken(signerKeyPair.getPrivate(), signerKeyPair.getPublic(), signerCertificate,
            Arrays.asList(certChain), "BC");

}

From source file:org.signserver.module.xades.signer.XAdESSignerUnitTest.java

/**
 * Run a signing test with default form and varying commitment types.
 * /*from   ww  w .  ja  v  a 2s.  c o m*/
 * @param keyType Token key type to use
 * @param signatureAlgorithm Signature algorithm property value to test, if null use default
 * @param expectedSignatureAlgorithmUri Expected XML signature algorithm URI
 * @param commitmentTypesProperty COMMITMENT_TYPES property to test with
 *                                if null, doesn't set the property
 * @param expectedCommitmentTypeUris List of expected commitment type URIs
 * @param claimedRoleProperty Claimed role property to test, ff null, don't set property
 * @param claimedRoleFromUsername If set to true, include the CLAIMED_ROLE_FROM_USERNAME property
 * @param useCertCredential Pass in a (faked dummy) certificate credential in the request context to simulate the situation when the
 *                          client credential is not a user name
 * @param username Username to pass in via the request context, if null no username is passed in
 * @param expectedClaimedRole Expected claimed role in signed document, if null check that no claimed role is included
 * @throws Exception
 */
private void testProcessData_basicSigningInternal(final KeyType keyType, final String signatureAlgorithm,
        final String expectedSignatureAlgorithmUri, final String commitmentTypesProperty,
        final Collection<String> expectedCommitmentTypeUris, final String claimedRoleProperty,
        final boolean claimedRoleFromUsername, final boolean useCertCredential, final String username,
        final String expectedClaimedRole) throws Exception {
    LOG.info("processData");

    final MockedCryptoToken token;

    switch (keyType) {
    case RSA:
        token = tokenRSA;
        break;
    case DSA:
        token = tokenDSA;
        break;
    case ECDSA:
        token = tokenECDSA;
        break;
    default:
        throw new NoSuchAlgorithmException("Unknown key algorithm");
    }

    WorkerConfig config = new WorkerConfig();

    if (commitmentTypesProperty != null) {
        config.setProperty("COMMITMENT_TYPES", commitmentTypesProperty);
    }

    if (signatureAlgorithm != null) {
        config.setProperty("SIGNATUREALGORITHM", signatureAlgorithm);
    }

    if (claimedRoleProperty != null) {
        config.setProperty("CLAIMED_ROLE", claimedRoleProperty);
    }

    if (claimedRoleFromUsername) {
        config.setProperty("CLAIMED_ROLE_FROM_USERNAME", "true");
    }

    final XAdESVerificationResult r = getVerificationResult(token, config, "<testroot/>", useCertCredential,
            username);

    assertEquals("BES", r.getSignatureForm().name());
    assertEquals("Unexpected signature algorithm in signature", expectedSignatureAlgorithmUri,
            r.getSignatureAlgorithmUri());

    final QualifyingProperties qp = r.getQualifyingProperties();

    final Set<String> foundUris = new HashSet<String>();

    final SignedProperties sp = qp.getSignedProperties();

    // check for ClaimedRole
    boolean foundExpectedRole = false;
    for (final SignedSignatureProperty sigProp : sp.getSigProps()) {
        LOG.debug("signed signature property: " + sigProp.getClass().getName() + ": " + sigProp.toString());

        if (sigProp instanceof SignerRoleProperty) {
            final SignerRoleProperty role = (SignerRoleProperty) sigProp;

            for (final String claimedRole : role.getClaimedRoles()) {
                if (expectedClaimedRole == null) {
                    fail("Should not contain a claimed role");
                } else if (expectedClaimedRole.equals(claimedRole)) {
                    foundExpectedRole = true;
                } else {
                    fail("Unexpected claimed role: " + claimedRole);
                }
            }
        }
    }

    if (expectedClaimedRole != null) {
        assertTrue("Expected to find claimed role: " + claimedRoleProperty, foundExpectedRole);
    }

    for (final SignedDataObjectProperty signedObjProp : sp.getDataObjProps()) {
        LOG.debug("object property: " + signedObjProp.getClass().getName() + ": " + signedObjProp.toString());

        if (signedObjProp instanceof AllDataObjsCommitmentTypeProperty) {
            final AllDataObjsCommitmentTypeProperty commitmentType = (AllDataObjsCommitmentTypeProperty) signedObjProp;

            final String uri = commitmentType.getUri();
            LOG.debug("Found commitment type: " + uri);
            if (expectedCommitmentTypeUris.contains(uri)) {
                foundUris.add(uri);
            } else {
                fail("Unexpected commitment type: " + uri);
            }
        }
    }

    assertTrue("Should contain expected commitment types: " + expectedCommitmentTypeUris.toString(),
            foundUris.size() == expectedCommitmentTypeUris.size());
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

/**
 * Creates a test signature and verifies it.
 *
 * @param privateKey Private key to sign with
 * @param publicKey Public key to verify with
 * @param signatureProvider Name of provider to sign with
 * @throws NoSuchAlgorithmException In case the key or signature algorithm is unknown
 * @throws NoSuchProviderException In case the supplied provider name is unknown or BC is not installed
 * @throws InvalidKeyException If signature verification failed or the key was invalid
 * @throws SignatureException If the signature could not be made or verified correctly
 *//*from   w ww. j a va 2  s .co m*/
public static void testSignAndVerify(PrivateKey privateKey, PublicKey publicKey, String signatureProvider)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final String sigAlg = suggestSigAlg(publicKey);
    if (sigAlg == null) {
        throw new NoSuchAlgorithmException("Unknown key algorithm: " + publicKey.getAlgorithm());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Testing keys with algorithm: " + publicKey.getAlgorithm());
        LOG.debug("testSigAlg: " + sigAlg);
        LOG.debug("provider: " + signatureProvider);
        LOG.trace("privateKey: " + privateKey);
        LOG.trace("privateKey class: " + privateKey.getClass().getName());
        LOG.trace("publicKey: " + publicKey);
        LOG.trace("publicKey class: " + publicKey.getClass().getName());
    }
    final Signature signSignature = Signature.getInstance(sigAlg, signatureProvider);
    signSignature.initSign(privateKey);
    signSignature.update(input);
    byte[] signBA = signSignature.sign();
    if (LOG.isTraceEnabled()) {
        LOG.trace("Created signature of size: " + signBA.length);
        LOG.trace("Created signature: " + new String(Hex.encode(signBA)));
    }

    final Signature verifySignature = Signature.getInstance(sigAlg, "BC");
    verifySignature.initVerify(publicKey);
    verifySignature.update(input);
    if (!verifySignature.verify(signBA)) {
        throw new InvalidKeyException("Test signature inconsistent");
    }
}

From source file:org.soulwing.crypt4j.DesCrypt.java

private void checkUnixCryptAvailability() throws NoSuchAlgorithmException {
    try {//from  w ww  . j  a va  2 s .c o  m
        getClassLoader().loadClass(UNIX_CRYPT_CLASS);
    } catch (ClassNotFoundException ex) {
        throw new NoSuchAlgorithmException("DES unavailable; Commons Codec library not on classpath");
    }
}

From source file:org.xdi.oxauth.cert.fingerprint.FingerprintHelper.java

public static String getPublicKeySshFingerprint(PublicKey publicKey)
        throws NoSuchAlgorithmException, IOException {
    if (publicKey instanceof RSAPublicKey) {
        return getPublicKeySshFingerprint((RSAPublicKey) publicKey);
    }//w  ww .  j  a  v  a  2 s. c o  m

    throw new NoSuchAlgorithmException("Unsopported PublicKey type");
}

From source file:swp.bibjsf.persistence.Data.java

/**
 * Returns an MD5 hash of reader's password.
 *
 * @param reader//  www .  j a  v a2 s . c o m
 *            reader whose password is to be hashed
 * @return MD5 hash of reader's password
 * @throws NoSuchAlgorithmException
 *             thrown if there is no MD5 algorithm
 */
private String hashPassword(Reader reader) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");

    String readerPassword = reader.getPassword();
    if (readerPassword == null) {
        readerPassword = "";
    }
    byte[] bpassword;
    try {
        bpassword = md.digest(readerPassword.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new NoSuchAlgorithmException("no UTF-8 encoding possible: " + e.getLocalizedMessage());
    }
    StringBuffer password = new StringBuffer();
    for (int i = 0; i < bpassword.length; i++) {
        password.append(Integer.toString((bpassword[i] & 0xff) + 0x100, 16).substring(1));
    }
    return password.toString();
}