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:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java

public static String generateSignature(final PrivateKey key, final String msg) {
    try {// w  ww . ja va  2s  . com
        final Signature sig = Signature.getInstance("SHA256withRSA");
        sig.initSign(key);
        sig.update(msg.getBytes("UTF-8"));
        final byte[] bsig = sig.sign();
        return B64.standard.encString(bsig);
    } catch (final Exception ex) {
        throw Exceptions.toUndeclared(ex);
    }
}

From source file:com.adito.security.pki.dsa.SshDssPrivateKey.java

/**
 *
 *
 * @param data/*from  w w w  .  j  a v a  2s.c  o  m*/
 *
 * @return
 *
 * @throws InvalidSshKeySignatureException
 */
public byte[] generateSignature(byte[] data) throws InvalidSignatureException {
    try {
        Signature sig = Signature.getInstance("SHA1withDSA");
        sig.initSign(prvkey);

        sig.update(data);

        byte[] signature = sig.sign();
        byte[] decoded = new byte[40];
        SimpleASNReader asn = new SimpleASNReader(signature);
        asn.getByte();
        asn.getLength();
        asn.getByte();

        byte[] r = asn.getData();
        asn.getByte();

        byte[] s = asn.getData();

        if (r.length >= 20) {
            System.arraycopy(r, r.length - 20, decoded, 0, 20);
        } else {
            System.arraycopy(r, 0, decoded, 20 - r.length, r.length);
        }

        if (s.length >= 20) {
            System.arraycopy(s, s.length - 20, decoded, 20, 20);
        } else {
            System.arraycopy(s, 0, decoded, 20 + (20 - s.length), s.length);
        }

        if (log.isDebugEnabled()) {
            log.debug("s length is " + String.valueOf(s.length));
            log.debug("r length is " + String.valueOf(r.length));

            String str = "";

            for (int i = 0; i < signature.length; i++) {
                str += (Integer.toHexString(signature[i] & 0xFF) + " ");
            }

            log.debug("Java signature is " + str);
            str = "";

            for (int i = 0; i < decoded.length; i++) {
                str += (Integer.toHexString(decoded[i] & 0xFF) + " ");
            }

            log.debug("SSH signature is " + str);
        }

        ByteArrayWriter baw = new ByteArrayWriter();
        baw.writeString(getAlgorithmName());
        baw.writeBinaryString(decoded);

        return baw.toByteArray();
    } catch (Exception e) {
        throw new InvalidSignatureException(e);
    }
}

From source file:test.integ.be.fedict.hsm.model.KeyStoreSingletonBeanTest.java

private void checkSigning(long keyStoreId) throws Exception {
    List<String> aliases = this.testedInstance.getKeyStoreAliases(keyStoreId);
    assertFalse(aliases.isEmpty());/*from  w  ww.  j a  v a 2 s .  co  m*/
    String alias = aliases.get(0);

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();
    byte[] signatureValue = this.testedInstance.sign(keyStoreId, alias, "SHA-1", digestValue);

    Signature signature = Signature.getInstance("SHA1withRSA");
    Certificate[] certificateChain = this.testedInstance.getCertificateChain(keyStoreId, alias);
    assertTrue(certificateChain.length > 0);
    X509Certificate certificate = (X509Certificate) certificateChain[0];
    signature.initVerify(certificate.getPublicKey());
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:com.jinhe.tss.framework.license.LicenseManager.java

/**
 * <pre>/*from  ww w  .  j  a v a  2  s.c  om*/
 * ?license??
 * ?Mac??????
 * ???????
 * </pre>
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.macAddress;
    if (!EasyUtils.isNullOrEmpty(macAddress)) {
        String curMacAddress = MacAddress.getMacAddress();
        if (!macAddress.equals(curMacAddress)) {
            return false;
        }
    }

    File keyFile = new File(LicenseFactory.PUBLIC_KEY_FILE);
    String publicKey = FileHelper.readFile(keyFile).trim();

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(EasyUtils.decodeHex(publicKey));
    KeyFactory keyFactory = KeyFactory.getInstance(LicenseFactory.KEY_ALGORITHM);
    java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance(LicenseFactory.KEY_ALGORITHM);
    sig.initVerify(pubKey);
    sig.update(license.getFingerprint());
    return sig.verify(EasyUtils.decodeHex(license.licenseSignature));
}

From source file:be.fedict.hsm.model.KeyStoreSingletonBean.java

/**
 * Sign the given digest value./*from www  . jav  a  2 s  .  c  o m*/
 * 
 * @param keyStoreId
 * @param keyStoreAlias
 * @param digestAlgo
 * @param digestValue
 * @return the signature, or <code>null</code> in case something went wrong.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws IOException
 * @throws SignatureException
 */
@Lock(LockType.READ)
public byte[] sign(long keyStoreId, String keyStoreAlias, String digestAlgo, byte[] digestValue)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException {
    Map<String, PrivateKeyEntry> keyStoreKeys = this.privateKeyEntries.get(keyStoreId);
    if (null == keyStoreKeys) {
        LOG.error("unknown key store: " + keyStoreId);
        return null;
    }
    PrivateKeyEntry privateKeyEntry = keyStoreKeys.get(keyStoreAlias);
    if (null == privateKeyEntry) {
        LOG.error("private key for alias not available: " + keyStoreAlias);
        return null;
    }
    PrivateKey privateKey = privateKeyEntry.getPrivateKey();
    Signature signature = Signature.getInstance("NONEwithRSA");
    signature.initSign(privateKey);

    ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
    byte[] digestInfoPrefix = digestInfoPrefixes.get(digestAlgo);
    if (null == digestInfoPrefix) {
        throw new NoSuchAlgorithmException(digestAlgo);
    }
    digestInfo.write(digestInfoPrefix);
    digestInfo.write(digestValue);

    signature.update(digestInfo.toByteArray());

    return signature.sign();
}

From source file:org.javaweb.utils.RSAUtils.java

/**
 * RSA???//  w  w w .j  av  a  2s .c o  m
 *
 * @param data ?
 * @param key  
 * @param sign ??Base64
 * @return
 * @throws Exception
 */
public static boolean verify(byte[] data, Key key, String sign) throws Exception {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key.getEncoded());
    KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
    PublicKey publicK = keyFactory.generatePublic(keySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicK);
    signature.update(data);

    return signature.verify(Base64.decodeBase64(sign));
}

From source file:org.umit.icm.mobile.utils.RSACrypto.java

/**
 * Returns an RSA KeyPair generated using 
 * {@link KeyPairGenerator#generateKeyPair()}. 
 * //from   w  w w.j  a va2 s .c  o m
 *    
                             
@return {@link KeyPair}                             
 *
                                    
@see         KeyPairGenerator
 */

public static byte[] Sign(PrivateKey privateKey, byte[] data) throws Exception {
    if (Constants.DEBUG_MODE)
        System.out.println("Signing the key inside RSACrypto#Sign");
    Signature dsa = Signature.getInstance("SHA1withRSA");

    dsa.initSign(privateKey);
    dsa.update(data);
    return dsa.sign();
}

From source file:com.microsoft.azure.oidc.token.impl.SimpleTokenValidator.java

@Override
public Boolean validateSignature(final Token token) {
    if (token == null) {
        throw new PreconditionException("Required parameter is null");
    }// w w  w. j a  v  a2  s .  c o  m
    if (algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName())
            .equals("HMAC")) {
        return Boolean.FALSE;
    }
    final Configuration configuration = configurationCache.load();
    if (configuration == null) {
        throw new GeneralException("Error loading configuration");
    }
    try {
        final TimeStamp now = timeStampFactory.createTimeStamp(System.currentTimeMillis() / 1000);
        if (configuration.getKey(token.getKeyName()).getNotBefore().compareTo(now) > 0) {
            return Boolean.FALSE;
        }
        final Base64 decoder = new Base64();
        final BigInteger exponent = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getExponent().getValue()));
        final BigInteger modulus = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getSecret().getValue()));
        final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
        final KeyFactory keyFactory = KeyFactory.getInstance(
                algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName()));
        final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        final Signature sig = Signature.getInstance(
                algorithmConfigurationService.get().getAlgorithmMap().get(token.getAlgorithm().getName()));
        sig.initVerify(pubKey);
        sig.update(token.getPayload().getValue().getBytes());
        return sig.verify(decoder.decode(token.getSignature().getValue()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | SignatureException | InvalidKeyException e) {
        LOGGER.error(e.getMessage(), e);
        return Boolean.FALSE;
    }
}

From source file:org.apache.xml.security.algorithms.implementations.SignatureDSA.java

/**
 * @inheritDoc/*from  ww  w  .j  a  v  a  2 s.  c o m*/
 */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
    if (!(publicKey instanceof PublicKey)) {
        String supplied = publicKey.getClass().getName();
        String needed = PublicKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initVerify((PublicKey) publicKey);
    } catch (InvalidKeyException ex) {
        // reinstantiate Signature object to work around bug in JDK
        // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
        Signature sig = this.signatureAlgorithm;
        try {
            this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
        } catch (Exception e) {
            // this shouldn't occur, but if it does, restore previous
            // Signature
            if (log.isDebugEnabled()) {
                log.debug("Exception when reinstantiating Signature:" + e);
            }
            this.signatureAlgorithm = sig;
        }
        throw new XMLSignatureException("empty", ex);
    }
}

From source file:be.fedict.eidviewer.lib.X509Utilities.java

public static boolean isValidSignature(X509Certificate certificate, byte[] data, byte[] data2,
        byte[] signature) {
    try {//from   ww w .  j a v  a 2s .c  o  m
        Signature verifier = Signature.getInstance("SHA1withRSA");
        verifier.initVerify(certificate);
        verifier.update(data);
        if (data2 != null)
            verifier.update(data2);
        return verifier.verify(signature);
    } catch (Exception e) {
        return false;
    }
}