Search in sources :

Example 21 with SignatureException

use of java.security.SignatureException in project XobotOS by xamarin.

the class PKCS10CertificationRequest method verify.

/**
     * verify the request using the passed in public key and the provider..
     */
public boolean verify(PublicKey pubKey, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    Signature sig;
    try {
        if (provider == null) {
            sig = Signature.getInstance(getSignatureName(sigAlgId));
        } else {
            sig = Signature.getInstance(getSignatureName(sigAlgId), provider);
        }
    } catch (NoSuchAlgorithmException e) {
        //
        if (oids.get(sigAlgId.getObjectId()) != null) {
            String signatureAlgorithm = (String) oids.get(sigAlgId.getObjectId());
            if (provider == null) {
                sig = Signature.getInstance(signatureAlgorithm);
            } else {
                sig = Signature.getInstance(signatureAlgorithm, provider);
            }
        } else {
            throw e;
        }
    }
    setSignatureParameters(sig, sigAlgId.getParameters());
    sig.initVerify(pubKey);
    try {
        sig.update(reqInfo.getEncoded(ASN1Encodable.DER));
    } catch (Exception e) {
        throw new SignatureException("exception encoding TBS cert request - " + e);
    }
    return sig.verify(sigBits.getBytes());
}
Also used : Signature(java.security.Signature) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DERBitString(org.bouncycastle.asn1.DERBitString) SignatureException(java.security.SignatureException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) GeneralSecurityException(java.security.GeneralSecurityException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 22 with SignatureException

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

the class SignatureTest method main.

public static void main(String[] args) throws Exception {
    String testAlg = args[0];
    int testSize = Integer.parseInt(args[1]);
    byte[] data = new byte[100];
    RandomFactory.getRandom().nextBytes(data);
    // create a key pair
    KeyPair kpair = generateKeys(KEYALG, testSize);
    Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());
    Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());
    // For signature algorithm, create and verify a signature
    Arrays.stream(privs).forEach(priv -> Arrays.stream(pubs).forEach(pub -> {
        try {
            checkSignature(data, (PublicKey) pub, (PrivateKey) priv, testAlg);
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException ex) {
            throw new RuntimeException(ex);
        }
    }));
}
Also used : KeyPairGenerator(java.security.KeyPairGenerator) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SignatureException(java.security.SignatureException) Signature(java.security.Signature) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeyFactory(java.security.KeyFactory) Key(java.security.Key) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) PUBLIC_KEY(javax.crypto.Cipher.PUBLIC_KEY) RSAPublicKey(java.security.interfaces.RSAPublicKey) RandomFactory(jdk.testlibrary.RandomFactory) PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) InvalidKeyException(java.security.InvalidKeyException) PRIVATE_KEY(javax.crypto.Cipher.PRIVATE_KEY) NoSuchProviderException(java.security.NoSuchProviderException) KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) RSAPublicKey(java.security.interfaces.RSAPublicKey) PrivateKey(java.security.PrivateKey)

Example 23 with SignatureException

use of java.security.SignatureException 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 24 with SignatureException

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

the class AndroidKeyStoreSignatureSpiBase method engineSign.

@Override
protected final byte[] engineSign() throws SignatureException {
    if (mCachedException != null) {
        throw new SignatureException(mCachedException);
    }
    byte[] signature;
    try {
        ensureKeystoreOperationInitialized();
        byte[] additionalEntropy = KeyStoreCryptoOperationUtils.getRandomBytesToMixIntoKeystoreRng(appRandom, getAdditionalEntropyAmountForSign());
        signature = mMessageStreamer.doFinal(EmptyArray.BYTE, 0, 0, // no signature provided -- it'll be generated by this invocation
        null, additionalEntropy);
    } catch (InvalidKeyException | KeyStoreException e) {
        throw new SignatureException(e);
    }
    resetWhilePreservingInitState();
    return signature;
}
Also used : SignatureException(java.security.SignatureException) KeyStoreException(android.security.KeyStoreException) InvalidKeyException(java.security.InvalidKeyException)

Example 25 with SignatureException

use of java.security.SignatureException in project oxAuth by GluuFederation.

the class UserInfoRestWebServiceImpl method requestUserInfo.

public Response requestUserInfo(String accessToken, String authorization, HttpServletRequest request, SecurityContext securityContext) {
    if (authorization != null && !authorization.isEmpty() && authorization.startsWith("Bearer ")) {
        accessToken = authorization.substring(7);
    }
    log.debug("Attempting to request User Info, Access token = {}, Is Secure = {}", accessToken, securityContext.isSecure());
    Response.ResponseBuilder builder = Response.ok();
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.USER_INFO);
    try {
        if (!UserInfoParamsValidator.validateParams(accessToken)) {
            builder = Response.status(400);
            builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_REQUEST));
        } else {
            AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
            if (authorizationGrant == null) {
                builder = Response.status(400);
                builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_TOKEN));
            } else if (authorizationGrant.getAuthorizationGrantType() == AuthorizationGrantType.CLIENT_CREDENTIALS) {
                builder = Response.status(403);
                builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE));
            } else if (!authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString()) && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) {
                builder = Response.status(403);
                builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE));
                oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, false);
            } else {
                oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
                CacheControl cacheControl = new CacheControl();
                cacheControl.setPrivate(true);
                cacheControl.setNoTransform(false);
                cacheControl.setNoStore(true);
                builder.cacheControl(cacheControl);
                builder.header("Pragma", "no-cache");
                User currentUser = authorizationGrant.getUser();
                try {
                    currentUser = userService.getUserByDn(authorizationGrant.getUserDn());
                } catch (EntryPersistenceException ex) {
                    log.warn("Failed to reload user entry: '{}'", authorizationGrant.getUserDn());
                }
                if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) {
                    KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg());
                    BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc());
                    builder.type("application/jwt");
                    builder.entity(getJweResponse(keyEncryptionAlgorithm, blockEncryptionAlgorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
                } else if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) {
                    SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(authorizationGrant.getClient().getUserInfoSignedResponseAlg());
                    builder.type("application/jwt");
                    builder.entity(getJwtResponse(algorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
                } else {
                    builder.type((MediaType.APPLICATION_JSON + ";charset=UTF-8"));
                    builder.entity(getJSonResponse(currentUser, authorizationGrant, authorizationGrant.getScopes()));
                }
            }
        }
    } catch (StringEncrypter.EncryptionException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (InvalidJwtException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (SignatureException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (InvalidClaimException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) OAuth2AuditLog(org.xdi.oxauth.model.audit.OAuth2AuditLog) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) SignatureAlgorithm(org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm) SignatureException(java.security.SignatureException) InvalidClaimException(org.xdi.oxauth.model.exception.InvalidClaimException) StringEncrypter(org.xdi.util.security.StringEncrypter) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) SignatureException(java.security.SignatureException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidClaimException(org.xdi.oxauth.model.exception.InvalidClaimException) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) BlockEncryptionAlgorithm(org.xdi.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm) JsonWebResponse(org.xdi.oxauth.model.token.JsonWebResponse) Response(javax.ws.rs.core.Response) KeyEncryptionAlgorithm(org.xdi.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) CacheControl(javax.ws.rs.core.CacheControl)

Aggregations

SignatureException (java.security.SignatureException)329 InvalidKeyException (java.security.InvalidKeyException)171 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)132 Signature (java.security.Signature)132 IOException (java.io.IOException)75 PublicKey (java.security.PublicKey)53 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)39 X509Certificate (java.security.cert.X509Certificate)33 BigInteger (java.math.BigInteger)32 CertificateException (java.security.cert.CertificateException)31 NoSuchProviderException (java.security.NoSuchProviderException)29 PrivateKey (java.security.PrivateKey)25 ByteArrayInputStream (java.io.ByteArrayInputStream)17 KeyFactory (java.security.KeyFactory)15 ArrayList (java.util.ArrayList)15 MySignature1 (org.apache.harmony.security.tests.support.MySignature1)14 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)12 GeneralSecurityException (java.security.GeneralSecurityException)12 MessageDigest (java.security.MessageDigest)12