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.codice.ddf.commands.util.DigitalSignature.java

public boolean verifyDigitalSignature(InputStream data, InputStream signature, String certificateAlias)
        throws IOException {
    byte[] sigToVerify = IOUtils.toByteArray(signature);

    Certificate certificate = getCertificate(certificateAlias);

    if (certificate == null) {
        throw new CatalogCommandRuntimeException("Unable to retrieve certificate");
    }/*from w w  w.  j  a  v a2s.c  om*/

    try {
        Signature rsa = Signature.getInstance("SHA256withRSA");
        rsa.initVerify(certificate);

        byte[] buffer = new byte[BUFFER_SIZE];
        int len;

        while ((len = data.read(buffer)) >= 0) {
            rsa.update(buffer, OFFSET, len);
        }

        return rsa.verify(sigToVerify);
    } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) {
        String message = "An error occurred while verifying file";
        LOGGER.debug(message, e);
        throw new CatalogCommandRuntimeException(message, e);
    }
}

From source file:org.apache.james.jmap.crypto.JamesSignatureHandler.java

@Override
public String sign(String source) {
    Preconditions.checkNotNull(source);/*from   w w w .ja  v  a  2s .  c o m*/
    try {
        Signature javaSignature = Signature.getInstance(ALGORITHM);
        javaSignature.initSign(privateKey);
        javaSignature.update(source.getBytes());
        return new Base64().encodeAsString(javaSignature.sign());
    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.turo.pushy.apns.auth.ApnsVerificationKey.java

/**
 * Constructs a new verification key with the given key identifier, team identifier, and elliptic curve private key.
 *
 * @param keyId the ten-character, Apple-issued identifier for the key itself
 * @param teamId the ten-character, Apple-issued identifier for the team to which the key belongs
 * @param key the elliptic curve private key underpinning this signing key
 *
 * @throws NoSuchAlgorithmException if the {@value APNS_SIGNATURE_ALGORITHM} algorith is not supported by the JVM
 * @throws InvalidKeyException if the given elliptic curve private key is invalid for any reason
 */// w ww  .j ava  2s .c om
public ApnsVerificationKey(final String keyId, final String teamId, final ECPublicKey key)
        throws NoSuchAlgorithmException, InvalidKeyException {
    super(keyId, teamId, key);

    // This is a little goofy, but we want to check early for missing algorithms or bogus keys, and the most direct
    // way to do that is to try to actually use the key to create a signature.
    final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM);
    signature.initVerify(key);
}

From source file:acceptable_risk.nik.uniobuda.hu.andrawid.util.Security.java

/**
 * Verifies that the signature from the server matches the computed
 * signature on the data.  Returns true if the data is correctly signed.
 *
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature/*from w w  w.java  2  s  .  c  o m*/
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
    Signature sig;
    try {
        sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(publicKey);
        sig.update(signedData.getBytes());
        if (!sig.verify(Base64.decode(signature))) {
            Log.e(TAG, "Signature verification failed.");
            return false;
        }
        return true;
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException.");
    } catch (InvalidKeyException e) {
        Log.e(TAG, "Invalid key specification.");
    } catch (SignatureException e) {
        Log.e(TAG, "Signature exception.");
    } catch (Base64DecoderException e) {
        Log.e(TAG, "Base64 decoding failed.");
    }
    return false;
}

From source file:Version2LicenseDecoder.java

public static void main(String[] args) throws IOException, Exception {
    new Version2LicenseDecoder();
    String lll = "AAABDA0ODAoPeNptUEtPg0AQvu+vIPG8ZsEKlmQPFda6DVAENB68rHTUbdotmQVi/71QTHykh5lM5nvMl7m4Q+2sOuOwwGHz8PomnDFnmVaOx9wrEoOtUTetPhi+ksXiJXREr3adGjckQjgNsWqBj3zKfMoCstWoLhNdg7EgNvqkFlkliryQpSA/DrzFDv7Qq2MDmdoDj9ZpKopILpIJV3Wre5gEu4n7BGhHE4+kSpsWjDI1iM9G4/FXomBMtMZ3ZbSdjm4PWpnN0M1knXX7V8D126MdDDl1SQnYA8qY31b5A5WRLKgfP0d0du8uSSkyPhRNPJ/5njcn38kHeiLjc8j5SHmH9Yey8P95XxVof60wKwITfDIxHZPgo323OEKd2FJ4BXvU7wIUIbLvXQNrkIAf4AL2Aeu4ZBRbTOA=X02dl";
    String lls = "AAABckRlc2NyaXB0aW9uPUpJUkE6IENvbW1lcmNpYWwKQ3JlYXRpb25EYXRlPTIwMTMtMDYtMDcKamlyYS5MaWNlbnNlRWRpdGlvbj1FTlRFUlBSSVNFCkV2YWx1YXRpb249ZmFsc2UKamlyYS5MaWNlbnNlVHlwZU5hbWU9Q09NTUVSQ0lBTApqaXJhLmFjdGl2ZT10cnVlCmxpY2Vuc2VWZXJzaW9uPTIKTWFpbnRlbmFuY2VFeHBpcnlEYXRlPTIwOTktMDYtMDcKT3JnYW5pc2F0aW9uPWpvaWFuZGpvaW4KU0VOPVNFTi1MMjYwNjIyOQpTZXJ2ZXJJRD1CVFBRLUlDSVItNkRYQy00SDFHCmppcmEuTnVtYmVyT2ZVc2Vycz0tMQpMaWNlbnNlSUQ9TElEU0VOLUwyNjA2MjI5CkxpY2Vuc2VFeHBpcnlEYXRlPTIwOTktMDYtMDcKUHVyY2hhc2VEYXRlPTIwMTMtMDYtMDc=X02g4";
    //      String sll = "Description=JIRA:Commercial\nCreationDate=2013-06-07\njira.LicenseEdition=ENTERPRISE\nEvaluation=false\njira.LicenseTypeName=COMMERCIAL\njira.active=true\nlicenseVersion=2\nMaintenanceExpiryDate=2099-06-07\nOrganisation=joiandjoin\nSEN=SEN-L2606229\nServerID=BTPQ-ICIR-6DXC-4H1G\njira.NumberOfUsers=-1\nLicenseID=LIDSEN-L2606229\nLicenseExpiryDate=2099-06-07\nPurchaseDate=2013-06-07";
    //      String sll = "com.allenta.jira.plugins.gitlab.gitlab-listener.enterprise=true\nDescription=GitLab Listener\\: Evaluation\nNumberOfUsers=-1\nCreationDate=2015-12-29\nContactEMail=xwturing@gmail.com\nEvaluation=true\ncom.allenta.jira.plugins.gitlab.gitlab-listener.Starter=false\nlicenseVersion=2\nMaintenanceExpiryDate=2099-01-27\nOrganisation=Evaluation license\nSEN=SEN-L7030895\ncom.allenta.jira.plugins.gitlab.gitlab-listener.active=true\nLicenseExpiryDate=2099-01-27\nLicenseTypeName=COMMERCIAL\nPurchaseDate=2015-12-29\n";
    //      String sll = "jira.product.jira-servicedesk.active=true\njira.product.jira-servicedesk.Starter=false\nNumberOfUsers=-1\nPurchaseDate=2016-01-05\ncom.atlassian.servicedesk.active=true\nLicenseTypeName=COMMERCIAL\nLicenseExpiryDate=2099-02-03\nContactEMail=xwturing@gmail.com\nServerID=BWGW-FKTG-N1UQ-PNHH\ncom.atlassian.servicedesk.LicenseTypeName=COMMERCIAL\njira.product.jira-servicedesk.NumberOfUsers=-1\nMaintenanceExpiryDate=2099-02-03\ncom.atlassian.servicedesk.enterprise=true\nLicenseID=LIDSEN-L7059162\nSEN=SEN-L7059162\nOrganisation=Evaluation license\nCreationDate=2016-01-05\ncom.atlassian.servicedesk.numRoleCount=-1\nlicenseVersion=2\nDescription=JIRA Service Desk (Server)\\: Evaluation\nEvaluation=true";
    String sll = "NumberOfUsers=-1\n" + "jira.product.jira-core.NumberOfUsers=-1\n" + "jira.NumberOfUsers=-1\n"
            + "PurchaseDate=2016-02-20\n" + "LicenseTypeName=COMMERCIAL\n" + "LicenseExpiryDate=2099-03-21\n"
            + "ContactEMail=xwturing@gmail.com\n" + "ServerID=BVDW-Q5Y0-CRXH-AI3I\n"
            + "jira.product.jira-core.Starter=false\n" + "jira.LicenseEdition=ENTERPRISE\n"
            + "jira.product.jira-core.active=true\n" + "MaintenanceExpiryDate=2099-03-21\n"
            + "LicenseID=LIDSEN-L7336401\n" + "SEN=SEN-L7336401\n" + "Organisation=Evaluation license\n"
            + "CreationDate=2016-02-20\n" + "licenseVersion=2\n"
            + "Description=JIRA Core (Server)\\: Evaluation\n" + "jira.active=true\n"
            + "jira.LicenseTypeName=COMMERCIAL\n" + "Evaluation=true";

    byte[] allData = sll.getBytes();
    Signature signature = Signature.getInstance("SHA1withDSA");
    signature.initVerify(PUBLIC_KEY);/*from   w  w  w. j  a  va 2s.  c  o m*/
    signature.update(allData);
    ByteArrayInputStream in = new ByteArrayInputStream(allData);
    DataInputStream dIn = new DataInputStream(in);
    int textLength = dIn.readInt();
    byte[] licenseText = new byte[textLength];
    dIn.read(licenseText);
    byte[] hash = new byte[dIn.available()];
    dIn.read(hash);
    String result = packLicense(allData, hash);
    System.out.println(result);
}

From source file:no.digipost.api.client.filters.response.ResponseSignatureFilter.java

@Override
public void filter(final ClientRequestContext clientRequestContext,
        final ClientResponseContext clientResponseContext) throws IOException {

    // TODO configure this on relevant WebTarget instead
    if ("/".equals(clientRequestContext.getUri().getPath())) {
        eventLogger.log("Verifiserer ikke signatur fordi det er rotressurs vi hentet.");
        return;/* w  ww.  j  a va2 s.  c  om*/
    }

    try {
        String serverSignaturBase64 = getServerSignaturFromResponse(clientResponseContext);
        byte[] serverSignaturBytes = Base64.decode(serverSignaturBase64.getBytes());

        String signatureString = getCanonicalResponseRepresentation(
                new ClientResponseToVerify(clientRequestContext, clientResponseContext));

        Signature instance = Signature.getInstance("SHA256WithRSAEncryption");
        instance.initVerify(lastSertifikat());
        instance.update(signatureString.getBytes());
        boolean verified = instance.verify(serverSignaturBytes);
        if (!verified) {
            throw new DigipostClientException(SERVER_SIGNATURE_ERROR,
                    "Melding fra server matcher ikke signatur.");
        } else {
            eventLogger.log("Verifiserte signert respons fra Digipost. Signatur fra HTTP-headeren "
                    + X_Digipost_Signature + " var OK: " + serverSignaturBase64);
        }
    } catch (Exception e) {
        LoggingUtil.logResponse(clientResponseContext);
        if (shouldThrow) {
            if (e instanceof DigipostClientException) {
                throw (DigipostClientException) e;
            } else {
                throw new DigipostClientException(SERVER_SIGNATURE_ERROR,
                        "Det skjedde en feil under signatursjekk: " + e.getMessage());
            }
        } else {
            LOG.warn("Feil under validering av server signatur: '" + e.getMessage() + "'. "
                    + (LOG.isDebugEnabled() ? ""
                            : "Konfigurer debug-logging for " + LOG.getName() + " for  se full stacktrace."));
            LOG.debug(e.getMessage(), e);
        }
    }
}

From source file:org.springframework.security.oauth.common.signature.RSA_SHA1SignatureMethod.java

/**
 * The Signature Base String is signed using the Consumers RSA private key per RFC3447 section 8.2.1, where K is the Consumers RSA private key,
 * M the Signature Base String, and S is the result signature octet string:<br/><br/>
 *
 * S = RSASSA-PKCS1-V1_5-SIGN (K, M)<br/><br/>
 *
 * oauth_signature is set to S, first base64-encoded per RFC2045 section 6.8, then URL-encoded per Parameter Encoding.
 *
 * @param signatureBaseString The signature base string.
 * @return The signature.//w  ww . ja  v a  2 s.c  om
 * @throws UnsupportedOperationException If there is no private key.
 */
public String sign(String signatureBaseString) {
    if (privateKey == null) {
        throw new UnsupportedOperationException("Cannot sign the base string: no private key supplied.");
    }

    try {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initSign(privateKey);
        signer.update(signatureBaseString.getBytes("UTF-8"));
        byte[] signatureBytes = signer.sign();
        signatureBytes = Base64.encodeBase64(signatureBytes);
        return new String(signatureBytes, "UTF-8");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e);
    } catch (SignatureException e) {
        throw new IllegalStateException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.linkage.crm.csb.sign.CtSignature.java

/**
 * .//from  w  ww  .  j  a  va2s.  c  o  m
 * 
 * @param originalText String 
 * @param signedText String 
 * @param pubKeyFile String 
 * @return boolean 
 */
public static boolean verify(String originalText, String signedText, String pubKeyFile) {
    try {
        CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
        FileInputStream fin = new FileInputStream(pubKeyFile);
        X509Certificate certificate = (X509Certificate) certificatefactory.generateCertificate(fin);
        PublicKey pub = certificate.getPublicKey();
        Signature dsa = Signature.getInstance("SHA1withDSA");
        dsa.initVerify(pub);
        dsa.update(originalText.getBytes());
        return dsa.verify(HexUtils.fromHexString(signedText));
    } catch (Exception ex) {
        logger.error("errors appeared while trying to verify a signature", ex);
        return false;
    }
}

From source file:org.syphr.utils.x509.X509Utils.java

/**
 * Verify a signature using the given token and certificate.
 *
 * @param message// w  w w  .  ja v a2 s.  c  om
 *            the message to which the signature belongs
 * @param signature
 *            the signature to verify
 * @param sigAlg
 *            the algorithm used to create the signature
 * @param certificate
 *            the certificate to use to verify the signature
 * @return <code>true</code> if the signature is valid; <code>false</code>
 *         otherwise
 * @throws CertificateException
 *             if there is an error reading the certificate
 * @throws InvalidKeyException
 *             if the given certificate does not have a valid public key
 * @throws SignatureException
 *             if the signature is not valid
 */
public static boolean verify(String message, byte[] signature, SignatureAlgorithm sigAlg,
        InputStream certificate) throws CertificateException, InvalidKeyException, SignatureException {
    Certificate cert = getCertFactory().generateCertificate(certificate);

    try {
        Signature sig = Signature.getInstance(sigAlg.getAlgorithm());
        sig.initVerify(cert);
        sig.update(message.getBytes());
        return sig.verify(signature);
    } catch (NoSuchAlgorithmException e) {
        /*
         * This is protected against by enforcing specific algorithm
         * choices.
         */
        throw new IllegalArgumentException("Unknown algorithm", e);
    }
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testSwingParentLocale() throws Exception {
    Security.addProvider(new BeIDProvider());

    final JFrame frame = new JFrame("Test Parent frame");
    frame.setSize(200, 200);//w ww . j  a va  2  s .co m
    frame.setLocation(300, 300);
    frame.setVisible(true);

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    final BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    keyStoreParameter.setLogoff(true);
    keyStoreParameter.setParentComponent(frame);
    keyStoreParameter.setLocale(new Locale("nl"));
    keyStore.load(keyStoreParameter);

    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    signature.sign();
}