java.util.jar.JarException#java.security.SignatureException源码实例Demo

下面列出了java.util.jar.JarException#java.security.SignatureException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jdk8u-dev-jdk   文件: InvalidBitString.java
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;
}
 
源代码2 项目: athenz   文件: CryptoExceptionTest.java
@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);
}
 
源代码3 项目: cloudstack   文件: RootCAProvider.java
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();
}
 
源代码4 项目: bumblebench   文件: SignatureBench.java
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;
}
 
源代码5 项目: nifi   文件: TlsCertificateAuthorityTest.java
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;
}
 
源代码6 项目: openjdk-jdk9   文件: NativeRSASignature.java
@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);
    }
}
 
源代码7 项目: UAF   文件: TestData.java
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"));
}
 
源代码8 项目: hadoop-ozone   文件: DefaultCertificateClient.java
/**
 * 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);
  }
}
 
@Test
public void testRSAAuthenticationToken()
    throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
  String tokenstr =
      "[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwg[email protected]WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=";
  RSAAuthenticationToken token = RSAAuthenticationToken.fromStr(tokenstr);
  String contents = token.plainToken();
  Assert.assertEquals(
      "[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ",
      contents);
  String sign = token.getSign();
  Assert.assertEquals(
      "WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=",
      sign);
  String pubKey =
      "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxKl5TNUTec7fL2degQcCk6vKf3c0wsfNK5V6elKzjWxm0MwbRj/UeR20VSnicBmVIOWrBS9LiERPPvjmmWUOSS2vxwr5XfhBhZ07gCAUNxBOTzgMo5nE45DhhZu5Jzt5qSV6o10Kq7+fCCBlDZ1UoWxZceHkUt5AxcrhEDulFjQIDAQAB";
  Assert.assertTrue(RSAUtils.verify(pubKey, sign, contents));
}
 
源代码10 项目: hottub   文件: InvalidBitString.java
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;
}
 
@Test(expectedExceptions = SignatureException.class)
public void fullEncryptionBadSignature() throws GeneralSecurityException {
    Map<String, AttributeValue> encryptedAttributes =
            encryptor.encryptAllFieldsExcept(Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
    assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
    encryptedAttributes.get("hashKey").setN("666");
    encryptor.decryptAllFieldsExcept(Collections.unmodifiableMap(encryptedAttributes), context, "hashKey", "rangeKey", "version");
}
 
源代码12 项目: hottub   文件: SignerOutputStream.java
@Override
public void write(int arg0) {
    super.write(arg0);
    try {
        sig.update((byte)arg0);
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    }
}
 
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);
  } 
}
 
源代码14 项目: openjdk-jdk8u   文件: SignatureFileVerifier.java
/**
 * 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;
    }
}
 
源代码15 项目: syncthing-android   文件: WebGuiActivity.java
/**
 * 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();
    }
}
 
源代码16 项目: ripple-lib-java   文件: X509CertificateObject.java
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);
}
 
源代码17 项目: jdk8u_jdk   文件: SignatureFileVerifier.java
/**
 * 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;
    }
}
 
源代码18 项目: openjdk-8   文件: SignatureDSA.java
/**
 * @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);
    }
}
 
源代码19 项目: openjdk-jdk8u-backup   文件: RSASignature.java
@Override
protected void engineUpdate(byte b) throws SignatureException {
    if (offset >= precomputedDigest.length) {
        offset = RAW_RSA_MAX + 1;
        return;
    }
    precomputedDigest[offset++] = b;
}
 
源代码20 项目: TorrentEngine   文件: JDKDigestSignature.java
protected void engineUpdate(
    byte[]  b,
    int     off,
    int     len) 
    throws SignatureException
{
    digest.update(b, off, len);
}
 
源代码21 项目: RipplePower   文件: X509V2CRLGenerator.java
/**
 * 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!");
    }
}
 
@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]));
}
 
/**
 * 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);
}
 
源代码24 项目: jdk8u-jdk   文件: Offsets.java
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);
}
 
源代码25 项目: commcare-android   文件: SigningUtil.java
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);
}
 
源代码26 项目: RipplePower   文件: X509V3CertificateGenerator.java
/**
 * 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);
}
 
源代码27 项目: gazpachoquest   文件: LoginShiroFilterTest.java
@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);
}
 
源代码28 项目: openjdk-jdk8u-backup   文件: SignatureECDSA.java
/** @inheritDoc */
protected void engineUpdate(byte[] input) throws XMLSignatureException {
    try {
        this.signatureAlgorithm.update(input);
    } catch (SignatureException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
 
源代码29 项目: ripple-lib-java   文件: X509V2CRLGenerator.java
/**
 * 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);
}
 
源代码30 项目: openjdk-8   文件: SignatureECDSA.java
/** @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);
    }
}