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, Provider provider) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:test.be.fedict.eid.applet.PcscTest.java

@Test
public void createPSSSignature() throws Exception {
    this.messages = new Messages(Locale.GERMAN);
    PcscEid pcscEid = new PcscEid(new TestView(), this.messages);
    if (false == pcscEid.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEid.waitForEidPresent();/*from   www.  j  av a 2  s  . c o m*/
    }
    CardChannel cardChannel = pcscEid.getCardChannel();

    byte[] message = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    byte[] digest = messageDigest.digest(message);

    try {
        CommandAPDU setApdu = new CommandAPDU(0x00, 0x22, 0x41, 0xB6, new byte[] { 0x04, // length of following data
                (byte) 0x80, // algo ref
                0x10, // PKCS1-PSS-SHA1
                (byte) 0x84, // tag for private key ref
                PcscEid.AUTHN_KEY_ID });
        ResponseAPDU responseAPDU = cardChannel.transmit(setApdu);
        assertEquals(0x9000, responseAPDU.getSW());

        pcscEid.verifyPin();

        CommandAPDU computeDigitalSignatureApdu = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, digest);
        responseAPDU = cardChannel.transmit(computeDigitalSignatureApdu);
        assertEquals(0x9000, responseAPDU.getSW());

        byte[] signatureValue = responseAPDU.getData();

        LOG.debug("signature value length: " + signatureValue.length);

        List<X509Certificate> authnCertificateChain = pcscEid.getAuthnCertificateChain();

        Signature signature = Signature.getInstance("SHA1withRSA/PSS", "BC");
        signature.initVerify(authnCertificateChain.get(0).getPublicKey());
        signature.update(message);
        boolean result = signature.verify(signatureValue);
        assertTrue(result);
    } finally {
        pcscEid.close();
    }
}

From source file:test.unit.be.fedict.eid.applet.service.SignatureDataMessageHandlerTest.java

public void testHandleMessagePSS_SHA256() throws Exception {
    // setup// w  ww  . j  av  a2 s .  c  om
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore,
            notAfter, null, keyPair.getPrivate(), true, 0, null, null);

    ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class);
    Map<String, String> httpHeaders = new HashMap<String, String>();
    HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class);
    HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class);

    EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("SignatureService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("SignatureServiceClass"))
            .andStubReturn(SignatureTestService.class.getName());

    MessageDigest messageDigest = MessageDigest.getInstance("SHA256");
    byte[] document = "hello world".getBytes();
    byte[] digestValue = messageDigest.digest(document);
    EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_VALUE_SESSION_ATTRIBUTE))
            .andStubReturn(digestValue);
    EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_ALGO_SESSION_ATTRIBUTE))
            .andStubReturn("SHA-256-PSS");

    SignatureDataMessage message = new SignatureDataMessage();
    message.certificateChain = new LinkedList<X509Certificate>();
    message.certificateChain.add(certificate);

    Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC");
    signature.initSign(keyPair.getPrivate());
    signature.update(document);
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    // prepare
    EasyMock.replay(mockServletConfig, mockHttpSession, mockServletRequest);

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession);

    // verify
    EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest);
    assertEquals(signatureValue, SignatureTestService.getSignatureValue());
}

From source file:org.ejbca.core.protocol.cmp.CmpMessageHelper.java

public static PKIMessage buildCertBasedPKIProtection(PKIMessage pKIMessage, CMPCertificate[] extraCerts,
        PrivateKey key, String digestAlg, String provider) throws NoSuchProviderException,
        NoSuchAlgorithmException, SecurityException, SignatureException, InvalidKeyException {
    // Select which signature algorithm we should use for the response, based on the digest algorithm and key type.
    ASN1ObjectIdentifier oid = AlgorithmTools.getSignAlgOidFromDigestAndKey(digestAlg, key.getAlgorithm());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Selected signature alg oid: " + oid.getId() + ", key algorithm: " + key.getAlgorithm());
    }//  ww w . j av  a  2s .c o  m
    // According to PKCS#1 AlgorithmIdentifier for RSA-PKCS#1 has null Parameters, this means a DER Null (asn.1 encoding of null), not Java null.
    // For the RSA signature algorithms specified above RFC3447 states "...the parameters MUST be present and MUST be NULL."
    PKIHeaderBuilder headerBuilder = getHeaderBuilder(pKIMessage.getHeader());
    AlgorithmIdentifier pAlg = null;
    if ("RSA".equalsIgnoreCase(key.getAlgorithm())) {
        pAlg = new AlgorithmIdentifier(oid, DERNull.INSTANCE);
    } else {
        pAlg = new AlgorithmIdentifier(oid);
    }
    headerBuilder.setProtectionAlg(pAlg);
    // Most PKCS#11 providers don't like to be fed an OID as signature algorithm, so 
    // we use BC classes to translate it into a signature algorithm name instead
    PKIHeader head = headerBuilder.build();
    String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Signing CMP message with signature alg: " + signatureAlgorithmName);
    }
    Signature sig = Signature.getInstance(signatureAlgorithmName, provider);
    sig.initSign(key);
    sig.update(CmpMessageHelper.getProtectedBytes(head, pKIMessage.getBody()));

    if ((extraCerts != null) && (extraCerts.length > 0)) {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()), extraCerts);
    } else {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()));
    }
    return pKIMessage;
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * ?????????/*from www .j  a  v  a 2  s . co m*/
 * 
 * @param ctx
 *            
 * @param content
 *            ??
 * @param privateKey
 *            ?
 * @return byte[] ???
 */
public static byte[] sign(SecurityContext ctx, byte[] content, Key privateKey) {
    try {
        Signature sign = Signature.getInstance(ctx.getSignatureAlgorithm(), ctx.getJceProvider());
        PrivateKey pk = (PrivateKey) privateKey;
        sign.initSign(pk);
        sign.update(content);
        byte[] signed = sign.sign();
        return signed;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}

From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java

private PKIMessage buildCertBasedPKIProtection(PKIMessage pKIMessage, CMPCertificate[] extraCerts,
        PrivateKey key, String digestAlg, String provider, boolean verbose) throws NoSuchProviderException,
        NoSuchAlgorithmException, SecurityException, SignatureException, InvalidKeyException {
    // Select which signature algorithm we should use for the response, based on the digest algorithm and key type.
    ASN1ObjectIdentifier oid = AlgorithmTools.getSignAlgOidFromDigestAndKey(digestAlg, key.getAlgorithm());
    if (verbose) {
        log.info("Selected signature alg oid: " + oid.getId() + ", key algorithm: " + key.getAlgorithm());
    }/*from   w  w  w  . j  av a 2s . c  o  m*/
    // According to PKCS#1 AlgorithmIdentifier for RSA-PKCS#1 has null Parameters, this means a DER Null (asn.1 encoding of null), not Java null.
    // For the RSA signature algorithms specified above RFC3447 states "...the parameters MUST be present and MUST be NULL."
    PKIHeaderBuilder headerBuilder = getHeaderBuilder(pKIMessage.getHeader());
    AlgorithmIdentifier pAlg = null;
    if ("RSA".equalsIgnoreCase(key.getAlgorithm())) {
        pAlg = new AlgorithmIdentifier(oid, DERNull.INSTANCE);
    } else {
        pAlg = new AlgorithmIdentifier(oid);
    }
    headerBuilder.setProtectionAlg(pAlg);
    // Most PKCS#11 providers don't like to be fed an OID as signature algorithm, so 
    // we use BC classes to translate it into a signature algorithm name instead
    PKIHeader head = headerBuilder.build();
    String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
    if (verbose) {
        log.info("Signing CMP message with signature alg: " + signatureAlgorithmName);
    }
    Signature sig = Signature.getInstance(signatureAlgorithmName, provider);
    sig.initSign(key);
    sig.update(getProtectedBytes(head, pKIMessage.getBody()));

    if ((extraCerts != null) && (extraCerts.length > 0)) {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()), extraCerts);
    } else {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()));
    }
    return pKIMessage;
}

From source file:edu.vt.middleware.crypt.CryptProvider.java

/**
 * <p>This finds a <code>Signature</code> using the known providers and the
 * supplied parameters.</p>/*w ww . j a v  a 2  s .c om*/
 *
 * @param  digestAlgorithm  <code>String</code> name
 * @param  algorithm  <code>String</code> name
 * @param  padding  <code>String</code> name
 *
 * @return  <code>Signature</code>
 *
 * @throws  CryptException  if the algorithm is not available from any
 * provider or if the provider is not available in the environment
 */
public static Signature getSignature(final String digestAlgorithm, final String algorithm, final String padding)
        throws CryptException {
    final Log logger = LogFactory.getLog(CryptProvider.class);
    Signature sig = null;
    String transformation = null;
    if (digestAlgorithm != null && padding != null) {
        transformation = digestAlgorithm + "/" + algorithm + "/" + padding;
    } else if (digestAlgorithm != null) {
        transformation = digestAlgorithm + "/" + algorithm;
    } else {
        transformation = algorithm;
    }
    for (int i = 0; i < providers.length; i++) {
        try {
            sig = Signature.getInstance(transformation, providers[i]);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm + " in " + providers[i]);
            }
        } catch (NoSuchProviderException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find provider " + providers[i]);
            }
        } finally {
            if (sig != null) {
                break;
            }
        }
    }
    if (sig == null) {
        try {
            sig = Signature.getInstance(transformation);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm);
            }
            throw new CryptException(e.getMessage());
        }
    }
    return sig;
}

From source file:org.ejbca.core.protocol.cmp.CmpMessageHelper.java

/** verifies signature protection on CMP PKI messages
 *  //from w ww. jav a 2 s . c o m
 * @param pKIMessage the CMP message to verify signature on, if protected by signature protection
 * @param pubKey the public key used to verify the signature
 * @return true if verification is ok or false if verification fails
 * @throws NoSuchAlgorithmException message is signed by an unknown algorithm
 * @throws NoSuchProviderException the BouncyCastle (BC) provider is not installed
 * @throws InvalidKeyException pubKey is not valid for signature verification
 * @throws SignatureException if the passed-in signature is improperly encoded or of the wrong type, if this signature algorithm is unable to process the input data provided, etc.
 */
public static boolean verifyCertBasedPKIProtection(PKIMessage pKIMessage, PublicKey pubKey)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    AlgorithmIdentifier sigAlg = pKIMessage.getHeader().getProtectionAlg();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Verifying signature with algorithm: " + sigAlg.getAlgorithm().getId());
    }
    Signature sig = Signature.getInstance(sigAlg.getAlgorithm().getId(), "BC");
    sig.initVerify(pubKey);
    sig.update(CmpMessageHelper.getProtectedBytes(pKIMessage));
    boolean result = sig.verify(pKIMessage.getProtection().getBytes());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Verification result: " + result);
    }
    return result;
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

@Override
public boolean validateSignature(byte[] sig, byte[] hash) {
    String alg = config.getProperty(RepositoryManagedSignatureProviderFactory.SIGNATURE_ALGORITHM);
    String prov = config.getProperty(RepositoryManagedSignatureProviderFactory.JAVA_SIGNATURE_PROVIDER);

    boolean valid = false;

    try {/*from w  w w.  jav a2  s.  c om*/
        Signature validate = Signature.getInstance(alg, prov);
        validate.initVerify(getPublicKey());
        validate.update(hash);
        valid = validate.verify(sig);
    } catch (NoSuchProviderException nspe) {
        throw new AlfrescoRuntimeException("Provider: " + prov + " was not found: " + nspe.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        throw new AlfrescoRuntimeException("Algorithm: " + alg + " is not available: " + nsae.getMessage());
    } catch (SignatureException se) {
        valid = false;
    } catch (InvalidKeyException ike) {
        valid = false;
    }

    return valid;
}

From source file:Networking.Client.java

public boolean SignatureVerification() {
    Signature sig = null;//from   w  w  w. ja v a 2  s.  co m
    Boolean result = false;
    try {
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(PubToVerify);
        KeyFactory keyFact = KeyFactory.getInstance("DSA", "SUN");
        PublicKey pubkeyToVerify = keyFact.generatePublic(pubKeySpec);
        confirmIdentity = checkAgainstRT(pubkeyToVerify.hashCode());
        sig = Signature.getInstance("SHA1withDSA", "SUN");
        sig.initVerify(pubkeyToVerify);

        byte[] g_pow_y_sign = this.node.getG_pow_y().toByteArray();
        byte[] g_pow_x_sign = this.node.getG_pow_x().toByteArray();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(g_pow_x_sign);
        outputStream.write(g_pow_y_sign);
        byte[] c = outputStream.toByteArray();

        sig.update(c);
        result = (sig.verify(sigToVerify));
    } catch (SignatureException | InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException
            | InvalidKeySpecException | IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * ???/*  w w  w .j  a v  a2s .  co m*/
 * 
 * @param ctx
 *            
 * @param source
 *            
 * @param signed
 *            ???
 * @param pubKey
 *            
 * @return boolean
 */
public static boolean verify(SecurityContext ctx, byte[] source, byte[] signed, PublicKey publicKey) {
    try {
        boolean verify = false;
        Signature sign = Signature.getInstance(ctx.getSignatureAlgorithm(), ctx.getJceProvider());
        sign.initVerify(publicKey);
        sign.update(source);
        verify = sign.verify(signed);
        return verify;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}