Example usage for java.security Signature getInstance

List of usage examples for java.security Signature getInstance

Introduction

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

Prototype

public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Sign provided data with specified private key and algortihm
 * /*from  ww  w  . j  a v  a  2s  .  co  m*/
 * @param privateKey
 *            the private key
 * @param signatureAlgorithm a valid signature algorithm
 * @param data
 *            the data to sign
 * @return the signature
 */
public static byte[] signData(final PrivateKey privateKey, final String signatureAlgorithm, final byte[] data)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    final Signature signer = Signature.getInstance(signatureAlgorithm);
    signer.initSign(privateKey);
    signer.update(data);
    return (signer.sign());
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Verify signed data with specified public key, algorith and signature
 * /*  w w w  .ja  va 2  s  . c o  m*/
 * @param publicKey
 *            the public key
 * @param signatureAlgorithm a valid signature algorithm
 * @param data
 *            the data to verify
 * @param signature
 *            the signature
 * @return true if the signature is ok
 */
public static boolean verifyData(final PublicKey publicKey, final String signatureAlgorithm, final byte[] data,
        final byte[] signature) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    final Signature signer = Signature.getInstance(signatureAlgorithm);
    signer.initVerify(publicKey);
    signer.update(data);
    return (signer.verify(signature));

}

From source file:org.globus.myproxy.MyProxy.java

private InputStream handleReply(InputStream in, OutputStream out, GSSCredential authzcreds,
        boolean wantTrustroots) throws IOException, MyProxyException {
    String tmp = null;/*  ww  w . j  a v a 2 s  .  c  om*/

    /* there was something weird here with the
       received protocol version sometimes. it
       contains an extra <32 byte. fixed it by
       using endsWith. now i read extra byte at the
       end of each message.
    */

    // protocol version
    tmp = readLine(in);
    if (tmp == null) {
        throw new EOFException();
    }
    if (!tmp.endsWith(MyProxyConstants.VERSION)) {
        throw new MyProxyException("Protocol version mismatch: " + tmp);
    }

    // response
    tmp = readLine(in);
    if (tmp == null) {
        throw new EOFException();
    }

    if (!tmp.startsWith(RESPONSE)) {
        throw new MyProxyException("Invalid reply: no response message");
    }

    boolean error = tmp.charAt(RESPONSE.length()) == '1';
    boolean authzchallenge = tmp.charAt(RESPONSE.length()) == '2';

    if (error) {
        StringBuffer errorStr = new StringBuffer();
        while ((tmp = readLine(in)) != null) {
            if (tmp.startsWith(ERROR)) {
                if (errorStr.length() > 0)
                    errorStr.append(' ');
                errorStr.append(tmp.substring(ERROR.length()));
            }
        }
        if (errorStr.length() == 0) {
            errorStr.append("unspecified server error");
        }
        throw new MyProxyException(errorStr.toString());
    }
    if (authzchallenge) {
        if (authzcreds == null) {
            throw new MyProxyException(
                    "Unable to respond to server's authentication challenge. No credentials for renewal.");
        }
        if (out == null) {
            throw new MyProxyException("Internal error. Authz challenge but no OutputStream.");
        }
        String[] authzdata = null;
        while ((tmp = readLine(in)) != null) {
            if (tmp.startsWith(AUTHZ_DATA)) {
                int pos = tmp.indexOf(':', AUTHZ_DATA.length() + 1);
                if (pos != -1) {
                    authzdata = new String[2];
                    authzdata[0] = tmp.substring(AUTHZ_DATA.length(), pos).trim();
                    authzdata[1] = tmp.substring(pos + 1).trim();
                }
                if (authzdata == null) {
                    throw new MyProxyException("Unable to parse authorization challenge from server.");
                }
                if (authzdata[0].equals("X509_certificate")) {
                    GlobusGSSCredentialImpl pkiCred = (GlobusGSSCredentialImpl) authzcreds;
                    try {
                        Signature sig = Signature.getInstance("SHA1withRSA");
                        sig.initSign(pkiCred.getPrivateKey());
                        sig.update(authzdata[1].getBytes());
                        byte[] sigbytes = sig.sign();
                        X509Certificate[] certs = pkiCred.getCertificateChain();
                        ByteArrayOutputStream buffer = new ByteArrayOutputStream(2048);
                        buffer.write(2); // AUTHORIZETYPE_CERT
                        buffer.write(0);
                        buffer.write(0);
                        buffer.write(0); // pad
                        DataOutputStream dos = new DataOutputStream(buffer);
                        dos.writeInt(sigbytes.length);
                        dos.flush();
                        buffer.write(sigbytes);
                        buffer.write((byte) certs.length);
                        for (int i = 0; i < certs.length; i++) {
                            buffer.write(certs[i].getEncoded());
                        }
                        out.write(buffer.toByteArray());
                        out.flush();
                    } catch (Exception e) {
                        throw new MyProxyException("Authz response failed.", e);
                    }
                } else {
                    authzdata = null;
                    continue;
                }
            }
        }

        return handleReply(in, out, authzcreds, wantTrustroots);

    }

    if (wantTrustroots == true) {
        while ((tmp = readLine(in)) != null) {
            if (tmp.startsWith(TRUSTROOTS)) {
                String filenameList = tmp.substring(TRUSTROOTS.length());
                this.trustrootFilenames = filenameList.split(",");
                this.trustrootData = new String[this.trustrootFilenames.length];
                for (int i = 0; i < this.trustrootFilenames.length; i++) {
                    String lineStart = "FILEDATA_" + this.trustrootFilenames[i] + "=";
                    tmp = readLine(in);
                    if (tmp == null) {
                        throw new EOFException();
                    }
                    if (!tmp.startsWith(lineStart)) {
                        throw new MyProxyException("bad MyProxy protocol RESPONSE: expecting " + lineStart
                                + " but received " + tmp);
                    }
                    this.trustrootData[i] = new String(
                            Base64.decode(tmp.substring(lineStart.length()).getBytes()));
                }
            }
        }
    }

    /* always consume the entire message */
    int avail = in.available();
    byte[] b = new byte[avail];
    if (avail > 0)
        in.read(b);

    ByteArrayInputStream inn = new ByteArrayInputStream(b);

    return inn;
}

From source file:com.threerings.getdown.data.Application.java

/**
 * Downloads a new copy of the specified control file, optionally validating its signature.
 * If the download is successful, moves it over the old file on the filesystem.
 *
 * <p> We implement simple signing of the digest.txt file for use with the Getdown applet, but
 * this should never be used as-is with a non-applet getdown installation, as the signing
 * format has no provisions for declaring arbitrary signing key IDs, signature algorithm, et al
 * -- it is entirely reliant on the ability to upgrade the Getdown applet, and its signature
 * validation implementation, at-will (ie, via an Applet).
 *
 * <p> TODO: Switch to PKCS #7 or CMS.
 *//*from  w  ww .  j  a v a2 s . c o  m*/
protected void downloadControlFile(String path, boolean validateSignature) throws IOException {
    File target = downloadFile(path);

    if (validateSignature) {
        if (_signers.isEmpty()) {
            log.info("No signers, not verifying file", "path", path);

        } else {
            File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
            byte[] signature = null;
            FileReader reader = null;
            try {
                reader = new FileReader(signatureFile);
                signature = StreamUtil.toByteArray(new FileInputStream(signatureFile));
            } finally {
                StreamUtil.close(reader);
                signatureFile.delete(); // delete the file regardless
            }

            byte[] buffer = new byte[8192];
            int length, validated = 0;
            for (Certificate cert : _signers) {
                FileInputStream dataInput = null;
                try {
                    dataInput = new FileInputStream(target);
                    Signature sig = Signature.getInstance("SHA1withRSA");
                    sig.initVerify(cert);
                    while ((length = dataInput.read(buffer)) != -1) {
                        sig.update(buffer, 0, length);
                    }

                    if (!sig.verify(Base64.decodeBase64(signature))) {
                        log.info("Signature does not match", "cert", cert.getPublicKey());
                        continue;
                    } else {
                        log.info("Signature matches", "cert", cert.getPublicKey());
                        validated++;
                    }

                } catch (IOException ioe) {
                    log.warning("Failure validating signature of " + target + ": " + ioe);

                } catch (GeneralSecurityException gse) {
                    // no problem!

                } finally {
                    StreamUtil.close(dataInput);
                    dataInput = null;
                }
            }

            // if we couldn't find a key that validates our digest, we are the hosed!
            if (validated == 0) {
                // delete the temporary digest file as we know it is invalid
                target.delete();
                throw new IOException("m.corrupt_digest_signature_error");
            }
        }
    }

    // now move the temporary file over the original
    File original = getLocalPath(path);
    if (!FileUtil.renameTo(target, original)) {
        throw new IOException("Failed to rename(" + target + ", " + original + ")");
    }
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

public static Properties readCredentials(DataInputStream dis, DataOutputStream dos, DistributedSystem system,
        SecurityService securityService) throws GemFireSecurityException, IOException {

    boolean requireAuthentication = securityService.isClientSecurityRequired();
    Properties credentials = null;
    try {//from ww  w. ja  v  a  2  s  .  c om
        byte secureMode = dis.readByte();
        throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE);
        if (secureMode == CREDENTIALS_NORMAL) {
            if (requireAuthentication) {
                credentials = DataSerializer.readProperties(dis);
            } else {
                DataSerializer.readProperties(dis); // ignore the credentials
            }
        } else if (secureMode == CREDENTIALS_DHENCRYPT) {
            boolean sendAuthentication = dis.readBoolean();
            InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter();
            // Get the symmetric encryption algorithm to be used
            String skAlgo = DataSerializer.readString(dis);
            // Get the public key of the other side
            byte[] keyBytes = DataSerializer.readByteArray(dis);
            byte[] challenge = null;
            PublicKey pubKey = null;
            if (requireAuthentication) {
                // Generate PublicKey from encoded form
                X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
                KeyFactory keyFact = KeyFactory.getInstance("DH");
                pubKey = keyFact.generatePublic(x509KeySpec);

                // Send the public key to other side
                keyBytes = dhPublicKey.getEncoded();
                challenge = new byte[64];
                random.nextBytes(challenge);

                // If the server has to also authenticate itself then
                // sign the challenge from client.
                if (sendAuthentication) {
                    // Get the challenge string from client
                    byte[] clientChallenge = DataSerializer.readByteArray(dis);
                    if (privateKeyEncrypt == null) {
                        throw new AuthenticationFailedException(
                                LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE
                                        .toLocalizedString());
                    }
                    // Sign the challenge from client and send it to the client
                    Signature sig = Signature.getInstance(privateKeySignAlgo);
                    sig.initSign(privateKeyEncrypt);
                    sig.update(clientChallenge);
                    byte[] signedBytes = sig.sign();
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                    // DataSerializer.writeString(privateKeyAlias, dos);
                    DataSerializer.writeString(privateKeySubject, dos);
                    DataSerializer.writeByteArray(signedBytes, dos);
                    securityLogWriter.fine("HandShake: sent the signed client challenge");
                } else {
                    // These two lines should not be moved before the if{} statement in
                    // a common block for both if...then...else parts. This is to handle
                    // the case when an AuthenticationFailedException is thrown by the
                    // if...then part when sending the signature.
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                }
                // Now send the server challenge
                DataSerializer.writeByteArray(challenge, dos);
                securityLogWriter.fine("HandShake: sent the public key and challenge");
                dos.flush();

                // Read and decrypt the credentials
                byte[] encBytes = DataSerializer.readByteArray(dis);
                KeyAgreement ka = KeyAgreement.getInstance("DH");
                ka.init(dhPrivateKey);
                ka.doPhase(pubKey, true);

                Cipher decrypt;

                int keysize = getKeySize(skAlgo);
                int blocksize = getBlockSize(skAlgo);

                if (keysize == -1 || blocksize == -1) {
                    SecretKey sKey = ka.generateSecret(skAlgo);
                    decrypt = Cipher.getInstance(skAlgo);
                    decrypt.init(Cipher.DECRYPT_MODE, sKey);
                } else {
                    String algoStr = getDhAlgoStr(skAlgo);

                    byte[] sKeyBytes = ka.generateSecret();
                    SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr);
                    IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize);

                    decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding");
                    decrypt.init(Cipher.DECRYPT_MODE, sks, ivps);
                }

                byte[] credentialBytes = decrypt.doFinal(encBytes);
                ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes);
                DataInputStream dinp = new DataInputStream(bis);
                credentials = DataSerializer.readProperties(dinp);
                byte[] challengeRes = DataSerializer.readByteArray(dinp);
                // Check the challenge string
                if (!Arrays.equals(challenge, challengeRes)) {
                    throw new AuthenticationFailedException(
                            LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT
                                    .toLocalizedString());
                }
                dinp.close();
            } else {
                if (sendAuthentication) {
                    // Read and ignore the client challenge
                    DataSerializer.readByteArray(dis);
                }
                dos.writeByte(REPLY_AUTH_NOT_REQUIRED);
                dos.flush();
            }
        } else if (secureMode == SECURITY_MULTIUSER_NOTIFICATIONCHANNEL) {
            // hitesh there will be no credential CCP will get credential(Principal) using
            // ServerConnection..
            logger.debug("readCredential where multiuser mode creating callback connection");
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException(
                LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex);
    }
    return credentials;
}

From source file:com.netscape.ca.CertificateAuthority.java

/**
 * Create a new lightweight authority signed by this authority.
 *
 * This method DOES NOT add the new CA to caMap; it is the
 * caller's responsibility./*w w  w . j  a v a  2s.com*/
 */
public ICertificateAuthority createSubCA(IAuthToken authToken, String subjectDN, String description)
        throws EBaseException {

    ensureReady();

    // check requested DN
    X500Name subjectX500Name = null;
    try {
        subjectX500Name = new X500Name(subjectDN);
    } catch (IOException e) {
        throw new IllegalArgumentException("Invalid Subject DN: " + subjectDN);
    }
    ensureAuthorityDNAvailable(subjectX500Name);

    // generate authority ID and nickname
    AuthorityID aid = new AuthorityID();
    String aidString = aid.toString();
    String nickname = hostCA.getNickname() + " " + aidString;

    // build database entry
    String dn = "cn=" + aidString + "," + authorityBaseDN();
    logger.debug("createSubCA: DN = " + dn);
    String parentDNString = null;
    try {
        parentDNString = mName.toLdapDNString();
    } catch (IOException e) {
        throw new EBaseException("Failed to convert issuer DN to string: " + e);
    }

    String thisClone = CMS.getEEHost() + ":" + CMS.getEESSLPort();

    LDAPAttribute[] attrs = { new LDAPAttribute("objectclass", "authority"), new LDAPAttribute("cn", aidString),
            new LDAPAttribute("authorityID", aidString), new LDAPAttribute("authorityKeyNickname", nickname),
            new LDAPAttribute("authorityKeyHost", thisClone), new LDAPAttribute("authorityEnabled", "TRUE"),
            new LDAPAttribute("authorityDN", subjectDN),
            new LDAPAttribute("authorityParentDN", parentDNString) };
    LDAPAttributeSet attrSet = new LDAPAttributeSet(attrs);
    if (this.authorityID != null)
        attrSet.add(new LDAPAttribute("authorityParentID", this.authorityID.toString()));
    if (description != null)
        attrSet.add(new LDAPAttribute("description", description));
    LDAPEntry ldapEntry = new LDAPEntry(dn, attrSet);

    addAuthorityEntry(aid, ldapEntry);

    X509CertImpl cert = null;

    try {
        // Generate signing key
        CryptoManager cryptoManager = CryptoManager.getInstance();
        // TODO read PROP_TOKEN_NAME config
        CryptoToken token = cryptoManager.getInternalKeyStorageToken();
        // TODO algorithm parameter
        KeyPairGenerator gen = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
        gen.initialize(2048);
        KeyPair keypair = gen.genKeyPair();
        PublicKey pub = keypair.getPublic();
        X509Key x509key = CryptoUtil.convertPublicKeyToX509Key(pub);

        // Create pkcs10 request
        logger.debug("createSubCA: creating pkcs10 request");
        PKCS10 pkcs10 = new PKCS10(x509key);
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(keypair.getPrivate());
        pkcs10.encodeAndSign(new X500Signer(signature, subjectX500Name));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pkcs10.print(new PrintStream(out));
        String pkcs10String = out.toString();

        // Sign certificate
        Locale locale = Locale.getDefault();
        String profileId = "caCACert";
        IProfileSubsystem ps = (IProfileSubsystem) CMS.getSubsystem(IProfileSubsystem.ID);
        IProfile profile = ps.getProfile(profileId);
        ArgBlock argBlock = new ArgBlock();
        argBlock.set("cert_request_type", "pkcs10");
        argBlock.set("cert_request", pkcs10String);
        CertEnrollmentRequest certRequest = CertEnrollmentRequestFactory.create(argBlock, profile, locale);
        EnrollmentProcessor processor = new EnrollmentProcessor("createSubCA", locale);
        Map<String, Object> resultMap = processor.processEnrollment(certRequest, null, authorityID, null,
                authToken);
        IRequest requests[] = (IRequest[]) resultMap.get(CAProcessor.ARG_REQUESTS);
        IRequest request = requests[0];
        Integer result = request.getExtDataInInteger(IRequest.RESULT);
        if (result != null && !result.equals(IRequest.RES_SUCCESS))
            throw new EBaseException(
                    "createSubCA: certificate request submission resulted in error: " + result);
        RequestStatus requestStatus = request.getRequestStatus();
        if (requestStatus != RequestStatus.COMPLETE) {
            // The request did not complete.  Inference: something
            // incorrect in the request (e.g. profile constraint
            // violated).
            String msg = "Failed to issue CA certificate. Final status: " + requestStatus + ".";
            String errorMsg = request.getExtDataInString(IRequest.ERROR);
            if (errorMsg != null)
                msg += " Additional info: " + errorMsg;
            throw new BadRequestDataException(msg);
        }

        // Add certificate to nssdb
        cert = request.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT);
        cryptoManager.importCertPackage(cert.getEncoded(), nickname);
    } catch (Exception e) {
        // something went wrong; delete just-added entry
        logger.error("Error creating lightweight CA certificate: " + e.getMessage(), e);

        try {
            deleteAuthorityEntry(aid);
        } catch (ELdapException e2) {
            // we are about to throw ECAException, so just
            // log this error.
            logger.error("Error deleting new authority entry after failure during certificate generation: "
                    + e2.getMessage(), e2);
        }
        if (e instanceof BadRequestDataException)
            throw (BadRequestDataException) e; // re-throw
        else
            throw new ECAException("Error creating lightweight CA certificate: " + e, e);
    }

    CertificateAuthority ca = new CertificateAuthority(hostCA, subjectX500Name, aid, this.authorityID,
            cert.getSerialNumber(), nickname, Collections.singleton(thisClone), description, true);

    // Update authority record with serial of issued cert
    LDAPModificationSet mods = new LDAPModificationSet();
    mods.add(LDAPModification.REPLACE, new LDAPAttribute("authoritySerial", cert.getSerialNumber().toString()));
    ca.modifyAuthorityEntry(mods);

    return ca;
}