Search in sources :

Example 71 with Signature

use of java.security.Signature in project jdk8u_jdk by JetBrains.

the class SolarisShortDSA method use.

static boolean use(KeyPair kp) throws Exception {
    Signature sig = Signature.getInstance("SHA1withDSA");
    sig.initSign(kp.getPrivate());
    sig.update(data);
    byte[] signed = sig.sign();
    Signature sig2 = Signature.getInstance("SHA1withDSA");
    sig2.initVerify(kp.getPublic());
    sig2.update(data);
    return sig2.verify(signed);
}
Also used : Signature(java.security.Signature)

Example 72 with Signature

use of java.security.Signature in project jdk8u_jdk by JetBrains.

the class OidAlgorithmPair method runTest.

private void runTest(OidAlgorithmPair oidAlgorithmPair, KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    Signature sgAlgorithm = Signature.getInstance(oidAlgorithmPair.algorithm, provider);
    Signature sgOid = Signature.getInstance(oidAlgorithmPair.oid, provider);
    if (sgAlgorithm == null) {
        throw new RuntimeException(String.format("Test failed: algorithm string %s getInstance failed.%n", oidAlgorithmPair.algorithm));
    }
    if (sgOid == null) {
        throw new RuntimeException(String.format("Test failed: OID %s getInstance failed.%n", oidAlgorithmPair.oid));
    }
    if (!sgAlgorithm.getAlgorithm().equals(oidAlgorithmPair.algorithm)) {
        throw new RuntimeException(String.format("Test failed: algorithm string %s getInstance " + "doesn't generate expected algorithm.%n", oidAlgorithmPair.algorithm));
    }
    sgAlgorithm.initSign(keyPair.getPrivate());
    sgAlgorithm.update(INPUT);
    sgOid.initVerify(keyPair.getPublic());
    sgOid.update(INPUT);
    if (!sgOid.verify(sgAlgorithm.sign())) {
        throw new RuntimeException("Signature verification failed unexpectedly");
    }
}
Also used : Signature(java.security.Signature)

Example 73 with Signature

use of java.security.Signature in project jdk8u_jdk by JetBrains.

the class Basic method signAlias.

private static int signAlias(int testnum, String alias) throws Exception {
    if (ks == null) {
        ks = KeyStore.getInstance(KS_TYPE, provider);
        ks.load(null, tokenPwd);
    }
    if (alias == null) {
        Enumeration enu = ks.aliases();
        if (enu.hasMoreElements()) {
            alias = (String) enu.nextElement();
        }
    }
    PrivateKey pkey = (PrivateKey) ks.getKey(alias, null);
    if ("RSA".equals(pkey.getAlgorithm())) {
        System.out.println("got [" + alias + "] signing key: " + pkey);
    } else {
        throw new SecurityException("expected RSA, got " + pkey.getAlgorithm());
    }
    Signature s = Signature.getInstance("MD5WithRSA", ks.getProvider());
    s.initSign(pkey);
    System.out.println("initialized signature object with key");
    s.update("hello".getBytes());
    System.out.println("signature object updated with [hello] bytes");
    byte[] signed = s.sign();
    System.out.println("received signature " + signed.length + " bytes in length");
    Signature v = Signature.getInstance("MD5WithRSA", ks.getProvider());
    v.initVerify(ks.getCertificate(alias));
    v.update("hello".getBytes());
    v.verify(signed);
    System.out.println("signature verified");
    System.out.println("test " + testnum++ + " passed");
    return testnum;
}
Also used : PrivateKey(java.security.PrivateKey) Signature(java.security.Signature)

Example 74 with Signature

use of java.security.Signature in project android_frameworks_base by AOSPA.

the class ApkSignatureSchemeV2Verifier method verifySigner.

private static X509Certificate[] verifySigner(ByteBuffer signerBlock, Map<Integer, byte[]> contentDigests, CertificateFactory certFactory) throws SecurityException, IOException {
    ByteBuffer signedData = getLengthPrefixedSlice(signerBlock);
    ByteBuffer signatures = getLengthPrefixedSlice(signerBlock);
    byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock);
    int signatureCount = 0;
    int bestSigAlgorithm = -1;
    byte[] bestSigAlgorithmSignatureBytes = null;
    List<Integer> signaturesSigAlgorithms = new ArrayList<>();
    while (signatures.hasRemaining()) {
        signatureCount++;
        try {
            ByteBuffer signature = getLengthPrefixedSlice(signatures);
            if (signature.remaining() < 8) {
                throw new SecurityException("Signature record too short");
            }
            int sigAlgorithm = signature.getInt();
            signaturesSigAlgorithms.add(sigAlgorithm);
            if (!isSupportedSignatureAlgorithm(sigAlgorithm)) {
                continue;
            }
            if ((bestSigAlgorithm == -1) || (compareSignatureAlgorithm(sigAlgorithm, bestSigAlgorithm) > 0)) {
                bestSigAlgorithm = sigAlgorithm;
                bestSigAlgorithmSignatureBytes = readLengthPrefixedByteArray(signature);
            }
        } catch (IOException | BufferUnderflowException e) {
            throw new SecurityException("Failed to parse signature record #" + signatureCount, e);
        }
    }
    if (bestSigAlgorithm == -1) {
        if (signatureCount == 0) {
            throw new SecurityException("No signatures found");
        } else {
            throw new SecurityException("No supported signatures found");
        }
    }
    String keyAlgorithm = getSignatureAlgorithmJcaKeyAlgorithm(bestSigAlgorithm);
    Pair<String, ? extends AlgorithmParameterSpec> signatureAlgorithmParams = getSignatureAlgorithmJcaSignatureAlgorithm(bestSigAlgorithm);
    String jcaSignatureAlgorithm = signatureAlgorithmParams.first;
    AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithmParams.second;
    boolean sigVerified;
    try {
        PublicKey publicKey = KeyFactory.getInstance(keyAlgorithm).generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
        sig.initVerify(publicKey);
        if (jcaSignatureAlgorithmParams != null) {
            sig.setParameter(jcaSignatureAlgorithmParams);
        }
        sig.update(signedData);
        sigVerified = sig.verify(bestSigAlgorithmSignatureBytes);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | InvalidAlgorithmParameterException | SignatureException e) {
        throw new SecurityException("Failed to verify " + jcaSignatureAlgorithm + " signature", e);
    }
    if (!sigVerified) {
        throw new SecurityException(jcaSignatureAlgorithm + " signature did not verify");
    }
    // Signature over signedData has verified.
    byte[] contentDigest = null;
    signedData.clear();
    ByteBuffer digests = getLengthPrefixedSlice(signedData);
    List<Integer> digestsSigAlgorithms = new ArrayList<>();
    int digestCount = 0;
    while (digests.hasRemaining()) {
        digestCount++;
        try {
            ByteBuffer digest = getLengthPrefixedSlice(digests);
            if (digest.remaining() < 8) {
                throw new IOException("Record too short");
            }
            int sigAlgorithm = digest.getInt();
            digestsSigAlgorithms.add(sigAlgorithm);
            if (sigAlgorithm == bestSigAlgorithm) {
                contentDigest = readLengthPrefixedByteArray(digest);
            }
        } catch (IOException | BufferUnderflowException e) {
            throw new IOException("Failed to parse digest record #" + digestCount, e);
        }
    }
    if (!signaturesSigAlgorithms.equals(digestsSigAlgorithms)) {
        throw new SecurityException("Signature algorithms don't match between digests and signatures records");
    }
    int digestAlgorithm = getSignatureAlgorithmContentDigestAlgorithm(bestSigAlgorithm);
    byte[] previousSignerDigest = contentDigests.put(digestAlgorithm, contentDigest);
    if ((previousSignerDigest != null) && (!MessageDigest.isEqual(previousSignerDigest, contentDigest))) {
        throw new SecurityException(getContentDigestAlgorithmJcaDigestAlgorithm(digestAlgorithm) + " contents digest does not match the digest specified by a preceding signer");
    }
    ByteBuffer certificates = getLengthPrefixedSlice(signedData);
    List<X509Certificate> certs = new ArrayList<>();
    int certificateCount = 0;
    while (certificates.hasRemaining()) {
        certificateCount++;
        byte[] encodedCert = readLengthPrefixedByteArray(certificates);
        X509Certificate certificate;
        try {
            certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
        } catch (CertificateException e) {
            throw new SecurityException("Failed to decode certificate #" + certificateCount, e);
        }
        certificate = new VerbatimX509Certificate(certificate, encodedCert);
        certs.add(certificate);
    }
    if (certs.isEmpty()) {
        throw new SecurityException("No certificates listed");
    }
    X509Certificate mainCertificate = certs.get(0);
    byte[] certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded();
    if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
        throw new SecurityException("Public key mismatch between certificate and signature record");
    }
    return certs.toArray(new X509Certificate[certs.size()]);
}
Also used : ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) BufferUnderflowException(java.nio.BufferUnderflowException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) DirectByteBuffer(java.nio.DirectByteBuffer) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 75 with Signature

use of java.security.Signature in project geode by apache.

the class PKCSAuthInit method getCredentials.

@Override
public Properties getCredentials(final Properties securityProperties, final DistributedMember server, final boolean isPeer) throws AuthenticationFailedException {
    final String keyStorePath = securityProperties.getProperty(KEYSTORE_FILE_PATH);
    if (keyStorePath == null) {
        throw new AuthenticationFailedException("PKCSAuthInit: key-store file path property [" + KEYSTORE_FILE_PATH + "] not set.");
    }
    final String alias = securityProperties.getProperty(KEYSTORE_ALIAS);
    if (alias == null) {
        throw new AuthenticationFailedException("PKCSAuthInit: key alias name property [" + KEYSTORE_ALIAS + "] not set.");
    }
    final String keyStorePass = securityProperties.getProperty(KEYSTORE_PASSWORD);
    try {
        final KeyStore ks = KeyStore.getInstance("PKCS12");
        final char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
        final FileInputStream certificatefile = new FileInputStream(keyStorePath);
        try {
            ks.load(certificatefile, passPhrase);
        } finally {
            certificatefile.close();
        }
        final Key key = ks.getKey(alias, passPhrase);
        if (key instanceof PrivateKey) {
            final PrivateKey privKey = (PrivateKey) key;
            final X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
            final Signature sig = Signature.getInstance(cert.getSigAlgName());
            sig.initSign(privKey);
            sig.update(alias.getBytes("UTF-8"));
            final byte[] signatureBytes = sig.sign();
            final Properties newprops = new Properties();
            newprops.put(KEYSTORE_ALIAS, alias);
            newprops.put(SIGNATURE_DATA, signatureBytes);
            return newprops;
        } else {
            throw new AuthenticationFailedException("PKCSAuthInit: " + "Failed to load private key from the given file: " + keyStorePath);
        }
    } catch (Exception ex) {
        throw new AuthenticationFailedException("PKCSAuthInit: Exception while getting credentials: " + ex, ex);
    }
}
Also used : PrivateKey(java.security.PrivateKey) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) Signature(java.security.Signature) Properties(java.util.Properties) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) Key(java.security.Key) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException)

Aggregations

Signature (java.security.Signature)261 SignatureException (java.security.SignatureException)84 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)70 InvalidKeyException (java.security.InvalidKeyException)61 PublicKey (java.security.PublicKey)61 PrivateKey (java.security.PrivateKey)43 IOException (java.io.IOException)42 KeyFactory (java.security.KeyFactory)41 X509Certificate (java.security.cert.X509Certificate)26 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)23 KeyPair (java.security.KeyPair)19 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)19 GeneralSecurityException (java.security.GeneralSecurityException)16 KeyPairGenerator (java.security.KeyPairGenerator)16 MySignature1 (org.apache.harmony.security.tests.support.MySignature1)16 ByteArrayInputStream (java.io.ByteArrayInputStream)14 BigInteger (java.math.BigInteger)14 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)14 CertificateException (java.security.cert.CertificateException)14 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)14