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.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java

/**
 * Signs the data using the key pair stored in the Android Key Store.  This signature can be
 * used with the data later to verify it was signed by this application.
 * @return A string encoding of the data signature generated
 *//*from ww w  .j a va 2  s  .  c o m*/
public String signData(String inputStr) throws KeyStoreException, UnrecoverableEntryException,
        NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException, CertificateException {
    byte[] data = inputStr.getBytes();

    // BEGIN_INCLUDE(sign_load_keystore)
    KeyStore ks = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);

    // Weird artifact of Java API.  If you don't have an InputStream to load, you still need
    // to call "load", or it'll crash.
    ks.load(null);

    // Load the key pair from the Android Key Store
    KeyStore.Entry entry = ks.getEntry(mAlias, null);

    /* If the entry is null, keys were never stored under this alias.
     * Debug steps in this situation would be:
     * -Check the list of aliases by iterating over Keystore.aliases(), be sure the alias
     *   exists.
     * -If that's empty, verify they were both stored and pulled from the same keystore
     *   "AndroidKeyStore"
     */
    if (entry == null) {
        Log.w(TAG, "No key found under alias: " + mAlias);
        Log.w(TAG, "Exiting signData()...");
        return null;
    }

    /* If entry is not a KeyStore.PrivateKeyEntry, it might have gotten stored in a previous
     * iteration of your application that was using some other mechanism, or been overwritten
     * by something else using the same keystore with the same alias.
     * You can determine the type using entry.getClass() and debug from there.
     */
    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        Log.w(TAG, "Not an instance of a PrivateKeyEntry");
        Log.w(TAG, "Exiting signData()...");
        return null;
    }
    // END_INCLUDE(sign_data)

    // BEGIN_INCLUDE(sign_create_signature)
    // This class doesn't actually represent the signature,
    // just the engine for creating/verifying signatures, using
    // the specified algorithm.
    Signature s = Signature.getInstance(SecurityConstants.SIGNATURE_SHA256withRSA);

    // Initialize Signature using specified private key
    s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey());

    // Sign the data, store the result as a Base64 encoded String.
    s.update(data);
    byte[] signature = s.sign();
    String result = Base64.encodeToString(signature, Base64.DEFAULT);
    // END_INCLUDE(sign_data)

    return result;
}

From source file:jfabrix101.billing.BillingSecurity.java

/**
 * Verifies that the signature from the server matches the computed
 * signature on the data.  Returns true if the data is correctly signed.
 *
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature//from  ww w. j  av a2 s  . c  o  m
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
    if (BillingConsts.DEBUG) {
        Log.i(TAG, "signature: " + signature);
    }
    Signature sig;
    try {
        sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(publicKey);
        sig.update(signedData.getBytes());
        if (!sig.verify(Base64.decode(signature))) {
            Log.e(TAG, "Signature verification failed.");
            return false;
        }
        return true;
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException.");
    } catch (InvalidKeyException e) {
        Log.e(TAG, "Invalid key specification.");
    } catch (SignatureException e) {
        Log.e(TAG, "Signature exception.");
    } catch (Exception e) {
        Log.e(TAG, "Base64 decoding failed.");
    }
    return false;
}

From source file:com.vmware.identity.samlservice.SamlServiceTest.java

@Test
public void testVerifySignatureVcd2() throws Exception {
    // pick a sample VCD message
    String message = "SAMLResponse=fZJNb%2BIwEIb%2FSuR7%2FJWQJhYBrRatVK"
            + "lcCsuhl5XjTCAosbMZm%2B7P3wClHxx6nPE7M%2B884%2FnyX99FJxixdb"
            + "YkgnISgTWubu2%2BJL%2B3v%2BKcLBdz1H0nB%2FXk9i74Z8DBWYRoKrWo"
            + "rm8lCaNVTmOLyuoeUHmjNj%2FWT0pSrobReWdcR6IVoG%2Bt9pdxB%2B8H"
            + "VIyJQlKR5VTIggqu8jRNmOlcqNm5OdtMZjq4Dme6azWyk6lJ9LgqyZ%2Bq"
            + "SUzKCw41AM%2BNEEZC1dQJT7K0qJJmktmb460riZamqhueFW1xNKI6pqbh"
            + "TXtIjqbJk6Sa5IgBHi16bX1JJBcy5lkssy3nSsyUEFTM8hcS7W7QpgXJGy"
            + "J1KR4%2Fk%2FkejEaE8QyDLG4whrE%2FxLbtq4DxqY%2FFwywWklOwe3rq"
            + "X%2FUI1LhePaRpyl6hQnTs3E2yNXhda6%2BZwWHOPtt5v9%2FGax%2FwLv"
            + "zpaoh2ugvwvVW8qNUmGAOIhN21WU9JvYfFM%2FwN040jvOqa0L2ZuRfepT"
            + "%2Fir79s8R8%3D&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%" + "2Fxmldsig-more%23rsa-sha256";

    // sign using our algorithm
    SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM);
    Signature sig = Signature.getInstance(algo.getAlgorithmName());
    sig.initSign(privateKey);//from w w w.  j  a  va  2  s  .  c  o m

    byte[] messageBytes = message.getBytes();
    sig.update(messageBytes);

    byte[] sigBytes = sig.sign();
    String signature = Shared.encodeBytes(sigBytes);

    // verify signature here
    sig.initVerify(x509Certificate.getPublicKey());
    sig.update(messageBytes);
    boolean verifies = sig.verify(sigBytes);
    log.debug("signature verifies in test: " + verifies);

    // just call verifySignature method and expect to not throw
    service.verifySignature(message, signature);
    /* disabled now: task 1301740
    // import our csp settings
    CasIdmClient idmClient = new CasIdmClient(SharedUtils.getIdmHostName());
            
    SharedUtils.importConfiguration(idmClient, VSPHERE_LOCAL_TENANT,
        "/csp2.xml");
            
    CasIdmAccessor idmAccessor = new CasIdmAccessor(idmClient);
    log.debug("CSP settings imported successfully");
    idmAccessor.setTenant(VSPHERE_LOCAL_TENANT);
            
    // create new SamlService
    SamlServiceFactory factory2 = new DefaultSamlServiceFactory();
    CertificateFactory certFactory = CertificateFactory
        .getInstance("X.509");
    CertPath certPath = certFactory.generateCertPath(idmAccessor
        .getSAMLAuthorityChain());
    SamlService service2 = factory2.createSamlService(
        idmClient.getTenantPrivateKey(VSPHERE_LOCAL_TENANT),
        SignatureAlgorithm.RSA_SHA256, SignatureAlgorithm.RSA_SHA256,
        idmClient.getEntityID(VSPHERE_LOCAL_TENANT), certPath);
            
    // now call it again with generated signature
    String vcdSignature = "tTUaPscQSmPKkqP9XGgCHZYoH%2FUy2MvZ1eoeP%2B3Y" +
        "nTDLxiuV5glxngtMbOGspo9NbL37lNVjdCUo7qQVDznUNmKpIOGa%2BGwE" +
        "jcgqeS7mBDsYPcICxVHZPYxbIaFCmlTIo125olswe4LuP92lIroe%2B%2F" +
        "DpeNXIGjUAFLHQwlLO7r73cHLH%2BPY2pcYww4X2I7Mhk%2FQ7I3tdMX1O" +
        "eOhqcRpMn8uyOs6JmVbMoVXuTVKyO96LmQUPCQVLmVjDeD%2BZjVALVLbs" +
        "vjWsdFt%2F%2Ff2MEXIQkYmeIM5HxZ5rW0uXRocarUrp8nhgxk%2FEQGhk" +
        "00KYP1xZTCC9JZR6OcbXJZZemBgq%2BA%3D%3D";
    vcdSignature = URLDecoder.decode(vcdSignature, "UTF-8");
    // just call verifySignature method and expect to not throw
            
    service2.verifySignature(message, vcdSignature); */
}

From source file:Manifest.java

/**
 * This method verifies the digital signature of the named manifest file, if
 * it has one, and if that verification succeeds, it verifies the message
 * digest of each file in filelist that is also named in the manifest. This
 * method can throw a bunch of exceptions
 *///from   w  ww.ja v a 2  s .co m
public static void verify(String manifestfile, KeyStore keystore) throws NoSuchAlgorithmException,
        SignatureException, InvalidKeyException, KeyStoreException, IOException {
    Properties manifest = new Properties();
    manifest.load(new FileInputStream(manifestfile));
    String digestAlgorithm = manifest.getProperty("__META.DIGESTALGORITHM");
    String signername = manifest.getProperty("__META.SIGNER");
    String signatureAlgorithm = manifest.getProperty("__META.SIGNATUREALGORITHM");
    String hexsignature = manifest.getProperty("__META.SIGNATURE");

    // Get a list of filenames in the manifest.
    List files = new ArrayList();
    Enumeration names = manifest.propertyNames();
    while (names.hasMoreElements()) {
        String s = (String) names.nextElement();
        if (!s.startsWith("__META"))
            files.add(s);
    }
    int numfiles = files.size();

    // If we've got a signature but no keystore, warn the user
    if (signername != null && keystore == null)
        System.out.println("Can't verify digital signature without " + "a keystore.");

    // If the manifest contained metadata about a digital signature, then
    // verify that signature first
    if (signername != null && keystore != null) {
        System.out.print("Verifying digital signature...");
        System.out.flush();

        // To verify the signature, we must process the files in exactly
        // the same order we did when we created the signature. We
        // guarantee this order by sorting the filenames.
        Collections.sort(files);

        // Create a Signature object to do signature verification with.
        // Initialize it with the signer's public key from the keystore
        Signature signature = Signature.getInstance(signatureAlgorithm);
        PublicKey publickey = keystore.getCertificate(signername).getPublicKey();
        signature.initVerify(publickey);

        // Now loop through these files in their known sorted order For
        // each one, send the bytes of the filename and of the digest to
        // the signature object for use in computing the signature. It is
        // important that this be done in exactly the same order when
        // verifying the signature as it was done when creating the
        // signature.
        for (int i = 0; i < numfiles; i++) {
            String filename = (String) files.get(i);
            signature.update(filename.getBytes());
            signature.update(hexDecode(manifest.getProperty(filename)));
        }

        // Now decode the signature read from the manifest file and pass
        // it to the verify() method of the signature object. If the
        // signature is not verified, print an error message and exit.
        if (!signature.verify(hexDecode(hexsignature))) {
            System.out.println("\nManifest has an invalid signature");
            System.exit(0);
        }

        // Tell the user we're done with this lengthy computation
        System.out.println("verified.");
    }

    // Tell the user we're starting the next phase of verification
    System.out.print("Verifying file message digests");
    System.out.flush();

    // Get a MessageDigest object to compute digests
    MessageDigest md = MessageDigest.getInstance(digestAlgorithm);
    // Loop through all files
    for (int i = 0; i < numfiles; i++) {
        String filename = (String) files.get(i);
        // Look up the encoded digest from the manifest file
        String hexdigest = manifest.getProperty(filename);
        // Compute the digest for the file.
        byte[] digest;
        try {
            digest = getFileDigest(filename, md);
        } catch (IOException e) {
            System.out.println("\nSkipping " + filename + ": " + e);
            continue;
        }

        // Encode the computed digest and compare it to the encoded digest
        // from the manifest. If they are not equal, print an error
        // message.
        if (!hexdigest.equals(hexEncode(digest)))
            System.out.println("\nFile '" + filename + "' failed verification.");

        // Send one dot of output for each file we process. Since
        // computing message digests takes some time, this lets the user
        // know that the program is functioning and making progress
        System.out.print(".");
        System.out.flush();
    }
    // And tell the user we're done with verification.
    System.out.println("done.");
}

From source file:com.github.aynu.yukar.framework.util.SecurityHelper.java

/**
 * ???//from   w  w w.j  av a 2  s  .c o m
 * <dl>
 * <dt>?
 * <dd>NONEwithECDSA??????????????
 * </dl>
 * @param publicKey ?
 * @param message 
 * @param signature ??
 * @return ?
 */
public static boolean verify(final PublicKey publicKey, final byte[] signature, final byte[] message) {
    try {
        final Signature sign = Signature.getInstance("NONEwithECDSA");
        sign.initVerify(publicKey);
        sign.update(message);
        return sign.verify(signature);
    } catch (final NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new StandardRuntimeException(e);
    }
}

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

@Test
public void pcscOTPSpike() 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();/*w ww  .j  a  v a2 s.co m*/
    }
    byte[] challenge1 = "123456".getBytes();
    byte[] challenge2 = "654321".getBytes();
    byte[] signatureValue1;
    byte[] signatureValue2;
    List<X509Certificate> authnCertChain;
    try {
        signatureValue1 = pcscEid.signAuthn(challenge1);
        signatureValue2 = pcscEid.signAuthn(challenge2);
        authnCertChain = pcscEid.getAuthnCertificateChain();
    } finally {
        pcscEid.close();
    }

    byte[] sv1 = Arrays.copyOf(signatureValue1, 13);
    byte[] sv2 = Arrays.copyOf(signatureValue2, 13);
    LOG.debug("same encrypted prefix: " + Arrays.equals(sv1, sv2));

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(authnCertChain.get(0).getPublicKey());
    signature.update(challenge1);
    boolean result = signature.verify(signatureValue1);
    assertTrue(result);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.DECRYPT_MODE, authnCertChain.get(0).getPublicKey());
    byte[] signatureDigestInfoValue = cipher.doFinal(signatureValue1);
    LOG.debug("encrypted signature value: " + signatureValue1.length);
    ASN1InputStream aIn = new ASN1InputStream(signatureDigestInfoValue);
    DigestInfo signatureDigestInfo = new DigestInfo((ASN1Sequence) aIn.readObject());
    LOG.debug("algo OID: " + signatureDigestInfo.getAlgorithmId().getObjectId().getId());
    LOG.debug("digest size: " + signatureDigestInfo.getDigest().length);
    int digestIndex = findSubArray(signatureDigestInfoValue, signatureDigestInfo.getDigest());
    assertTrue(-1 != digestIndex);
    LOG.debug("digest index: " + digestIndex);

    // inject the encrypted digest of signature1 into signature2
    // padding will look bad now
    System.arraycopy(signatureValue1, 13, signatureValue2, 13, 20);
    cipher = Cipher.getInstance("RSA/ECB/nopadding");
    cipher.init(Cipher.DECRYPT_MODE, authnCertChain.get(0).getPublicKey());
    signatureValue2 = Arrays.copyOf(signatureValue2, 13 + 20);
    byte[] signatureDigestInfoValue2 = cipher.doFinal(signatureValue2);
    LOG.debug("decrypted structure size: " + signatureDigestInfoValue2.length);
    signatureDigestInfoValue2 = Arrays.copyOf(signatureDigestInfoValue2, 13 + 20);
    LOG.debug("decrypted structure size (truncated): " + signatureDigestInfoValue2.length);
    ASN1InputStream aIn2 = new ASN1InputStream(signatureDigestInfoValue2);
    DigestInfo signatureDigestInfo2 = new DigestInfo((ASN1Sequence) aIn2.readObject());
    LOG.debug("digest size: " + signatureDigestInfo2.getDigest().length);
    LOG.debug("digest: " + new String(signatureDigestInfo2.getDigest()));
}

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

public void testHandleMessageInvalidIntegritySignature() throws Exception {
    // setup//from  www .j av a  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=TestNationalRegistration", 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("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(AuditTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("SkipNationalNumberCheck")).andStubReturn(null);

    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address");

    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;

    KeyPair intruderKeyPair = MiscTestUtils.generateKeyPair();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(intruderKeyPair.getPrivate());
    signature.update(idFile);
    byte[] idFileSignature = signature.sign();
    message.identitySignatureFile = idFileSignature;
    message.rrnCertFile = certificate.getEncoded();

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

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    try {
        this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession);
        fail();
    } catch (ServletException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // verify
        EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest);
        assertNull(IdentityIntegrityTestService.getCertificate());
        assertEquals("remote-address", AuditTestService.getAuditIntegrityRemoteAddress());
    }
}

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

public void testHandleMessageNRCID() throws Exception {
    // setup/*w  ww . ja  v a  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);
    String nrcidSecret = "112233445566778899AABBCCDDEEFF00112233445566778899";
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME))
            .andStubReturn(nrcidSecret);
    String nrcidAppId = "my-app-id";
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME))
            .andStubReturn(nrcidAppId);
    String nrcidOrgId = "my-org-id";
    EasyMock.expect(
            mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME))
            .andStubReturn(nrcidOrgId);

    EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session"))
            .andStubReturn(new String(Hex.encodeHex(sessionId)));
    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(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);
    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("1.2.3.4");
    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);

    // 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());

    String nrcid = UserIdentifierUtil.getNonReversibleCitizenIdentifier(userId, nrcidOrgId, nrcidAppId,
            nrcidSecret);

    assertTrue(nrcid.equals(AuditTestService.getAuditUserId()));
    assertTrue(nrcid.equals(testHttpSession.getAttribute("eid.identifier")));
}

From source file:org.loklak.api.cms.LoginService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JSONObjectWithDefault permissions) throws APIException {

    // login check for app
    if (post.get("checkLogin", false)) {
        JSONObject result = new JSONObject();
        if (authorization.getIdentity().isEmail()) {
            result.put("loggedIn", true);
            result.put("message", "You are logged in as " + authorization.getIdentity().getName());
        } else {//from  w  w w .j  av  a 2 s  .c o  m
            result.put("loggedIn", false);
            result.put("message", "Not logged in");
        }
        return result;
    }

    // do logout if requested
    if (post.get("logout", false)) { // logout if requested

        // invalidate session
        post.getRequest().getSession().invalidate();

        // delete cookie if set
        deleteLoginCookie(response);

        JSONObject result = new JSONObject();
        result.put("message", "Logout successful");
        return result;
    }

    // check login type by checking which parameters are set
    boolean passwordLogin = false;
    boolean pubkeyHello = false;
    boolean pubkeyLogin = false;

    if (post.get("login", null) != null && post.get("password", null) != null
            && post.get("type", null) != null) {
        passwordLogin = true;
    } else if (post.get("login", null) != null && post.get("keyhash", null) != null) {
        pubkeyHello = true;
    } else if (post.get("sessionID", null) != null && post.get("response", null) != null) {
        pubkeyLogin = true;
    } else {
        throw new APIException(400, "Bad login parameters.");
    }

    // check if user is blocked because of too many invalid login attempts
    checkInvalidLogins(post, authorization, permissions);

    if (passwordLogin) { // do login via password

        String login = post.get("login", null);
        String password = post.get("password", null);
        String type = post.get("type", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        // check if the password is valid
        String passwordHash;
        String salt;
        try {
            passwordHash = authentication.getString("passwordHash");
            salt = authentication.getString("salt");
        } catch (Throwable e) {
            Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: "
                    + post.getClientHost() + " : password or salt missing in database");
            throw new APIException(422, "Invalid credentials");
        }

        if (!passwordHash.equals(getHash(password, salt))) {

            // save invalid login in accounting object
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");

            Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: "
                    + post.getClientHost());
            throw new APIException(422, "Invalid credentials");
        }

        JSONObject result = new JSONObject();

        switch (type) {
        case "session": // create a browser session
            post.getRequest().getSession().setAttribute("identity", identity);
            break;
        case "cookie": // set a long living cookie
            // create random string as token
            String loginToken = createRandomString(30);

            // create cookie
            Cookie loginCookie = new Cookie("login", loginToken);
            loginCookie.setPath("/");
            loginCookie.setMaxAge(defaultCookieTime.intValue());

            // write cookie to database
            ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken);
            JSONObject user_obj = new JSONObject();
            user_obj.put("id", identity.toString());
            user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime);
            DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent());

            response.addCookie(loginCookie);
            break;
        case "access-token": // create and display an access token

            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);

            break;
        default:
            throw new APIException(400, "Invalid type");
        }

        Log.getLog().info(
                "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost());

        result.put("message", "You are logged in as " + identity.getName());
        return result;
    } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge

        String login = post.get("login", null);
        String keyHash = post.get("keyhash", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        if (!DAO.login_keys.has(identity.toString())
                || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash))
            throw new APIException(400, "Unknown key");

        String challengeString = createRandomString(30);
        String newSessionID = createRandomString(30);

        ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange,
                newSessionID);
        Authentication challenge_auth = new Authentication(credential, DAO.authentication);
        challenge_auth.setIdentity(identity);
        challenge_auth.put("activated", true);

        challenge_auth.put("challenge", challengeString);
        challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash));
        challenge_auth.setExpireTime(60 * 10);

        JSONObject result = new JSONObject();
        result.put("challenge", challengeString);
        result.put("sessionID", newSessionID);
        result.put("message",
                "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID");
        return result;
    } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid

        String sessionID = post.get("sessionID", null);
        String challangeResponse = post.get("response", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID));
        ClientIdentity identity = authentication.getIdentity();

        String challenge = authentication.getString("challenge");
        PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA");

        Signature sig;
        boolean verified;
        try {
            sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(key);
            sig.update(challenge.getBytes());
            verified = sig.verify(Base64.getDecoder().decode(challangeResponse));
        } catch (NoSuchAlgorithmException e) {
            throw new APIException(400, "No such algorithm");
        } catch (InvalidKeyException e) {
            throw new APIException(400, "Invalid key");
        } catch (Throwable e) {
            throw new APIException(400, "Bad signature");
        }

        if (verified) {
            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            JSONObject result = new JSONObject();

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);
            return result;
        } else {
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");
            throw new APIException(400, "Bad Signature");
        }
    }
    throw new APIException(500, "Server error");
}

From source file:com.floreantpos.license.FiveStarPOSLicenseManager.java

private boolean verify(byte[] message, String signature, PublicKey publicKey) throws LicenseException {
    try {/*from   www. j  a  v a 2  s .  c  o  m*/

        Signature dsa = Signature.getInstance("SHA/DSA");
        dsa.initVerify(publicKey);
        dsa.update(message);

        byte[] decoded = Base64.getDecoder().decode(signature);
        return dsa.verify(decoded);

    } catch (Exception e) {
        throw new LicenseException("Invalid license key! Please contact our support.", e);
    }
}