java.security.SignatureException Java Examples

The following examples show how to use java.security.SignatureException. 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: DefaultCertificateClient.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Creates digital signature over the data stream using the s private key.
 *
 * @param data - Data to sign.
 * @throws CertificateException - on Error.
 */
@Override
public byte[] signData(byte[] data) throws CertificateException {
  try {
    Signature sign = Signature.getInstance(securityConfig.getSignatureAlgo(),
        securityConfig.getProvider());

    sign.initSign(getPrivateKey());
    sign.update(data);

    return sign.sign();
  } catch (NoSuchAlgorithmException | NoSuchProviderException
      | InvalidKeyException | SignatureException e) {
    getLogger().error("Error while signing the stream", e);
    throw new CertificateException("Error while signing the stream", e,
        CRYPTO_SIGN_ERROR);
  }
}
 
Example #2
Source File: TlsCertificateAuthorityTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
private Certificate validateServerKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableEntryException,
        InvalidKeyException, NoSuchProviderException, SignatureException {
    serverConfig = objectMapper.readValue(new ByteArrayInputStream(serverConfigFileOutputStream.toByteArray()), TlsConfig.class);

    KeyStore serverKeyStore = KeyStoreUtils.getKeyStore(serverConfig.getKeyStoreType());
    serverKeyStore.load(new ByteArrayInputStream(serverKeyStoreOutputStream.toByteArray()), serverConfig.getKeyStorePassword().toCharArray());
    String keyPassword = serverConfig.getKeyPassword();
    KeyStore.Entry serverKeyEntry = serverKeyStore.getEntry(TlsToolkitStandalone.NIFI_KEY,
            new KeyStore.PasswordProtection(keyPassword == null ? serverConfig.getKeyStorePassword().toCharArray() : keyPassword.toCharArray()));

    assertTrue(serverKeyEntry instanceof KeyStore.PrivateKeyEntry);
    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) serverKeyEntry;
    Certificate[] certificateChain = privateKeyEntry.getCertificateChain();
    assertEquals(1, certificateChain.length);
    Certificate caCertificate = certificateChain[0];
    caCertificate.verify(caCertificate.getPublicKey());
    assertPrivateAndPublicKeyMatch(privateKeyEntry.getPrivateKey(), caCertificate.getPublicKey());
    return caCertificate;
}
 
Example #3
Source File: SignatureBench.java    From bumblebench with Apache License 2.0 6 votes vote down vote up
protected long doBatch(long numIterations) throws InterruptedException {
    try {
        for (long i = 0; i < numIterations; i++) {
            if (exeMode == 1) {
               sig.update(data);
               signatureBytes = sig.sign();
            } else if (exeMode == 2) {
               sig.update(data);
               sig.verify(signatureBytes, 0, signatureBytes.length);
            }
        }
    } catch (SignatureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return numIterations;
}
 
Example #4
Source File: RootCAProvider.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private boolean saveNewRootCACertificate() {
    if (caKeyPair == null) {
        throw new CloudRuntimeException("Cannot issue self-signed root CA certificate as CA keypair is not initialized");
    }
    try {
        LOG.debug("Generating root CA certificate");
        final X509Certificate rootCaCertificate = CertUtils.generateV3Certificate(
                null, caKeyPair, caKeyPair.getPublic(),
                rootCAIssuerDN.value(), CAManager.CertSignatureAlgorithm.value(),
                getCaValidityDays(), null, null);
        if (!configDao.update(rootCACertificate.key(), rootCACertificate.category(), CertUtils.x509CertificateToPem(rootCaCertificate))) {
            LOG.error("Failed to update RootCA public/x509 certificate");
        }
    } catch (final CertificateException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException | InvalidKeyException | OperatorCreationException | IOException e) {
        LOG.error("Failed to generate RootCA certificate from private/public keys due to exception:", e);
        return false;
    }
    return loadRootCACertificate();
}
 
Example #5
Source File: CryptoExceptionTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testCryptoExceptions() {

    CryptoException ex = new CryptoException();
    assertNotNull(ex);
    assertEquals(ex.getCode(), CryptoException.CRYPTO_ERROR);

    assertNotNull(new CryptoException(new NoSuchAlgorithmException()));
    assertNotNull(new CryptoException(new InvalidKeyException()));
    assertNotNull(new CryptoException(new NoSuchProviderException()));
    assertNotNull(new CryptoException(new SignatureException()));
    assertNotNull(new CryptoException(new FileNotFoundException()));
    assertNotNull(new CryptoException(new IOException()));
    assertNotNull(new CryptoException(new CertificateException()));
    assertNotNull(new CryptoException(new InvalidKeySpecException()));
    assertNotNull(new CryptoException(new OperatorCreationException("unit-test")));
    assertNotNull(new CryptoException(new PKCSException("unit-test")));
    assertNotNull(new CryptoException(new CMSException("unit-test")));

    ex = new CryptoException(CryptoException.CERT_HASH_MISMATCH, "X.509 Certificate hash mismatch");
    assertEquals(ex.getCode(), CryptoException.CERT_HASH_MISMATCH);
}
 
Example #6
Source File: NativeRSASignature.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected synchronized int engineSign(byte[] outbuf, int offset, int len)
    throws SignatureException {
    boolean doCancel = true;
    try {
        if (outbuf == null || (offset < 0) || (outbuf.length < (offset + sigLength))
            || (len < sigLength)) {
            throw new SignatureException("Invalid output buffer. offset: " +
                offset + ". len: " + len + ". sigLength: " + sigLength);
        }
        int rv = doFinal(outbuf, offset, sigLength);
        doCancel = false;
        if (rv < 0) {
            throw new SignatureException(new UcryptoException(-rv));
        }
        return sigLength;
    } finally {
        reset(doCancel);
    }
}
 
Example #7
Source File: InvalidBitString.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static boolean test(Certificate target, Certificate signer,
        String title, boolean expected) throws Exception {
    System.out.print("Checking " + title + ": expected: " +
            (expected ? "    verified" : "NOT verified"));
    boolean actual;
    try {
        PublicKey pubKey = signer.getPublicKey();
        target.verify(pubKey);
        actual = true;
    } catch (SignatureException se) {
        actual = false;
    }
    System.out.println(", actual: " +
            (actual ? "    verified" : "NOT verified"));
    return actual == expected;
}
 
Example #8
Source File: TestData.java    From UAF with Apache License 2.0 6 votes vote down vote up
public TestData(PublicKey pubArg, PrivateKey privArg)
		throws NoSuchAlgorithmException, InvalidKeySpecException,
		NoSuchProviderException, InvalidKeyException, SignatureException,
		UnsupportedEncodingException, InvalidAlgorithmParameterException {
	pub = pubArg;
	priv = privArg;
	int signedDataId = TagsEnum.TAG_UAFV1_SIGNED_DATA.id;
	int signedDataLength = 200;
	dataForSigning[0] = (byte) (signedDataId & 0x00ff);
	dataForSigning[1] = (byte) (signedDataId & 0xff00);
	dataForSigning[2] = (byte) (signedDataLength & 0x00ff);
	dataForSigning[3] = (byte) (signedDataLength & 0xff00);
	//signature = NamedCurve.sign(priv, dataForSigning);
	rsSignature = NamedCurve.signAndFromatToRS(priv,
			SHA.sha(dataForSigning, "SHA-1"));
}
 
Example #9
Source File: InvalidBitString.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean test(Certificate target, Certificate signer,
        String title, boolean expected) throws Exception {
    System.out.print("Checking " + title + ": expected: " +
            (expected ? "    verified" : "NOT verified"));
    boolean actual;
    try {
        PublicKey pubKey = signer.getPublicKey();
        target.verify(pubKey);
        actual = true;
    } catch (SignatureException se) {
        actual = false;
    }
    System.out.println(", actual: " +
            (actual ? "    verified" : "NOT verified"));
    return actual == expected;
}
 
Example #10
Source File: TestRSAAuthenticationToken.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testRSAAuthenticationToken()
    throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
  String tokenstr =
      "e8a04b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ@WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=";
  RSAAuthenticationToken token = RSAAuthenticationToken.fromStr(tokenstr);
  String contents = token.plainToken();
  Assert.assertEquals(
      "e8a04b54cf2711e7b701286ed488fc20@c8636e5acf1f11e7b701286ed488fc20@1511315597475@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ",
      contents);
  String sign = token.getSign();
  Assert.assertEquals(
      "WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=",
      sign);
  String pubKey =
      "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxKl5TNUTec7fL2degQcCk6vKf3c0wsfNK5V6elKzjWxm0MwbRj/UeR20VSnicBmVIOWrBS9LiERPPvjmmWUOSS2vxwr5XfhBhZ07gCAUNxBOTzgMo5nE45DhhZu5Jzt5qSV6o10Kq7+fCCBlDZ1UoWxZceHkUt5AxcrhEDulFjQIDAQAB";
  Assert.assertTrue(RSAUtils.verify(pubKey, sign, contents));
}
 
Example #11
Source File: X509V2CRLGenerator.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * generate an X509 CRL, based on the current issuer and subject
 * using the default provider "BC".
 * @deprecated use generate(key, "BC")
 */
public X509CRL generateX509CRL(
    PrivateKey      key)
    throws SecurityException, SignatureException, InvalidKeyException
{
    try
    {
        return generateX509CRL(key, "BC", null);
    }
    catch (NoSuchProviderException e)
    {
        throw new SecurityException("BC provider not installed!");
    }
}
 
Example #12
Source File: X509CertificateObject.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public final void verify(
    PublicKey   key,
    String      sigProvider)
    throws CertificateException, NoSuchAlgorithmException,
    InvalidKeyException, NoSuchProviderException, SignatureException
{
    String    sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm());
    Signature signature = Signature.getInstance(sigName, sigProvider);
    
    checkSignature(key, signature);
}
 
Example #13
Source File: WebGuiActivity.java    From syncthing-android with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Catch (self-signed) SSL errors and test if they correspond to Syncthing's certificate.
 */
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
    try {
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            // The mX509Certificate field is not available for ICS- devices
            Log.w(TAG, "Skipping certificate check for devices <ICS");
            handler.proceed();
            return;
        }
        // Use reflection to access the private mX509Certificate field of SslCertificate
        SslCertificate sslCert = error.getCertificate();
        Field f = sslCert.getClass().getDeclaredField("mX509Certificate");
        f.setAccessible(true);
        X509Certificate cert = (X509Certificate)f.get(sslCert);
        if (cert == null) {
            Log.w(TAG, "X509Certificate reference invalid");
            handler.cancel();
            return;
        }
        cert.verify(mCaCert.getPublicKey());
        handler.proceed();
    } catch (NoSuchFieldException|IllegalAccessException|CertificateException|
            NoSuchAlgorithmException|InvalidKeyException|NoSuchProviderException|
            SignatureException e) {
        Log.w(TAG, e);
        handler.cancel();
    }
}
 
Example #14
Source File: SignatureExceptionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test for <code>SignatureException(Throwable)</code> constructor
 * Assertion: constructs SignatureException when <code>cause</code> is not
 * null
 */
public void testSignatureException05() {
    SignatureException tE = new SignatureException(tCause);
    if (tE.getMessage() != null) {
        String toS = tCause.toString();
        String getM = tE.getMessage();
        assertTrue("getMessage() should contain ".concat(toS), (getM
                .indexOf(toS) != -1));
    }
    assertNotNull("getCause() must not return null", tE.getCause());
    assertEquals("getCause() must return ".concat(tCause.toString()), tE
            .getCause(), tCause);
}
 
Example #15
Source File: SignatureFileVerifier.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given the PKCS7 block and SignerInfo[], create an array of
 * CodeSigner objects. We do this only *once* for a given
 * signature block file.
 */
private CodeSigner[] getSigners(SignerInfo[] infos, PKCS7 block)
    throws IOException, NoSuchAlgorithmException, SignatureException,
        CertificateException {

    ArrayList<CodeSigner> signers = null;

    for (int i = 0; i < infos.length; i++) {

        SignerInfo info = infos[i];
        ArrayList<X509Certificate> chain = info.getCertificateChain(block);
        CertPath certChain = certificateFactory.generateCertPath(chain);
        if (signers == null) {
            signers = new ArrayList<>();
        }
        // Append the new code signer. If timestamp is invalid, this
        // jar will be treated as unsigned.
        signers.add(new CodeSigner(certChain, info.getTimestamp()));

        if (debug != null) {
            debug.println("Signature Block Certificate: " +
                chain.get(0));
        }
    }

    if (signers != null) {
        return signers.toArray(new CodeSigner[signers.size()]);
    } else {
        return null;
    }
}
 
Example #16
Source File: JacksonProtocolManager.java    From incubator-retired-gossip with Apache License 2.0 5 votes vote down vote up
private static byte[] sign(byte [] bytes, PrivateKey pk){
  Signature dsa;
  try {
    dsa = Signature.getInstance("SHA1withDSA", "SUN");
    dsa.initSign(pk);
    dsa.update(bytes);
    return dsa.sign();
  } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException e) {
    throw new RuntimeException(e);
  } 
}
 
Example #17
Source File: DelegatedEncryptionTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = SignatureException.class)
public void signedOnlyNoSignature() throws GeneralSecurityException {
    Map<String, AttributeValue> encryptedAttributes =
            encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
    assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
    encryptedAttributes.remove(encryptor.getSignatureFieldName());
    encryptor.decryptAllFieldsExcept(encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
 
Example #18
Source File: ECKey.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Given an arbitrary piece of text and a Bitcoin-format message signature encoded in base64, returns an ECKey
 * containing the public key that was used to sign it. This can then be compared to the expected public key to
 * determine if the signature was correct. These sorts of signatures are compatible with the Bitcoin-Qt/bitcoind
 * format generated by signmessage/verifymessage RPCs and GUI menu options. They are intended for humans to verify
 * their communications with each other, hence the base64 format and the fact that the input is text.
 *
 * @param message Some piece of human readable text.
 * @param signatureBase64 The Bitcoin-format message signature in base64
 * @throws SignatureException If the public key could not be recovered or if there was a signature format error.
 */
public static ECKey signedMessageToKey(String message, String signatureBase64) throws SignatureException {
    byte[] signatureEncoded;
    try {
        signatureEncoded = Base64.decode(signatureBase64);
    } catch (RuntimeException e) {
        // This is what you get back from Bouncy Castle if base64 doesn't decode :(
        throw new SignatureException("Could not decode base64", e);
    }
    // Parse the signature bytes into r/s and the selector value.
    if (signatureEncoded.length < 65)
        throw new SignatureException("Signature truncated, expected 65 bytes and got " + signatureEncoded.length);
    int header = signatureEncoded[0] & 0xFF;
    // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
    //                  0x1D = second key with even y, 0x1E = second key with odd y
    if (header < 27 || header > 34)
        throw new SignatureException("Header byte out of range: " + header);
    BigInteger r = new BigInteger(1, Arrays.copyOfRange(signatureEncoded, 1, 33));
    BigInteger s = new BigInteger(1, Arrays.copyOfRange(signatureEncoded, 33, 65));
    ECDSASignature sig = new ECDSASignature(r, s);
    byte[] messageBytes = Utils.formatMessageForSigning(message);
    // Note that the C++ code doesn't actually seem to specify any character encoding. Presumably it's whatever
    // JSON-SPIRIT hands back. Assume UTF-8 for now.
    Sha256Hash messageHash = Sha256Hash.twiceOf(messageBytes);
    boolean compressed = false;
    if (header >= 31) {
        compressed = true;
        header -= 4;
    }
    int recId = header - 27;
    ECKey key = ECKey.recoverFromSignature(recId, sig, messageHash, compressed);
    if (key == null)
        throw new SignatureException("Could not recover public key from signature");
    return key;
}
 
Example #19
Source File: X509V3CertificateGenerator.java    From ripple-lib-java with ISC License 5 votes vote down vote up
/**
 * generate an X509 certificate, based on the current issuer and subject,
 * using the passed in provider for the signing.
 */
public X509Certificate generate(
    PrivateKey      key,
    String          provider)
    throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
{
    return generate(key, provider, null);
}
 
Example #20
Source File: SignatureSpi.java    From ripple-lib-java with ISC License 5 votes vote down vote up
protected void engineUpdate(
    byte[]  b,
    int     off,
    int     len) 
    throws SignatureException
{
    digest.update(b, off, len);
}
 
Example #21
Source File: SignatureECDSA.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/** @inheritDoc */
protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
    try {
        this.signatureAlgorithm.update(buf, offset, len);
    } catch (SignatureException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example #22
Source File: Offsets.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
boolean verifySignature(byte[] sigData, int sigOffset, int sigLength,
        int updateOffset, int updateLength)
            throws InvalidKeyException, SignatureException {
    signature.initVerify(pubkey);
    signature.update(cleartext, updateOffset, updateLength);
    return signature.verify(sigData, sigOffset, sigLength);
}
 
Example #23
Source File: SigningUtil.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private static boolean verifyMessageSignature(PublicKey publicKey,
                                              String messageString, byte[] signature)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    Signature sign = Signature.getInstance("SHA256withRSA/PSS", new BouncyCastleProvider());
    byte[] message = messageString.getBytes();
    sign.initVerify(publicKey);
    sign.update(message);
    return sign.verify(signature);
}
 
Example #24
Source File: TransactionWrapper.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static long checkWeight(Permission permission, List<ByteString> sigs, byte[] hash,
                               List<ByteString> approveList)
        throws SignatureException, PermissionException, SignatureFormatException {
    long currentWeight = 0;
    //    if (signature.size() % 65 != 0) {
    //      throw new SignatureFormatException("Signature size is " + signature.size());
    //    }
    if (sigs.size() > permission.getKeysCount()) {
        throw new PermissionException(
                "Signature count is " + (sigs.size()) + " more than key counts of permission : "
                        + permission.getKeysCount());
    }
    HashMap addMap = new HashMap();
    for (ByteString sig : sigs) {
        if (sig.size() < 65) {
            throw new SignatureFormatException(
                    "Signature size is " + sig.size());
        }
        String base64 = TransactionWrapper.getBase64FromByteString(sig);
        byte[] address = ECKey.signatureToAddress(hash, base64);
        long weight = getWeight(permission, address);
        if (weight == 0) {
            throw new PermissionException(
                    ByteArray.toHexString(sig.toByteArray()) + " is signed by " + Wallet
                            .encode58Check(address) + " but it is not contained of permission.");
        }
        if (addMap.containsKey(base64)) {
            throw new PermissionException(Wallet.encode58Check(address) + " has signed twice!");
        }
        addMap.put(base64, weight);
        if (approveList != null) {
            approveList.add(ByteString.copyFrom(address)); //out put approve list.
        }
        currentWeight += weight;
    }
    return currentWeight;
}
 
Example #25
Source File: DOMHMACSignatureMethod.java    From openjdk-8-source 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 #26
Source File: SignatureECDSA.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/** @inheritDoc */
protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
    try {
        this.signatureAlgorithm.update(buf, offset, len);
    } catch (SignatureException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example #27
Source File: X509V3CertificateGenerator.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * generate an X509 certificate, based on the current issuer and subject,
 * using the passed in provider for the signing.
 * @deprecated use generate()
 */
public X509Certificate generateX509Certificate(
    PrivateKey      key,
    String          provider)
    throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException
{
    return generateX509Certificate(key, provider, null);
}
 
Example #28
Source File: LoginShiroFilterTest.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void handleRequestTest() throws SignatureException, IOException {
    ContainerRequestContext requestContext = createMock(ContainerRequestContext.class);
    ClassResourceInfo resourceClass = createMock(ClassResourceInfo.class);
    HttpHeaders headers = createMock(HttpHeaders.class);
    UriInfo uriInfo = createMock(UriInfo.class);

    String date = DateFormatUtils.SMTP_DATETIME_FORMAT.format(new Date());

    String resource = "/questionnaires/61";
    String method = "GET";
    String stringToSign = new StringBuilder().append(method).append(" ").append(resource).append("\n").append(date)
            .toString();
    String apiKey = "B868UOHUTKUDWXM";
    
    String secret = "IQO27YUZO8NJ7RADIK6SJ9BQZNYP4EMO";
    String signature = HMACSignature.calculateRFC2104HMAC(stringToSign, secret);
    String authToken = generateAuth(apiKey, signature);

    expect(requestContext.getMethod()).andReturn(method);
    expect(uriInfo.getRequestUri()).andReturn(URI.create("http://localhost:8080/gazpachoquest-rest-web/api/" + resource));
    
    expect(requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).andReturn(authToken);
    expect(requestContext.getHeaderString(HttpHeaders.DATE)).andReturn(date);
    
    expect(headers.getRequestHeader(HttpHeaders.AUTHORIZATION)).andReturn(Arrays.asList(authToken));
    expect(headers.getRequestHeader(HttpHeaders.DATE)).andReturn(Arrays.asList(date));

    expect(uriInfo.getPath()).andReturn(resource.substring(1));

    replay(requestContext,resourceClass, uriInfo, headers);

    loginShiroFilter.setUriInfo(uriInfo);
    loginShiroFilter.setHeaders(headers);

    loginShiroFilter.filter(requestContext);
}
 
Example #29
Source File: SignatureECDSA.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/** @inheritDoc */
protected void engineUpdate(byte[] input) throws XMLSignatureException {
    try {
        this.signatureAlgorithm.update(input);
    } catch (SignatureException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example #30
Source File: X509V2CRLGenerator.java    From ripple-lib-java with ISC License 5 votes vote down vote up
/**
 * generate an X509 certificate, based on the current issuer and subject
 * using the passed in provider for the signing.
 */
public X509CRL generate(
    PrivateKey      key,
    String          provider)
    throws CRLException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
{
    return generate(key, provider, null);
}