Example usage for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec

List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec

Introduction

In this page you can find the example usage for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec.

Prototype

public PKCS8EncodedKeySpec(byte[] encodedKey) 

Source Link

Document

Creates a new PKCS8EncodedKeySpec with the given encoded key.

Usage

From source file:net.padlocksoftware.padlock.KeyManager.java

/**
 * Import a Padlock 2.x (DSA based) KeyPair from an InputStream.  The stream is
 * assumed to have been previously exported in a supported format using the
 * exportKeyPair methods.//ww  w.ja  v a2s.c  o  m
 * @param stream The KeyPair stream to import.
 * @return The DSA KeyPair contained in the specified file.
 * @throws java.io.IOException If file is missing or contain invalid data.
 * @since 2.0
 */
public static KeyPair importKeyPair(InputStream stream) throws IOException {
    if (stream == null)
        throw new IllegalArgumentException("Stream cannot be null");

    KeyPair pair = null;
    Properties p = new Properties();
    p.load(stream);
    stream.close();
    String pri = p.getProperty("private");
    String pub = p.getProperty("public");

    if (pri == null || pub == null) {
        throw new IOException("Stream data is invalid");
    }

    // Load the keys
    try {

        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Hex.decodeHex(pri.toCharArray()));
        KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Hex.decodeHex(pub.toCharArray()));
        PublicKey publicKey = keyFactory.generatePublic(pubSpec);

        pair = new KeyPair(publicKey, privateKey);
    } catch (Exception e) {
        throw new RuntimeException("Invalid stream: " + e.getMessage());
    }

    return pair;
}

From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKey.java

protected PrivateKey getKey(String alg, byte[] data) throws GeneralSecurityException {
    if (alg.equals("RSA")) {
        try {/*from   w  ww.j ava2 s  .c o  m*/
            if (data.length == 0) {
                throw new GeneralSecurityException("Cannot process empty byte stream.");
            }
            ByteArrayInputStream bis = new ByteArrayInputStream(data);
            ASN1InputStream derin = new ASN1InputStream(bis);
            ASN1Primitive keyInfo = derin.readObject();

            DERObjectIdentifier rsaOid = PKCSObjectIdentifiers.rsaEncryption;
            AlgorithmIdentifier rsa = new AlgorithmIdentifier(rsaOid);
            PrivateKeyInfo pkeyinfo = new PrivateKeyInfo(rsa, keyInfo);
            ASN1Primitive derkey = pkeyinfo.toASN1Primitive();
            byte[] keyData = BouncyCastleUtil.toByteArray(derkey);
            // The DER object needs to be mangled to
            // create a proper ProvateKeyInfo object
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyData);
            KeyFactory kfac = KeyFactory.getInstance("RSA");

            return kfac.generatePrivate(spec);
        } catch (IOException e) {
            // that should never happen
            return null;
        }

    } else {
        return null;
    }
}

From source file:org.wso2.sample.identity.oauth2.IDTokenDecrypterServlet.java

/**
 * Decrypt the id token using the private key.
 *
 * @param JWE              id token to be decrypted
 * @param privateKeyString client private key as a string
 * @return decrypted id token as an EncryptedJWT object
 * @throws NoSuchAlgorithmException/*from www .j  av  a  2 s.co  m*/
 * @throws InvalidKeySpecException
 * @throws ParseException
 * @throws JOSEException
 * @throws IllegalArgumentException
 */
private EncryptedJWT decryptJWE(String JWE, String privateKeyString) throws NoSuchAlgorithmException,
        InvalidKeySpecException, ParseException, JOSEException, IllegalArgumentException {

    KeyFactory kf = KeyFactory.getInstance("RSA");
    // Remove EOF characters from key string and generate key object.
    privateKeyString = privateKeyString.replace("\n", "").replace("\r", "");
    PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));
    PrivateKey privateKey = kf.generatePrivate(keySpecPKCS8);

    EncryptedJWT jwt = EncryptedJWT.parse(JWE);

    // Create a decrypter with the specified private RSA key.
    RSADecrypter decrypter = new RSADecrypter((RSAPrivateKey) privateKey);

    jwt.decrypt(decrypter);

    return jwt;
}

From source file:pxb.android.tinysign.TinySign.java

private static Signature instanceSignature() throws Exception {
    byte[] data = dBase64(Constants.privateKey);
    KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = rSAKeyFactory.generatePrivate(new PKCS8EncodedKeySpec(data));
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);/*w  w  w  .jav a  2s.  com*/
    return signature;
}

From source file:info.magnolia.cms.security.SecurityUtil.java

public static String decrypt(String message, String encodedKey) throws SecurityException {
    try {//w  w w . j a v a2  s .  c  om
        if (StringUtils.isBlank(encodedKey)) {
            throw new SecurityException(
                    "Activation key was not found. Please make sure your instance is correctly configured.");
        }

        // decode key
        byte[] binaryKey = hexToByteArray(encodedKey);

        // create RSA public key cipher
        Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC");
        try {
            // create private key
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PublicKey pk = kf.generatePublic(publicKeySpec);
            pkCipher.init(Cipher.DECRYPT_MODE, pk);

        } catch (InvalidKeySpecException e) {
            // decrypting with private key?
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PrivateKey pk = kf.generatePrivate(privateKeySpec);
            pkCipher.init(Cipher.DECRYPT_MODE, pk);
        }

        // decrypt
        String[] chunks = StringUtils.split(message, ";");
        if (chunks == null) {
            throw new SecurityException(
                    "The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.");
        }
        StringBuilder clearText = new StringBuilder();
        for (String chunk : chunks) {
            byte[] byteChunk = hexToByteArray(chunk);
            clearText.append(new String(pkCipher.doFinal(byteChunk), "UTF-8"));
        }
        return clearText.toString();
    } catch (NumberFormatException e) {
        throw new SecurityException(
                "The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.",
                e);
    } catch (IOException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchPaddingException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (InvalidKeySpecException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (InvalidKeyException e) {
        throw new SecurityException(
                "Failed to read authentication string. Please use Java version with cryptography support.", e);
    } catch (NoSuchProviderException e) {
        throw new SecurityException(
                "Failed to find encryption provider. Please use Java version with cryptography support.", e);
    } catch (IllegalBlockSizeException e) {
        throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.",
                e);
    } catch (BadPaddingException e) {
        throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.",
                e);
    }

}

From source file:com.aqnote.shared.cryptology.asymmetric.DSA.java

/**
 * ?private key//w w  w.  jav a2  s  .c o m
 * 
 * @throws RuntimeException key
 */
public static PrivateKey readPrivateKey(byte[] keyBytes) throws RuntimeException {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        byte[] encodedKey = Base64.decodeBase64(keyBytes);
        EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
        return keyFactory.generatePrivate(keySpec);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:pepperim.util.IMCrypt.java

/**
 * @param b64str Base64-encoded private key
 * @return PrivateKey object//from w  ww.  jav a 2s  .c  om
 */
public static PrivateKey decodePrivateKey(String b64str) {
    try {
        byte[] keydata = B64_Dec(b64str);
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(keydata);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey pk = kf.generatePrivate(ks);
        return pk;
    } catch (GeneralSecurityException e) {
        Main.log(e.getMessage());
        return null;
    }
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

/**
 * Loader constructor. Loads an existing MyCareNet session key.
 * /*from  w w w . j av  a  2  s .  c o m*/
 * @param encodedPrivateKey
 * @param encodedPublicKey
 * @param encodedCertificate
 * @param notBefore
 * @param notAfter
 */
public SessionKey(byte[] encodedPrivateKey, byte[] encodedPublicKey, byte[] encodedCertificate, Date notBefore,
        Date notAfter) {
    this.notBefore = notBefore;
    this.notAfter = notAfter;

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("RSA", e);
    }
    PublicKey publicKey;
    try {
        publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid public key: " + e.getMessage(), e);
    }

    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey;
    try {
        privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid private key: " + e.getMessage(), e);
    }

    this.keyPair = new KeyPair(publicKey, privateKey);

    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
    try {
        this.certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException("certificate decoding error: " + e.getMessage(), e);
    }
}

From source file:info.globalbus.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;/*  www . j  av  a 2  s.co  m*/

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

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

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test
            // validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}

From source file:org.javlo.external.agitos.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;//  w  w w.j ava  2s  .  c o m

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

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

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                RSAPrivateKey pubKey = (RSAPrivateKey) keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}