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:com.launchkey.sdk.crypto.JCECrypto.java

private Signature getSha256withRSA() throws NoSuchAlgorithmException {
    return Signature.getInstance(RSA_SIGNING_ALGO, provider);
}

From source file:com.xk72.cocoafob.LicenseGenerator.java

/**
 * Verify the given license for the given {@link LicenseData}.
 * @param licenseData/*  ww  w  .j  a  v a  2  s  .  com*/
 * @param license
 * @return Whether the license verified successfully.
 * @throws LicenseGeneratorException If the verification encounters an error, usually due to invalid input. You MUST check the return value of this method if no exception is thrown.
 * @throws IllegalStateException If the generator is not setup correctly to verify licenses.
 */
public boolean verifyLicense(LicenseData licenseData, String license)
        throws LicenseGeneratorException, IllegalStateException {
    if (!isCanVerifyLicenses()) {
        throw new IllegalStateException(
                "The LicenseGenerator cannot verify licenses as it was not configured with a public key");
    }

    final String stringData = licenseData.toLicenseStringData();

    /* replace O with 8 and I with 9 */
    String licenseSignature = license.replace("8", "O").replace("9", "I");

    /* remove dashes */
    licenseSignature = licenseSignature.replace("-", "");

    /* Pad the output length to a multiple of 8 with '=' characters */
    while (licenseSignature.length() % 8 != 0) {
        licenseSignature += "=";
    }

    byte[] decoded = new Base32().decode(licenseSignature);
    try {
        Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
        dsa.initVerify(publicKey);
        dsa.update(stringData.getBytes("UTF-8"));
        return dsa.verify(decoded);
    } catch (NoSuchAlgorithmException e) {
        throw new LicenseGeneratorException(e);
    } catch (NoSuchProviderException e) {
        throw new LicenseGeneratorException(e);
    } catch (InvalidKeyException e) {
        throw new LicenseGeneratorException(e);
    } catch (SignatureException e) {
        throw new LicenseGeneratorException(e);
    } catch (UnsupportedEncodingException e) {
        throw new LicenseGeneratorException(e);
    }
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Decrypts a message.//from w w w . j  a  v  a 2  s  .c  o  m
 * @param args Arguments: enc, privateKey, sig, publicKey
 * @param callback Callback
 */
public static void decrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        // Get the arguments
        String enc = args.getString(0);
        String key = args.getString(1);
        String sig = null;
        String pub = null;
        if (args.length() == 4) {
            sig = args.getString(2);
            pub = args.getString(3);
        }
        Boolean ver = null;

        // Convert everything into byte arrays
        byte[] encRaw = Base64.decode(enc, Base64.DEFAULT);
        byte[] keyRaw = Base64.decode(stripKey(key), Base64.DEFAULT);

        // Verify signature
        if (sig != null && pub != null) {
            try {
                byte[] sigRaw = Base64.decode(sig, Base64.DEFAULT);
                byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);
                X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
                KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
                Signature s = Signature.getInstance("SHA1withRSA", "BC");
                s.initVerify(kf.generatePublic(publicKeySpec));
                s.update(encRaw);
                ver = s.verify(sigRaw);
            } catch (Exception ex) {
                Log.i("whistle", "Verification failed: " + ex.getMessage());
                ver = false;
            }
        }

        // Split enc into encrypted aes data and remaining enc
        byte[] encSplit = encRaw;
        byte[] aesRaw = new byte[RSA_BYTES];
        System.arraycopy(encSplit, 0, aesRaw, 0, aesRaw.length);
        encRaw = new byte[encSplit.length - RSA_BYTES];
        System.arraycopy(encSplit, RSA_BYTES, encRaw, 0, encRaw.length);

        // Decrypt encrypted aes data using RSAES-OAEP
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        Cipher c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding");
        c.init(Cipher.DECRYPT_MODE, kf.generatePrivate(privateKeySpec));
        aesRaw = c.doFinal(aesRaw);

        // Decrypted enc using AES-CBC
        byte[] aesKey = new byte[AES_BYTES];
        byte[] aesIv = new byte[aesRaw.length - aesKey.length];
        System.arraycopy(aesRaw, 0, aesKey, 0, aesKey.length);
        System.arraycopy(aesRaw, aesKey.length, aesIv, 0, aesIv.length);
        c = Cipher.getInstance("AES/CBC/PKCS7Padding");
        c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));
        byte[] dec = c.doFinal(encRaw);

        JSONArray res = new JSONArray();
        res.put(new String(dec, "utf-8"));
        res.put(ver);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Decrypt error:" + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:cn.mrdear.pay.util.RSAUtils.java

/**
 * ???//from   w w w.  j a v a2 s . c  o m
 * 
 * @param algorithm
 *            ??
 * @param publicKey
 *            
 * @param sign
 *            ??
 * @param data
 *            ?
 * @return ??
 */
public static boolean verify(String algorithm, PublicKey publicKey, byte[] sign, byte[] data) {
    Assert.isNotEmpty(algorithm);
    Assert.notNull(publicKey);
    Assert.notNull(sign);
    Assert.notNull(data);

    try {
        Signature signature = Signature.getInstance(algorithm, PROVIDER);
        signature.initVerify(publicKey);
        signature.update(data);
        return signature.verify(sign);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (SignatureException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

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

public void testHandleMessagePSS() throws Exception {
    // setup/*from   w w w  . j a  va 2 s . co  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-PSS");

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

    Signature signature = Signature.getInstance("SHA1withRSA/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.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java

@Override
public String sign(String signingInput, String alias, String sharedSecret,
        SignatureAlgorithm signatureAlgorithm) throws Exception {
    if (signatureAlgorithm == SignatureAlgorithm.NONE) {
        return "";
    } else if (SignatureAlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) {
        SecretKey secretKey = new SecretKeySpec(sharedSecret.getBytes(Util.UTF8_STRING_ENCODING),
                signatureAlgorithm.getAlgorithm());
        Mac mac = Mac.getInstance(signatureAlgorithm.getAlgorithm());
        mac.init(secretKey);//from   w w w  . j a v a2 s.  c  o m
        byte[] sig = mac.doFinal(signingInput.getBytes());
        return Base64Util.base64urlencode(sig);
    } else { // EC or RSA
        PrivateKey privateKey = getPrivateKey(alias);

        Signature signature = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC");
        //Signature signature = Signature.getInstance(signatureAlgorithm.getAlgorithm());
        signature.initSign(privateKey);
        signature.update(signingInput.getBytes());

        return Base64Util.base64urlencode(signature.sign());
    }
}

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

@Test
public void testPSS() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC");

    byte[] data = "hello world".getBytes();

    signature.initSign(privateKey);/*from  w w w  . j a  v a 2  s  .  c  om*/
    signature.update(data);
    byte[] signatureValue = signature.sign();

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

    LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue)));

    signature.initVerify(publicKey);
    signature.update(data);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    signature.initSign(privateKey);
    signature.update(data);
    byte[] signatureValue2 = signature.sign();

    LOG.debug("signature size: " + signatureValue2.length);

    LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue2)));

    assertFalse(Arrays.equals(signatureValue, signatureValue2));

    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256", "BC");
    byte[] digest = messageDigest.digest(data);

    signature = Signature.getInstance("RAWRSASSA-PSS", "BC");
    signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
    signature.initVerify(publicKey);
    signature.update(digest);
    result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:cn.mrdear.pay.util.RSAUtils.java

/**
 * ???//from  w ww  .  ja  v  a 2  s.c  o m
 * 
 * @param algorithm
 *            ??
 * @param certificate
 *            ?
 * @param sign
 *            ??
 * @param data
 *            ?
 * @return ??
 */
public static boolean verify(String algorithm, Certificate certificate, byte[] sign, byte[] data) {
    Assert.isNotEmpty(algorithm);
    Assert.notNull(certificate);
    Assert.notNull(sign);
    Assert.notNull(data);

    try {
        Signature signature = Signature.getInstance(algorithm, PROVIDER);
        signature.initVerify(certificate);
        signature.update(data);
        return signature.verify(sign);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (SignatureException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java

@Override
public boolean verifySignature(String signingInput, String encodedSignature, String alias, JSONObject jwks,
        String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws Exception {
    boolean verified = false;

    if (signatureAlgorithm == SignatureAlgorithm.NONE) {
        return Util.isNullOrEmpty(encodedSignature);
    } else if (SignatureAlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) {
        String expectedSignature = sign(signingInput, null, sharedSecret, signatureAlgorithm);
        return expectedSignature.equals(encodedSignature);
    } else { // EC or RSA
        PublicKey publicKey = null;

        try {// www. j a va 2s.c o m
            if (jwks == null) {
                publicKey = getPublicKey(alias);
            } else {
                publicKey = getPublicKey(alias, jwks);
            }
            if (publicKey == null) {
                return false;
            }

            byte[] signature = Base64Util.base64urldecode(encodedSignature);

            Signature verifier = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC");
            //Signature verifier = Signature.getInstance(signatureAlgorithm.getAlgorithm());
            verifier.initVerify(publicKey);
            verifier.update(signingInput.getBytes());
            verified = verifier.verify(signature);
        } catch (NoSuchAlgorithmException e) {
            LOG.error(e.getMessage(), e);
            verified = false;
        } catch (SignatureException e) {
            LOG.error(e.getMessage(), e);
            verified = false;
        } catch (InvalidKeyException e) {
            LOG.error(e.getMessage(), e);
            verified = false;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            verified = false;
        }
    }

    return verified;
}

From source file:com.alfaariss.oa.engine.core.crypto.CryptoManager.java

/**
 * Retrieve an instance of the configured {@link Signature}.    
 * @return The configured type of Signature.
 * @throws CryptoException If creation fails. 
 * @see <a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html#Signature">
 *  The Signature Class</a>//from  w  w  w .  j av a 2s .c o m
 */
public Signature getSignature() throws CryptoException {
    Signature signature = null;
    if (_sSigningAlgorithm != null) //Signing enabled
    {
        try {
            if (_sSigningProvider != null)
                signature = Signature.getInstance(_sSigningAlgorithm, _sSigningProvider);
            else
                signature = Signature.getInstance(_sSigningAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            _logger.error("Invalid signature algorithm", e);
            throw new CryptoException(SystemErrors.ERROR_INTERNAL);
        } catch (NoSuchProviderException e) {
            _logger.error("Invalid signature provider", e);
            throw new CryptoException(SystemErrors.ERROR_INTERNAL);
        }

        _logger.debug("Established Signature instance of provider " + signature.getProvider().getName());
    } else
        _logger.debug("Signing disabled");

    return signature;
}