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.structr.util.StructrLicenseVerifier.java

private StructrLicenseVerifier(final String keystoreFileName, final String password) {

    logger.info("Starting license server..");

    try {/*  w  ww  .  j  a  va  2  s .c  om*/

        logger.info("Loading key store, initializing ciphers..");

        this.gson = new GsonBuilder().setPrettyPrinting().create();
        this.keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        this.blockCipher = Cipher.getInstance(StructrLicenseManager.KeyEncryptionAlgorithm);
        this.streamCipher = Cipher.getInstance(StructrLicenseManager.DataEncryptionAlgorithm);
        this.signer = Signature.getInstance(StructrLicenseManager.SignatureAlgorithm);

        try (final InputStream is = new FileInputStream(keystoreFileName)) {

            keyStore.load(is, password.toCharArray());

            this.key = keyStore.getKey("structr", password.toCharArray());

            blockCipher.init(Cipher.DECRYPT_MODE, key);
        }

    } catch (Throwable t) {
        logger.warn("Unable to initialize key store or ciphers: {}", t.getMessage());
    }
}

From source file:hh.learnj.test.license.test.rsa.RSATest.java

/**
 * ???/*ww  w.  j  a va 2s .  com*/
 * 
 * @return
 * @throws Exception
 */
static void verifyByPublicKey(String target, String sign) throws Exception {
    PublicKey publicKey = getPublicKey();
    Signature signature = Signature.getInstance(ALGORITHM_SIGN);
    signature.initVerify(publicKey);
    signature.update(target.getBytes("UTF-8"));
    if (signature.verify(decodeBase64(sign))) {
        System.out.println("???");
    } else {
        System.out.println("???");
    }
}

From source file:org.waveprotocol.wave.crypto.WaveSignatureVerifier.java

/**
 * Verifies the signature on some signed payload.
 * @param signedPayload the payload on which we're verifiying the signature.
 * @param signatureInfo the signature provided with the payload.
 * @param authority name of the authority that we expect the target
 *   certificate to be issued to./*from w w w  .  j  a  v  a  2  s .  c  om*/
 *
 * @throws SignatureException if the signature can't be verified, either
 *   because it simply didn't check out, or because of other reasons, like us
 *   not supporting the signature algorithm specified.
 * @throws UnknownSignerException if we can't find the cert chain in the local
 *   cert-path store.
 */
public void verify(byte[] signedPayload, ProtocolSignature signatureInfo, String authority)
        throws SignatureException, UnknownSignerException {

    SignerInfo signer = pathStore.getSignerInfo(signatureInfo.getSignerId().toByteArray());

    if (signer == null) {
        throw new UnknownSignerException("could not find information about signer "
                + Base64.encodeBase64(signatureInfo.getSignerId().toByteArray()));
    }

    verifySignerInfo(signer);

    Signature verifier;
    try {
        verifier = Signature.getInstance(AlgorithmUtil.getJceName(signatureInfo.getSignatureAlgorithm()));
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(
                "can't verify signatures of type " + signatureInfo.getSignatureAlgorithm().toString(), e);
    }

    X509Certificate cert = signer.getCertificates().get(0);

    try {
        verifier.initVerify(cert);
    } catch (InvalidKeyException e) {
        throw new SignatureException("certificate of signer was not issued for " + "message signing");
    }

    try {
        verifier.update(signedPayload);
    } catch (java.security.SignatureException e) {
        // this is thrown if the verifier object is not properly initialized.
        // this shouldn't happen as we _just_ initialized it on the previous line.
        throw new IllegalStateException(e);
    }

    try {
        if (!verifier.verify(signatureInfo.getSignatureBytes().toByteArray())) {
            throw new SignatureException("signature did not verify");
        }
    } catch (java.security.SignatureException e) {
        throw new SignatureException(e);
    }

    verifyMatchingAuthority(authority, cert);
}

From source file:ai.susi.tools.JsonSignature.java

public static boolean verify(Map<String, byte[]> obj, PublicKey key)
        throws SignatureException, InvalidKeyException {

    if (!obj.containsKey(signatureString))
        throw new SignatureException("No signature supplied");

    Signature signature;//from  w  w w .j a  va  2s.c  om
    try {
        signature = Signature.getInstance("SHA256withRSA");
    } catch (NoSuchAlgorithmException e) {
        return false; //does not happen
    }

    byte[] sigString = obj.get(signatureString);
    byte[] sig = Base64.getDecoder().decode(sigString);
    obj.remove(signatureString);

    signature.initVerify(key);
    signature.update(obj.toString().getBytes(StandardCharsets.UTF_8));
    boolean res = signature.verify(sig);

    obj.put(signatureString, sigString);

    return res;
}

From source file:com.vmware.identity.rest.core.util.RequestSigner.java

/**
 * Verify a signed request using a hex-formatted string, the string to sign, and a certificate's public key.
 *
 * @param signedRequestHex a hex-encoded string representing the signed request to verify.
 * @param stringToSign the string that will be signed with the public key for
 * verification purposes.//from  w  ww  .  j a  v a 2  s  . com
 * @param publicKey the public key used for verification.
 * @return true if the signature was verified, false if not.
 * @throws DecoderException if there is an error decoding the hex string.
 * @throws InvalidKeyException if the public key is invalid.
 * @throws SignatureException if the signature algorithm is unable to process the input
 * data provided.
 */
public static boolean verify(String signedRequestHex, String stringToSign, PublicKey publicKey)
        throws DecoderException, InvalidKeyException, SignatureException {
    byte[] signedRequest = Hex.decodeHex(signedRequestHex.toCharArray());

    Signature sig;

    try {
        sig = Signature.getInstance(SHA256_WITH_RSA);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("An error occurred while getting the signature algorithm", e);
    }

    sig.initVerify(publicKey);
    sig.update(stringToSign.getBytes(StandardCharsets.UTF_8));

    return sig.verify(signedRequest);
}

From source file:netinf.common.security.impl.SignatureAlgorithmImpl.java

/**
 * @see SignatureAlgorithm#verifySignature(String, String, PublicKey, String)
 *//*from   w  ww.j a v a2  s.  co  m*/
@Override
public boolean verifySignature(String originalString, String signatureString, PublicKey pk,
        String hashAndSignatureFunction)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    Signature signature = Signature.getInstance(hashAndSignatureFunction);
    signature.initVerify(pk);
    signature.update(originalString.getBytes());
    return signature.verify(Base64.decodeBase64(signatureString));
}

From source file:net.padlocksoftware.padlock.license.LicenseSigner.java

/**
 * Sign the supplied license using the PrivateKey given at the LicenseSigner instantation.
 * /*from  ww  w  . j  a  v  a  2s  .  c o  m*/
 * @param license The license to sign. Once signed, a license cannot be modified.
 * @throws IllegalStateException If the license has already been signed.
 */
public void sign(License license) {
    synchronized (license) {
        if (license.isSigned()) {
            throw new IllegalStateException("License is already signed");
        }

        String licenseString = ((LicenseImpl) license).concatenate();
        try {
            Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initSign(privateKey);
            signature.update(licenseString.getBytes("UTF-8"));
            byte[] sig = signature.sign();
            String sigString = new String(Hex.encodeHex(sig));
            ((LicenseImpl) license).props.setProperty("signature", sigString);
        } catch (SignatureException ex) {
            logger.log(Level.SEVERE, "Signature failure.  Please verify a DSA security provider is available.",
                    ex);
        } catch (InvalidKeyException ex) {
            logger.log(Level.SEVERE, "Key failure.  Please verify a DSA security provider is available.", ex);
        } catch (NoSuchAlgorithmException ex) {
            logger.log(Level.SEVERE,
                    "Signature creation failure.  Please verify a DSA security provider is available.", ex);
        } catch (UnsupportedEncodingException ex) {
            logger.log(Level.SEVERE, "Encoding Exception.  Please report to support@padlocksoftware.net", ex);
        }
    }
}

From source file:com.ddubyat.develop.jhawtcode.util.PropertyUtil.java

private boolean validLicense(String email, String licenseCode) throws Exception {

    Resource res = applicationContext.getResource("classpath:jhc-public.der");
    InputStream is = res.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[4096];
    byte[] pkey;/*w  w w .  ja  v a2 s  . c  om*/
    int stream;
    while ((stream = is.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, stream);
    }

    pkey = baos.toByteArray();

    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pkey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey mypk = keyFactory.generatePublic(keySpec);

    Signature instance = Signature.getInstance("SHA1withRSA");
    instance.initVerify(mypk);
    instance.update(email.getBytes());

    //BASE64Decoder decoder = new BASE64Decoder();
    //byte[] decodedBytes = decoder.decodeBuffer(licenseCode);

    return instance.verify(DatatypeConverter.parseBase64Binary(licenseCode));
}

From source file:com.valco.utility.FacturasUtility.java

private static byte[] getBytesCadenaFirmada(java.security.PrivateKey pk, OutputStream output)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    Signature firma = Signature.getInstance("SHA1withRSA");
    firma.initSign(pk);/*from   ww w. j  av a 2  s .  co  m*/
    firma.update(output.toString().getBytes("UTF-8"));
    byte[] cadenaFirmada = firma.sign();
    return cadenaFirmada;
}

From source file:com.xinferin.licensing.LicenceGenerator.java

/**
 * Signs the data and returns the signature.
 * @param toBeSigned Data to be signed/* ww w .j a  v  a  2 s .  c  om*/
 * @return byte[] Signature
 * @throws Exception 
*/
public byte[] signData(byte[] toBeSigned) throws Exception {

    try {
        if (privateKey == null)
            initialisePrivateKey();

        Signature signatureInstance = Signature.getInstance("SHA1withRSA");
        signatureInstance.initSign(privateKey);
        signatureInstance.update(toBeSigned);

        return signatureInstance.sign();

    } catch (NoSuchAlgorithmException ex) {
        throw new Exception("The SHA1withRSA algorithm was not found. " + ex.getCause());
    } catch (InvalidKeyException in) {
        throw new Exception("Invalid key returned from database. " + in.getCause());
    } catch (SignatureException se) {
        throw new Exception("No signature instance can be created. " + se.getCause());
    }
}