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:pepperim.util.IMCrypt.java

/**
 * Regular RSA signing (using SHA1-hash)
 * @param data Data to be signed/*w w  w .j  ava 2 s . c o m*/
 * @param key Key to be used for the signature
 * @return Base64-encoded RSA signature
 */
public static String RSA_Sign(String data, PrivateKey key) {
    try {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initSign(key);
        signer.update(data.getBytes());
        byte[] signature = signer.sign();
        return B64_Enc(signature);
    } catch (GeneralSecurityException e) {
        Main.log(e.getMessage());
        return "";
    }
}

From source file:com.aqnote.shared.cryptology.asymmetric.DSA.java

/**
 * ???//from   w ww .ja va  2  s. co  m
 * 
 * @param content ????
 * @param keyPairName key pair
 * @return base64???
 */
public String sign(byte[] content, String keyPairName) throws RuntimeException {
    KeyPairEntry entry = (KeyPairEntry) keyPairs.get(keyPairName);
    if (entry == null || entry.privateKey == null) {
        return null;
    }

    try {
        Signature signature = Signature.getInstance(ALGORITHM);
        signature.initSign(entry.privateKey);
        signature.update((byte[]) content);
        byte[] signed = signature.sign();

        if (log.isDebugEnabled()) {
            log.debug("Java signature[length=" + signed.length + "]: " + toHexString(signed));
        }

        return Base64.encodeBase64String(signed);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}

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

public void testHandleMessageWithIntegrityCheck() throws Exception {
    // setup//w  w w  . j a  va  2s  .co  m
    KeyPair rootKeyPair = MiscTestUtils.generateKeyPair();
    KeyPair rrnKeyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate rootCertificate = MiscTestUtils.generateCertificate(rootKeyPair.getPublic(),
            "CN=TestRootCA", notBefore, notAfter, null, rootKeyPair.getPrivate(), true, 0, null, null);
    X509Certificate rrnCertificate = MiscTestUtils.generateCertificate(rrnKeyPair.getPublic(),
            "CN=TestNationalRegistration", notBefore, notAfter, null, rootKeyPair.getPrivate(), false, 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("IdentityIntegrityService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("IdentityIntegrityServiceClass"))
            .andStubReturn(IdentityIntegrityTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("SkipNationalNumberCheck")).andStubReturn(null);

    EasyMock.expect(mockHttpSession.getAttribute("eid.identifier")).andStubReturn(null);

    mockHttpSession.setAttribute(EasyMock.eq("eid.identity"), EasyMock.isA(Identity.class));
    EasyMock.expect(mockHttpSession.getAttribute("eid")).andStubReturn(null);
    mockHttpSession.setAttribute(EasyMock.eq("eid"), EasyMock.isA(EIdData.class));

    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_ADDRESS_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_CERTIFICATES_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_PHOTO_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);

    byte[] idFile = "foobar-id-file".getBytes();
    IdentityDataMessage message = new IdentityDataMessage();
    message.idFile = idFile;

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(rrnKeyPair.getPrivate());
    signature.update(idFile);
    byte[] idFileSignature = signature.sign();
    message.identitySignatureFile = idFileSignature;
    message.rrnCertFile = rrnCertificate.getEncoded();
    message.rootCertFile = rootCertificate.getEncoded();

    // 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(rrnCertificate, IdentityIntegrityTestService.getCertificate());
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMSignatureMethod.java

boolean verify(Key key, SignedInfo si, byte[] sig, XMLValidateContext context)
        throws InvalidKeyException, SignatureException, XMLSignatureException {
    if (key == null || si == null || sig == null) {
        throw new NullPointerException();
    }/*from w w w. ja v a2 s .  co m*/

    if (!(key instanceof PublicKey)) {
        throw new InvalidKeyException("key must be PublicKey");
    }
    if (signature == null) {
        try {
            Provider p = (Provider) context.getProperty("org.jcp.xml.dsig.internal.dom.SignatureProvider");
            signature = (p == null) ? Signature.getInstance(getJCAAlgorithm())
                    : Signature.getInstance(getJCAAlgorithm(), p);
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    signature.initVerify((PublicKey) key);
    if (log.isDebugEnabled()) {
        log.debug("Signature provider:" + signature.getProvider());
        log.debug("verifying with key: " + key);
    }
    ((DOMSignedInfo) si).canonicalize(context, new SignerOutputStream(signature));

    try {
        Type type = getAlgorithmType();
        if (type == Type.DSA) {
            return signature.verify(convertXMLDSIGtoASN1(sig));
        } else if (type == Type.ECDSA) {
            return signature.verify(SignatureECDSA.convertXMLDSIGtoASN1(sig));
        } else {
            return signature.verify(sig);
        }
    } catch (IOException ioe) {
        throw new XMLSignatureException(ioe);
    }
}

From source file:org.mitre.jwt.signer.impl.RsaSigner.java

private void initializeSigner() throws NoSuchAlgorithmException {
    if (this.keystore != null && this.alias != null && this.password != null) {
        // if it looks like we're configured with a keystore, load it here
        loadKeysFromKeystore();/*from  w  w w.j a v a 2  s  .c  o  m*/
    }

    if (signer == null) {
        signer = Signature.getInstance(getAlgorithm().getStandardName());
    }
}

From source file:org.oscarehr.common.hl7.v2.oscar_to_oscar.SendingUtils.java

private static byte[] getSignature(byte[] bytes, PrivateKey receiverServiceKey)
        throws SignatureException, InvalidKeyException, NoSuchAlgorithmException {
    Signature signature = Signature.getInstance("MD5WithRSA");
    signature.initSign(receiverServiceKey);
    signature.update(bytes);/*from w  w  w  . ja  v  a2s .  c o m*/
    return (signature.sign());
}

From source file:oscar.oscarLab.ca.all.pageUtil.LabUploadAction.java

public static boolean validateSignature(PublicKey key, String sigString, File input) {
    Base64 base64 = new Base64(0);
    byte[] buf = new byte[1024];

    try {//from  w ww.  j a  v a  2 s  . co  m

        InputStream msgIs = new FileInputStream(input);
        Signature sig = Signature.getInstance("MD5WithRSA");
        sig.initVerify(key);

        // Read in the message bytes and update the signature
        int numRead = 0;
        while ((numRead = msgIs.read(buf)) >= 0) {
            sig.update(buf, 0, numRead);
        }
        msgIs.close();

        return (sig.verify(base64.decode(sigString.getBytes(MiscUtils.ENCODING))));

    } catch (Exception e) {
        logger.debug("Could not validate signature: " + e);
        MiscUtils.getLogger().error("Error", e);
        return (false);
    }
}

From source file:mx.bigdata.sat.cfdi.CFDv33.java

@Override
public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory
            .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initVerify(cert);//from  ww  w .j a va2s.  c  o m
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.VirtualFirealarmSecurityManager.java

public static boolean verifySignature(String data, String signedData, PublicKey verificationKey)
        throws VirtualFirealarmDeviceMgtPluginException {

    Signature signature;/*from   w w  w.ja va  2s .co  m*/
    boolean verified;

    try {
        signature = Signature.getInstance(SHA_512);
        signature.initVerify(verificationKey);
        signature.update(Base64.decodeBase64(data));

        verified = signature.verify(Base64.decodeBase64(signedData));

    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SHA_512 + "]";
        log.error(errorMsg);
        throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SHA_512 + "]";
        log.error(errorMsg);
        throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + verificationKey + "\n]\n";
        log.error(errorMsg);
        throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    }

    return verified;
}

From source file:mx.bigdata.sat.cfd.CFDv2.java

String getSignature(PrivateKey key) throws Exception {
    byte[] bytes = getOriginalBytes();
    byte[] signed;
    String alg = getDigestAlgorithm();
    Signature sig = Signature.getInstance(alg);
    sig.initSign(key);//from   w  w  w .  j  ava2 s .co  m
    sig.update(bytes);
    signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
}