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:mx.bigdata.cfdi.TFDv1.java

public int verify(Certificate cert) throws Exception {
    if (tfd == null) {
        return 601; //No contiene timbrado
    }//w  ww . ja va2 s  . c o m
    Base64 b64 = new Base64();
    String sigStr = tfd.getSelloSAT();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean verified = sig.verify(signature);
    return verified ? 600 : 602; //Sello del timbrado no valido
}

From source file:service.GoogleCalendarAuth.java

public GoogleCalendarAuth(String client_id, String key) {
    final long now = System.currentTimeMillis() / 1000L;
    final long exp = now + 3600;
    final char[] password = "notasecret".toCharArray();
    final String claim = "{\"iss\":\"" + client_id + "\"," + "\"scope\":\"" + SCOPE + "\","
            + "\"aud\":\"https://accounts.google.com/o/oauth2/token\"," + "\"exp\":" + exp + "," +
            // "\"prn\":\"some.user@somecorp.com\"," + // This require some.user to have their email served from a googlemail domain?
            "\"iat\":" + now + "}";
    try {//from   w  ww  .  j a va 2  s .c o  m
        final String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));
        final byte[] jwt_data = jwt.getBytes("UTF8");
        final Signature sig = Signature.getInstance("SHA256WithRSA");

        final KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), password);

        sig.initSign((PrivateKey) ks.getKey("privatekey", password));
        sig.update(jwt_data);
        final byte[] signatureBytes = sig.sign();
        final String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        final String assertion = jwt + "." + b64sig;
        //System.out.println("Assertion: " + assertion);
        final String data = "grant_type=assertion" + "&assertion_type="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8") + "&assertion="
                + URLEncoder.encode(assertion, "UTF-8");

        // Make the Access Token Request
        URLConnection conn = null;
        try {
            final URL url = new URL("https://accounts.google.com/o/oauth2/token");
            conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            final InputStream error = ((HttpURLConnection) conn).getErrorStream();
            final BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                sb.append(line);
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        System.out.println("access_token=" + access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#signFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *//*w w w  .j ava2s  .c o  m*/
public synchronized FileSecurityResponse signFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#signFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm());
            signature.initSign(keyPair.getPrivate());
            signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile())));

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", signature);
            }

            byte[] sig = signature.sign();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
            }

            IOUtils.write(sig, new FileOutputStream(request.getSignedFile()));

            if ((request.getSignedFile().exists()) && (request.getSignedFile().length() != 0)) {
                response.setSignedFile(request.getSignedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);

        throw new FileSecurityException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (SignatureException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new FileSecurityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.SIGNFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

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

/**
 * RSA???//ww  w  .  j a  v a  2s. com
 *
 * @param data ?
 * @param key  ?
 * @return
 * @throws Exception
 */
public static String sign(byte[] data, Key key) throws Exception {
    byte[] keyBytes = key.getEncoded();
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

    signature.initSign(privateK);
    signature.update(data);

    return Base64.encodeBase64String(signature.sign());
}

From source file:mx.bigdata.cfdi.CFDv3.java

public void verify() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);
    X509Certificate cert = KeyLoader.loadX509Certificate(new ByteArrayInputStream(cbs));
    cert.checkValidity();/*  www  .j a v a2s. c  o m*/
    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}

From source file:com.ss.license.LicenseManager.java

/**
 * license/*from w  w  w.  ja va2  s .  c o m*/
 * Mac
 * 
 * 
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.getMacAddress();
    if (macAddress != null && macAddress.length() > 0) {
        String curMacAddress = "";
        if (!macAddress.equals(curMacAddress))
            return false;
    }
    String publicKey = FileHelper.readFile(new File(LicenseFactory.PUBLIC_KEY_FILE)).trim();

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

    Signature sig = Signature.getInstance("DSA");
    sig.initVerify(pubKey);
    sig.update(license.getFingerprint());
    return sig.verify(EasyUtils.decodeHex(license.getLicenseSignature()));
}

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

public void testHandleMessage() throws Exception {
    // setup//w  w  w.  j  a  va  2  s . com
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    String userId = "1234";
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(),
            "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null,
            null);

    byte[] salt = "salt".getBytes();
    byte[] sessionId = "session-id".getBytes();

    AuthenticationDataMessage message = new AuthenticationDataMessage();
    message.authnCert = certificate;
    message.saltValue = salt;
    message.sessionId = sessionId;

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

    byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession);

    AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId,
            null, challenge);
    byte[] toBeSigned = authenticationContract.calculateToBeSigned();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuthenticationTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(AuditTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class"))
            .andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class"))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig
            .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(
            AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class"))
            .andReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);

    EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session"))
            .andStubReturn(new String(Hex.encodeHex(sessionId)));
    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("1.2.3.4");

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

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

    // verify
    EasyMock.verify(mockServletRequest, mockServletConfig);
    assertTrue(AuthenticationTestService.isCalled());
    assertEquals(userId, AuditTestService.getAuditUserId());
    assertEquals(userId, testHttpSession.getAttribute("eid.identifier"));
}

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

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

    MyFrame myFrame = new MyFrame();

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(myFrame);/*from w  w  w  .ja  v a2s. c  om*/

    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);
    byte[] signatureValue = signature.sign();

    Certificate[] certificateChain = keyStore.getCertificateChain("Authentication");
    signature.initVerify(certificateChain[0]);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

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

public void testHandleMessage() throws Exception {
    // setup/*from   ww w .  ja va 2 s .  c o m*/
    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("SHA1");
    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-1");

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

    Signature signature = Signature.getInstance("SHA1withRSA");
    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());
}