Java 类java.security.spec.EncodedKeySpec 实例源码

项目:DecompiledMinecraft    文件:CryptManager.java   
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
项目:DecompiledMinecraft    文件:CryptManager.java   
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
项目:BaseClient    文件:CryptManager.java   
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
项目:BaseClient    文件:CryptManager.java   
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
项目:JWT4B    文件:AlgorithmLinker.java   
private static PublicKey generatePublicKeyFromString(String key, String algorithm) {
    PublicKey publicKey = null;
    if(key.length()>1){
        key = key.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s+", "").replaceAll("\\r+", "").replaceAll("\\n+", "");
        byte[] keyByteArray = java.util.Base64.getDecoder().decode(key);
        try {
            KeyFactory kf = KeyFactory.getInstance(algorithm);
            EncodedKeySpec keySpec = new X509EncodedKeySpec(keyByteArray);
            publicKey = kf.generatePublic(keySpec);
        } catch (Exception e) {
            ConsoleOut.output(e.getMessage());
        }
    }
    return publicKey;
}
项目:JWT4B    文件:AlgorithmLinker.java   
private static PrivateKey generatePrivateKeyFromString(String key, String algorithm) {
    PrivateKey privateKey = null;
    if(key.length()>1){
        key = key.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "")
             .replaceAll("\\s+", "").replaceAll("\\r+", "").replaceAll("\\n+", "");
        byte[] keyByteArray = Base64.decode(key);
        try {
            KeyFactory kf = KeyFactory.getInstance(algorithm);
            EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyByteArray);
            privateKey = kf.generatePrivate(keySpec);
        } catch (Exception e) {
            ConsoleOut.output(e.getMessage());
        }
    }
    return privateKey;
}
项目:Backmemed    文件:CryptManager.java   
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
项目:CustomWorldGen    文件:CryptManager.java   
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
项目:http4e    文件:CryptUtils.java   
/**
 * Method convertes the bytes arrays back to private and public key objects
 */
public static Key[] bytesToPrivatePublicKeys( String algorithm, byte[] privKeyBytes, byte[] pubKeyBytes) throws Exception{
   PrivateKey privKey = null;
   PublicKey pubKey = null;
   KeyFactory keyFactory = KeyFactory.getInstance(algorithm);

   if (privKeyBytes != null) {
      EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
      privKey = keyFactory.generatePrivate(privateKeySpec);
   }

   if (pubKeyBytes != null) {
      EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);
      pubKey = keyFactory.generatePublic(publicKeySpec);
   }

   return new Key[] { privKey, pubKey };
}
项目:routing-bird    文件:RsaSha1MessageSigner.java   
@Override
public String sign(HttpRequest request, HttpParameters requestParams) throws OAuthMessageSignerException {
    byte[] decodedPrivateKey;
    try {
        decodedPrivateKey = Base64.decode(getConsumerSecret());
        String baseString = new SignatureBaseString(request, requestParams).generate();
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_TYPE);
        EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedPrivateKey);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        signature.initSign(privateKey);
        signature.update(baseString.getBytes());
        byte[] rsasha1 = signature.sign();
        return Base64.encode(rsasha1);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | SignatureException e) {
        throw new OAuthMessageSignerException(e);
    }
}
项目:routing-bird    文件:SimpleRsaSha1Method.java   
/**
 * Generates the RSA-SHA1 signature of OAuth request elements.
 *
 * @param baseString the combined OAuth elements to sign.
 * @param secrets    the secrets object containing the private key for generating the signature.
 * @return the OAuth signature, in base64-encoded form.
 * @throws InvalidSecretException if the supplied secret is not valid.
 */
@Override
public String sign(final String baseString, final OAuth1Secrets secrets) throws InvalidSecretException {

    byte[] decodedPrivateKey;
    try {
        decodedPrivateKey = Base64.decode(secrets.getConsumerSecret());
    } catch (IOException ioe) {
        throw new InvalidSecretException(LocalizationMessages.ERROR_INVALID_CONSUMER_SECRET(ioe));
    }

    try {
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_TYPE);
        EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedPrivateKey);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        signature.initSign(privateKey);
        signature.update(baseString.getBytes());
        byte[] rsasha1 = signature.sign();
        return Base64.encode(rsasha1);
    } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | SignatureException e) {
        throw new IllegalStateException(e);
    }
}
项目:j2objc    文件:EncodedKeySpecTest.java   
/**
 * Tests that <code>getEncoded()</code> method returns valid byte array
 */
public final void testGetEncoded() {

    byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check returned array */
    boolean result = true;
    for (int i = 0; i < encodedKey.length; i++) {
        if (encodedKey[i] != ek[i]) {
            /* indicate failure */
            result = false;
        }
    }
    /* passed */
    assertTrue(result);
}
项目:j2objc    文件:EncodedKeySpecTest.java   
/**
 * Tests that internal state of the object can not be modified by modifying
 * initial array value
 */
public final void testIsStatePreserved1() {
    /* Create initial byte array */
    byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };

    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Modify initial array's value */
    encodedKey[3] = (byte) 5;

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek[3] == (byte) 4);
}
项目:j2objc    文件:EncodedKeySpecTest.java   
/**
 * Tests that internal state of the object can not be modified using
 * returned value of <code>getEncoded()</code> method
 */
public final void testIsStatePreserved2() {

    byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();
    /* Modify returned value */
    ek[3] = (byte) 5;
    /* Get encoded key again */
    byte[] ek1 = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek1[3] == (byte) 4);
}
项目:In-the-Box-Fork    文件:EncodedKeySpecTest.java   
/**
 * Tests that <code>getEncoded()</code> method returns valid byte array
 */
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "",
    method = "getEncoded",
    args = {}
)
public final void testGetEncoded() {

    byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check returned array */
    boolean result = true;
    for (int i = 0; i < encodedKey.length; i++) {
        if (encodedKey[i] != ek[i]) {
            /* indicate failure */
            result = false;
        }
    }
    /* passed */
    assertTrue(result);
}
项目:In-the-Box-Fork    文件:EncodedKeySpecTest.java   
/**
 * Tests that internal state of the object can not be modified by modifying
 * initial array value
 */
@TestTargetNew(
    level = TestLevel.PARTIAL_COMPLETE,
    notes = "",
    method = "getEncoded",
    args = {}
)
public final void testIsStatePreserved1() {
    /* Create initial byte array */
    byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };

    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Modify initial array's value */
    encodedKey[3] = (byte) 5;

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek[3] == (byte) 4);
}
项目:In-the-Box-Fork    文件:EncodedKeySpecTest.java   
/**
 * Tests that internal state of the object can not be modified using
 * returned value of <code>getEncoded()</code> method
 */
@TestTargetNew(
    level = TestLevel.PARTIAL_COMPLETE,
    notes = "",
    method = "getEncoded",
    args = {}
)
public final void testIsStatePreserved2() {

    byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();
    /* Modify returned value */
    ek[3] = (byte) 5;
    /* Get encoded key again */
    byte[] ek1 = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek1[3] == (byte) 4);
}
项目:In-the-Box-Fork    文件:PKCS8EncodedKeySpecTest.java   
/**
 * Test for <code>PKCS8EncodedKeySpec</code> constructor<br>
 * Assertion: constructs new <code>PKCS8EncodedKeySpec</code>
 * object using valid parameter
 */
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "",
    method = "PKCS8EncodedKeySpec",
    args = {byte[].class}
)
public final void testPKCS8EncodedKeySpec() {
    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};

    EncodedKeySpec eks = new PKCS8EncodedKeySpec(encodedKey);

    assertTrue(eks instanceof PKCS8EncodedKeySpec);
    try {
        eks = new PKCS8EncodedKeySpec(null);
        fail("expected NullPointerException");
    } catch (NullPointerException e) {
        // ok
    }
}
项目:In-the-Box-Fork    文件:X509EncodedKeySpecTest.java   
/**
 * Test for <code>X509EncodedKeySpec</code> constructor<br>
 * Assertion: constructs new <code>X509EncodedKeySpec</code>
 * object using valid parameter
 */
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "",
    method = "X509EncodedKeySpec",
    args = {byte[].class}
)
public final void testX509EncodedKeySpec() {
    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};

    EncodedKeySpec eks = new X509EncodedKeySpec(encodedKey);

    assertTrue(eks instanceof X509EncodedKeySpec);
    try {
        eks = new X509EncodedKeySpec(null);
        fail("expected NullPointerException");
    } catch (NullPointerException e) {
        // ok
    }
}
项目:cypher    文件:RSAKey.java   
/**
 * @return an RSA decryption cipher
 */
protected synchronized AsymmetricBlockCipher getRSADecryptCipher()
{
    if (decodeCipher == null)
    {
        try
        {
            byte[] bytes = getEncoder().decode(privateKey);
            EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bytes);

            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            PrivateKey key = keyFactory.generatePrivate(privateKeySpec);

            this.decodeCipher = new PKCS1Encoding(new RSABlindedEngine());
            decodeCipher.init(false, generatePrivateKeyParameter((RSAPrivateKey) key));
        }
        catch (Exception e)
        {
            throw new RuntimeException("Error constructing Cipher: ", e);
        }
    }

    return decodeCipher;
}
项目:cypher    文件:RSAKey.java   
/**
 * @return
 */
protected synchronized AsymmetricBlockCipher getRSAEncryptCipher()
{
    if (encodeCipher == null)
    {
        try
        {
            byte[] bytes = getEncoder().decode(publicKey);
            EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bytes);

            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            PublicKey key = keyFactory.generatePublic(publicKeySpec);

            this.encodeCipher = new PKCS1Encoding(new RSABlindedEngine());
            encodeCipher.init(true, generatePublicKeyParameter((RSAPublicKey) key));
        }
        catch (Exception e)
        {
            throw new RuntimeException("Error constructing Cipher: ", e);
        }
    }

    return encodeCipher;
}
项目:cn1    文件:EncodedKeySpecTest.java   
/**
 * Tests that <code>getEncoded()</code> method
 * returns valid byte array
 */
public final void testGetEncoded() {

    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check returned array */
    boolean result = true;
    for (int i=0; i<encodedKey.length; i++) {
        if (encodedKey[i] != ek[i]) {
            /* indicate failure */
            result = false;
        }
    }
    /* passed */
    assertTrue(result);
}
项目:cn1    文件:EncodedKeySpecTest.java   
/**
 * Tests that internal state of the object
 * can not be modified by modifying initial array value
 */
public final void testIsStatePreserved1() {
    /* Create initial byte array */
    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};

    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Modify initial array's value */
    encodedKey[3] = (byte)5;

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek[3] == (byte)4);
}
项目:cn1    文件:EncodedKeySpecTest.java   
/**
 * Tests that internal state of the object
 * can not be modified using returned value
 * of <code>getEncoded()</code> method 
*/
public final void testIsStatePreserved2() {

    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();        
    /* Modify returned value */
    ek[3] = (byte)5;
    /* Get encoded key again */
    byte[] ek1 = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek1[3] == (byte)4);
}
项目:CERTUS-Server    文件:RSAKeys.java   
public static Validator getPrivateKey (byte[] encodedPrivateKey){
    Validator vKey = new Validator();

    try {
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
                encodedPrivateKey);
        KeyFactory generator = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = generator.generatePrivate(privateKeySpec);

        vKey.setVerified(true);
        vKey.setObject(privateKey);
    } catch (Exception e) {
        vKey.setVerified(false);
        vKey.setStatus("Convertion of bytes to private key failed");
    }

    return vKey;
}
项目:freeVM    文件:EncodedKeySpecTest.java   
/**
 * Tests that <code>getEncoded()</code> method
 * returns valid byte array
 */
public final void testGetEncoded() {

    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check returned array */
    boolean result = true;
    for (int i=0; i<encodedKey.length; i++) {
        if (encodedKey[i] != ek[i]) {
            /* indicate failure */
            result = false;
        }
    }
    /* passed */
    assertTrue(result);
}
项目:freeVM    文件:EncodedKeySpecTest.java   
/**
 * Tests that internal state of the object
 * can not be modified by modifying initial array value
 */
public final void testIsStatePreserved1() {
    /* Create initial byte array */
    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};

    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Modify initial array's value */
    encodedKey[3] = (byte)5;

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek[3] == (byte)4);
}
项目:freeVM    文件:EncodedKeySpecTest.java   
/**
 * Tests that internal state of the object
 * can not be modified using returned value
 * of <code>getEncoded()</code> method 
*/
public final void testIsStatePreserved2() {

    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();        
    /* Modify returned value */
    ek[3] = (byte)5;
    /* Get encoded key again */
    byte[] ek1 = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek1[3] == (byte)4);
}
项目:freeVM    文件:EncodedKeySpecTest.java   
/**
 * Tests that <code>getEncoded()</code> method
 * returns valid byte array
 */
public final void testGetEncoded() {

    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check returned array */
    boolean result = true;
    for (int i=0; i<encodedKey.length; i++) {
        if (encodedKey[i] != ek[i]) {
            /* indicate failure */
            result = false;
        }
    }
    /* passed */
    assertTrue(result);
}
项目:freeVM    文件:EncodedKeySpecTest.java   
/**
 * Tests that internal state of the object
 * can not be modified by modifying initial array value
 */
public final void testIsStatePreserved1() {
    /* Create initial byte array */
    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};

    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Modify initial array's value */
    encodedKey[3] = (byte)5;

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek[3] == (byte)4);
}
项目:freeVM    文件:EncodedKeySpecTest.java   
/**
 * Tests that internal state of the object
 * can not be modified using returned value
 * of <code>getEncoded()</code> method 
*/
public final void testIsStatePreserved2() {

    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();        
    /* Modify returned value */
    ek[3] = (byte)5;
    /* Get encoded key again */
    byte[] ek1 = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek1[3] == (byte)4);
}
项目:holico    文件:CertificateMessage.java   
/**
 * @return the peer's public contained in its certificate.
 */
public PublicKey getPublicKey() {
    PublicKey publicKey = null;

    if (rawPublicKeyBytes == null) {
        publicKey = certificateChain[0].getPublicKey();
    } else {
        // get server's public key from Raw Public Key
        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(rawPublicKeyBytes);
        try {
            // TODO make instance variable
            publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
        } catch (Exception e) {
            LOG.severe("Could not reconstruct the server's public key.");
            e.printStackTrace();
        }
    }
    return publicKey;

}
项目:pay-me    文件:DefaultSignatureValidatorTest.java   
@Test public void shouldValidateTheSHA1WithRSASignature() throws Exception {
    // create a public/private key pair
    KeyFactory keyFactory   = KeyFactory.getInstance("RSA");
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    KeyPair pair = keyGen.generateKeyPair();
    EncodedKeySpec encoded = new X509EncodedKeySpec(pair.getPublic().getEncoded());
    PublicKey encodedPublic = keyFactory.generatePublic(encoded);
    String encodePublicBase64 = Base64.encodeToString(encodedPublic.getEncoded(), Base64.DEFAULT);

    // and sign some data with it
    Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(pair.getPrivate());
    String data = "some sample data";
    sig.update(data.getBytes());

    String signature = Base64.encodeToString(sig.sign(), Base64.DEFAULT);

    SignatureValidator validator = new DefaultSignatureValidator(encodePublicBase64);
    assertThat(validator.validate(data, signature)).isTrue();
    assertThat(validator.validate(data+"extraData", signature)).isFalse();
}
项目:zrtp-java    文件:BCDHSuite.java   
@Override
public byte[] getDhResult(byte[] aMsg, int offset , boolean isLegacyClient) throws ZrtpException {
    try {
        int PV_LENGTH = keyType.pvLengthInWords * 4;
        byte[] encodedKey = new byte[keyType.pvLengthInWords * 4 + 1];
        encodedKey[0] = 4;
        System.arraycopy(aMsg, offset, encodedKey, 1, encodedKey.length - 1);
        EncodedKeySpec keySpec = getSpec(encodedKey, keyPair.getPublic());
        PublicKey pub = keyFactory.generatePublic(keySpec);
        KeyAgreement agreement = KeyAgreement.getInstance(algorithm, "ZBC");
        agreement.init(keyPair.getPrivate());
        agreement.doPhase(pub, true);
        byte[] secret = agreement.generateSecret();
        byte[] iDHResult = null;
        if(!isLegacyClient) {
            iDHResult = new byte[secret.length];
            System.arraycopy(secret, 0, iDHResult, 0, secret.length);    
        } else {
            iDHResult = new byte[PV_LENGTH];
            System.arraycopy(secret, 0, iDHResult, iDHResult.length - secret.length, secret.length);    
        }
        return iDHResult;
    } catch (Exception e) {
        throw new ZrtpException(e);
    }
}
项目:delta-sdk-java    文件:CryptoService.java   
/**
 * Transforms the private key, encoded as a base 64 string, into a private
 * key instance.
 *
 * @param key private key as a base64 encoded string
 * @return the private key
 * @throws DeltaClientException on error creating private key from string
 */
public PrivateKey getPrivateKey(String key) throws DeltaClientException {
    try {
        byte[] byteKey = BaseEncoding.base64().decode(key);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(byteKey);
        return keyFactory.generatePrivate(privateKeySpec);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException | IllegalArgumentException e) {
        throw new DeltaClientException("Error creating private key from string", e);
    }
}
项目:adblib    文件:AdbCrypto.java   
/**
 * Creates a new AdbCrypto object from a key pair loaded from files.
 *
 * @param base64     Implementation of base 64 conversion interface required by ADB
 * @param privateKey File containing the RSA private key
 * @param publicKey  File containing the RSA public key
 * @return New AdbCrypto object
 * @throws IOException              If the files cannot be read
 * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
 * @throws InvalidKeySpecException  If a PKCS8 or X509 key spec cannot be found
 */
public static AdbCrypto loadAdbKeyPair(AdbBase64 base64, File privateKey, File publicKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    AdbCrypto crypto = new AdbCrypto();

    int privKeyLength = (int) privateKey.length();
    int pubKeyLength = (int) publicKey.length();
    byte[] privKeyBytes = new byte[privKeyLength];
    byte[] pubKeyBytes = new byte[pubKeyLength];

    FileInputStream privIn = new FileInputStream(privateKey);
    FileInputStream pubIn = new FileInputStream(publicKey);

    privIn.read(privKeyBytes);
    pubIn.read(pubKeyBytes);

    privIn.close();
    pubIn.close();

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);

    crypto.keyPair = new KeyPair(keyFactory.generatePublic(publicKeySpec),
            keyFactory.generatePrivate(privateKeySpec));
    crypto.base64 = base64;

    return crypto;
}
项目:AppOpsX    文件:AdbCrypto.java   
/**
 * Creates a new AdbCrypto object from a key pair loaded from files.
 * @param base64 Implementation of base 64 conversion interface required by ADB 
 * @param privateKey File containing the RSA private key
 * @param publicKey File containing the RSA public key
 * @return New AdbCrypto object
 * @throws IOException If the files cannot be read
 * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
 * @throws InvalidKeySpecException If a PKCS8 or X509 key spec cannot be found
 */
public static AdbCrypto loadAdbKeyPair(AdbBase64 base64, File privateKey, File publicKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
{
    AdbCrypto crypto = new AdbCrypto();

    int privKeyLength = (int)privateKey.length();
    int pubKeyLength = (int)publicKey.length();
    byte[] privKeyBytes = new byte[privKeyLength];
    byte[] pubKeyBytes = new byte[pubKeyLength];

    FileInputStream privIn = new FileInputStream(privateKey);
    FileInputStream pubIn = new FileInputStream(publicKey);

    privIn.read(privKeyBytes);
    pubIn.read(pubKeyBytes);

    privIn.close();
    pubIn.close();

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);

    crypto.keyPair = new KeyPair(keyFactory.generatePublic(publicKeySpec),
            keyFactory.generatePrivate(privateKeySpec));
    crypto.base64 = base64;

    return crypto;
}
项目:excellent-ball    文件:AdbCrypto.java   
/**
 * Creates a new AdbCrypto object from a key pair loaded from files.
 *
 * @param base64     Implementation of base 64 conversion interface required by ADB
 * @param privateKey File containing the RSA private key
 * @param publicKey  File containing the RSA public key
 * @return New AdbCrypto object
 * @throws IOException              If the files cannot be read
 * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
 * @throws InvalidKeySpecException  If a PKCS8 or X509 key spec cannot be found
 */
public static AdbCrypto loadAdbKeyPair(AdbBase64 base64, File privateKey, File publicKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    AdbCrypto crypto = new AdbCrypto();

    int privKeyLength = (int) privateKey.length();
    int pubKeyLength = (int) publicKey.length();
    byte[] privKeyBytes = new byte[privKeyLength];
    byte[] pubKeyBytes = new byte[pubKeyLength];

    FileInputStream privIn = new FileInputStream(privateKey);
    FileInputStream pubIn = new FileInputStream(publicKey);

    privIn.read(privKeyBytes);
    pubIn.read(pubKeyBytes);

    privIn.close();
    pubIn.close();

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);

    crypto.keyPair = new KeyPair(keyFactory.generatePublic(publicKeySpec),
            keyFactory.generatePrivate(privateKeySpec));
    crypto.base64 = base64;

    return crypto;
}
项目:http4e    文件:TestCrypt.java   
private static void testPublicPrivateKeys(){
   try {
      String keyAlgorithm = "RSA";
      Key[] keys = CryptUtils.generatePrivatePublicKeys(keyAlgorithm, 1024);
      Key kPriv = keys[0];
      Key kPub = keys[1];
      byte[] kPubBytes = kPub.getEncoded();
      byte[] kPrivBytes = kPriv.getEncoded();
      System.out.println("--------------PublicKey----------------");
      System.out.println(kPub);
      System.out.println(kPub.getAlgorithm());
      System.out.println(kPub.getEncoded());
      System.out.println("--------------PrivateKey----------------");
      System.out.println(kPriv);
      System.out.println(kPriv.getAlgorithm());
      System.out.println(kPriv.getEncoded());

      // The bytes can be converted back to public and private key objects
      KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
      EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(kPrivBytes);
      PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec);

      EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(kPubBytes);
      PublicKey publicKey2 = keyFactory.generatePublic(publicKeySpec);

      // The original and new keys are the same
      System.out.println("  Are both private keys equal? " + kPriv.equals(privateKey2));

      System.out.println("  Are both public keys equal? " + kPub.equals(publicKey2));
   } catch (Exception e) {
      e.printStackTrace();
   }
}
项目:BigApp_Discuz_Android    文件:Rsa.java   
/**
 * Generates Public Key from BASE64 encoded string
 * 
 * @param key
 *            BASE64 encoded string which represents the key
 * @return The PublicKey
 * @throws java.lang.Exception
 */
public static PublicKey getPublicKeyFromBase64String(String base64PublicKey) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("Rsa");

        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decode(base64PublicKey));
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
        return publicKey;
    } catch (Exception ex) {
        Log.e(LOGTAG,ex.getMessage());
        return null;
    }
}