Example usage for java.security KeyFactory getInstance

List of usage examples for java.security KeyFactory getInstance

Introduction

In this page you can find the example usage for java.security KeyFactory getInstance.

Prototype

public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyFactory object that converts public/private keys of the specified algorithm.

Usage

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * RSA??/* w w w.ja va 2s .c  o m*/
 * <dl>
 * <dt>?
 * <dd>RSA??
 * </dl>
 * @param name RSA???
 * @return RSA?
 */
public KeyPair loadKeyPair(final String name) {
    try {
        final Properties property = new PropertyService(PROPERTY_NAME).getProperty();
        final KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGO_NAME);
        final RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(
                Hex.decodeHex(property.getProperty(String.format(KEY_PUBLIC_ENCODED, name)).toCharArray())));
        final RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(
                Hex.decodeHex(property.getProperty(String.format(KEY_PRIVATE_ENCODED, name)).toCharArray())));
        return new KeyPair(publicKey, privateKey);
    } catch (final IOException | DecoderException | InvalidKeySpecException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.abdera2.common.security.DHBase.java

private Key decode(byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException {
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
    KeyFactory keyFact = KeyFactory.getInstance("DH");
    return keyFact.generatePublic(x509KeySpec);
}

From source file:gemlite.core.util.RSAUtils.java

/**
 * <P>//from  www  .  j a  v  a 2s. c  o  m
 * ?
 * </p>
 * 
 * @param encryptedData
 *          ?
 * @param privateKey
 *          ?(BASE64?)
 * @return
 * @throws Exception
 */
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
    byte[] keyBytes = Base64Utils.decode(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateK);
    int inputLen = encryptedData.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // ?
    while (inputLen - offSet > 0) {
        if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
            cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
        } else {
            cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        i++;
        offSet = i * MAX_DECRYPT_BLOCK;
    }
    byte[] decryptedData = out.toByteArray();
    out.close();
    return decryptedData;
}

From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java

/**
 * // ww w  . jav a  2s  .  c o m
 * 
 * 
 * @param info ?
 * @return ?
 * @throws GeneralSecurityException GeneralSecurityException
 */
public String decode(String info) throws GeneralSecurityException {
    byte[] priKeyText = this.getPriKeyText();
    PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKeyText));
    KeyFactory keyFactory = null;
    if (provider == null) {
        keyFactory = KeyFactory.getInstance(ALGORITHM);
    } else {
        keyFactory = KeyFactory.getInstance(ALGORITHM, provider);
    }
    // ??
    PrivateKey priKey = keyFactory.generatePrivate(priPKCS8);
    // ?CipherECB?PKCS5Padding
    Cipher cipher = null;
    if (provider == null) {
        cipher = Cipher.getInstance(ALGORITHM);
    } else {
        cipher = Cipher.getInstance(ALGORITHM, provider);
    }
    // ?
    cipher.init(Cipher.DECRYPT_MODE, priKey);
    byte[] newPlainText = cipher.doFinal(Base64.decodeBase64(info.getBytes()));
    return new String(newPlainText);
}

From source file:com.jinhe.tss.core.common.license.LicenseManager.java

/**
 * ?license??/* w ww .  ja  va2s  .c om*/
 * ?Mac??????
 * ???????
 * 
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.getMacAddress();
    if (macAddress != null && macAddress.length() > 0) {
        String curMacAddress = MacAddressUtil.getMacAddress();
        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:org.mitre.jwt.JwtTest.java

/**
 * @throws Exception//from  www . j  a va2s. c  o m
 */
@Test
public void testGenerateRsaSignature() throws Exception {

    // Hard code the private/public key so as not to depend on it being in
    // the keystore...

    RSAPrivateKeySpec privateSpec = new RSAPrivateKeySpec(new BigInteger(
            "AD6E684550542947AD95EF9BACDC0AC2C9168C6EB3212D378C23E5539266111DB2E5B4D42B1E47EB4F7A65DB63D9782C72BC365492FD1E5C7B4CD2174C611668C29013FEDE22619B3F58DA3531BB6C02B3266768B7895CBDAFB3F9AC7A7B2F3DB17EF4DCF03BD2575604BDE0A01BB1FB7B0E733AD63E464DB4D7D89626297A214D7CECCD0C50421A322A01E9DCEA23443F6A9339576B31DFA504A133076394562CB57F3FDEDB26F9A82BED2F6D52D6F6BF8286E2497EF0B5C8456F32B4668F5A9F5FCD3781345DDDB749792C37238A53D18FD976C0C9D1F1E211F1A4A9AAE679C45B92D1741EF0D3C3F373232CE7FB93E9BC461E1C508A20B74E7E3361B3C527",
            16),
            new BigInteger(
                    "627CDD67E75B33EA0990A8F64DEED389942A62EB867C23B274B9F9C440D2078C47089D6D136369D21E5B52B688F8797F3C54D7C1A58B6A8F7851C2C90A4DE42CEFB864328B31191ED19582AD4CA5B38BC0F2E12C9D75BB1DD946AA55A1648D0A4ADEDEED0CDBDBF24EDDF87A345225FBBB0114BCE7E78B831B5CAC197068837AB0B3F07157952A05F67A72B9852972C704B6B32A70C3BB3DEB186936B0F7D6ABE012DEB89BC2DBE1F88AE7A28C06C53D1FB2459E58D8ED266E3BFC28266981D2A5F624D36555DD64F410461ADA5D53F448BA5EEBBD4BCEC3AF53285FB394650D7B3BFB06712E081AAD160EED6E83A3EA2D092712C07A6331209F62D27184BFC9",
                    16));

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    PrivateKey privateKey = keyFactory.generatePrivate(privateSpec);

    RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(new BigInteger(
            "AD6E684550542947AD95EF9BACDC0AC2C9168C6EB3212D378C23E5539266111DB2E5B4D42B1E47EB4F7A65DB63D9782C72BC365492FD1E5C7B4CD2174C611668C29013FEDE22619B3F58DA3531BB6C02B3266768B7895CBDAFB3F9AC7A7B2F3DB17EF4DCF03BD2575604BDE0A01BB1FB7B0E733AD63E464DB4D7D89626297A214D7CECCD0C50421A322A01E9DCEA23443F6A9339576B31DFA504A133076394562CB57F3FDEDB26F9A82BED2F6D52D6F6BF8286E2497EF0B5C8456F32B4668F5A9F5FCD3781345DDDB749792C37238A53D18FD976C0C9D1F1E211F1A4A9AAE679C45B92D1741EF0D3C3F373232CE7FB93E9BC461E1C508A20B74E7E3361B3C527",
            16), new BigInteger("10001", 16));

    PublicKey publicKey = keyFactory.generatePublic(publicSpec);

    Jwt jwt = new Jwt();
    jwt.getHeader().setType("JWT");
    jwt.getHeader().setAlgorithm("RS256");
    jwt.getClaims().setExpiration(new Date(1300819380L * 1000L));
    jwt.getClaims().setIssuer("joe");
    jwt.getClaims().setClaim("http://example.com/is_root", Boolean.TRUE);

    JwtSigner signer = new RsaSigner(JwsAlgorithm.RS256.getJwaName(), publicKey, privateKey);
    ((RsaSigner) signer).afterPropertiesSet();

    /*
     * Expected string based on the following structures, serialized exactly
     * as follows and base64 encoded:
     * 
     * header: {"typ":"JWT","alg":"HS256"} claims:
     * {"exp":1300819380,"iss":"joe","http://example.com/is_root":true}
     * 
     * Expected signature: dSRvtD-ExzGN-
     * fRXd1wRZOPo1JFPuqgwvaIKp8jgcyMXJegy6IUjssfUfUcICN5yvh0ggOMWMeWkwQ7
     * -PlXMJWymdhXVI3BOpNt7ZOB2vMFYSOOHNBJUunQoe1lmNxuHQdhxqoHahn3u1cLDXz
     * -xx-
     * JELduuMmaDWqnTFPodVPl45WBKHaQhlOiFWj3ZClUV2k5p2yBT8TmxekL8gWwgVbQk5yPnYOs
     * -PcMjzODc9MZX4yI10ZSCSDciwf-
     * rgkQLT7wW4uZCoqTZ7187sCodHd6nw3nghqbtqN05fQ3Yq7ykwaR8pdQBFb2L9l7DhLLuXIREDKIFUHBSUs8OnvXFMg
     */

    String signature = "dSRvtD-ExzGN-fRXd1wRZOPo1JFPuqgwvaIKp8jgcyMXJegy6IUjssfUfUcICN5yvh0ggOMWMeWkwQ7-PlXMJWymdhXVI3BOpNt7ZOB2vMFYSOOHNBJUunQoe1lmNxuHQdhxqoHahn3u1cLDXz-xx-JELduuMmaDWqnTFPodVPl45WBKHaQhlOiFWj3ZClUV2k5p2yBT8TmxekL8gWwgVbQk5yPnYOs-PcMjzODc9MZX4yI10ZSCSDciwf-rgkQLT7wW4uZCoqTZ7187sCodHd6nw3nghqbtqN05fQ3Yq7ykwaR8pdQBFb2L9l7DhLLuXIREDKIFUHBSUs8OnvXFMg";
    String expected = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJleHAiOjEzMDA4MTkzODAsImlzcyI6ImpvZSIsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
            + "." + signature;

    signer.sign(jwt);

    String actual = jwt.toString();

    assertThat(signer.verify(actual), equalTo(true));
    assertThat(actual, equalTo(expected));
    assertThat(jwt.getSignature(), equalTo(signature));
}

From source file:com.znsx.util.licence.LicenceUtil.java

/**
 * ???/*from   w  w w.j a  v  a2 s . com*/
 * 
 * @param data
 *            ??
 * @param publicKeyString
 *            ??base64?
 * @param signature
 *            base64????
 * @return
 * @throws Exception
 */
public static boolean verify(String data, String publicKeyString, String signature) throws Exception {
    // ???
    // BASE64Decoder decoder = new BASE64Decoder();
    // byte[] bytes = decoder.decodeBuffer(publicKeyString);
    Base64 base64 = new Base64();
    byte[] bytes = base64.decode(publicKeyString.getBytes("utf8"));
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
    PublicKey publicKey = KeyFactory.getInstance("DSA").generatePublic(keySpec);
    // ?
    Signature sign = Signature.getInstance("DSA");
    sign.initVerify(publicKey);
    sign.update(data.getBytes("utf8"));
    // return sign.verify(decoder.decodeBuffer(signature));
    return sign.verify(base64.decode(signature.getBytes("utf8")));
}

From source file:com.ibm.dbwkl.helper.CryptionModule.java

/**
 * @return PublicKey Instance//w ww.j  a  v a 2s . co m
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws InvalidKeySpecException
 */
private RSAPublicKey getPublicKey() throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    KeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(PUBLIC_KEY));
    RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);

    return publicKey;
}

From source file:com.vmware.o11n.plugin.crypto.model.CryptoUtil.java

/**
 * Generate a RSA Public Key from a KeySpec
 *
 * @param keySpec//  w  w w .  j  a v a 2 s  .  c  o  m
 * @return RSA Public Key
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
private static PublicKey getPublicKey(KeySpec keySpec)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory fac = KeyFactory.getInstance(KEYFACTORY_ALGORITHM);
    return fac.generatePublic(keySpec);
}

From source file:license.regist.ReadProjectInfo.java

static PublicKey readPublicKeyFromFile() throws Exception {
    ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(KeyData.publicKey));
    try {/*from   w  w w .j  a  va2s  .  c  o  m*/
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        return fact.generatePublic(keySpec);
    } finally {
        oin.close();
    }
}