Example usage for java.security PublicKey getFormat

List of usage examples for java.security PublicKey getFormat

Introduction

In this page you can find the example usage for java.security PublicKey getFormat.

Prototype

public String getFormat();

Source Link

Document

Returns the name of the primary encoding format of this key, or null if this key does not support encoding.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String algorithm = "DSA"; // or RSA, DH, etc.

    // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
    keyGen.initialize(1024);/*www  . j  av  a 2  s  .c o m*/
    KeyPair keypair = keyGen.genKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();
    String format = privateKey.getFormat(); // PKCS#8
    format = publicKey.getFormat(); // X.509
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    MainClass kpge = new MainClass();
    KeyPair kp = kpge.generateKeyPair(999);
    System.out.println("-- Public Key ----");
    PublicKey pubKey = kp.getPublic();
    System.out.println("   Algorithm=" + pubKey.getAlgorithm());
    System.out.println("   Encoded=" + pubKey.getEncoded());
    System.out.println("   Format=" + pubKey.getFormat());
}

From source file:Main.java

static PublicKey getRsaPublicKey(String n, String e) {
    BigInteger rsaN = null;/*from   w ww .  j ava 2  s.  c o  m*/
    BigInteger rsaE = null;

    try {
        rsaN = new BigInteger(n);
        rsaE = new BigInteger(e);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    RSAPublicKeySpec pubRsaSpec = new RSAPublicKeySpec(rsaN, rsaE);
    try {
        KeyFactory keyfact = KeyFactory.getInstance("RSA", "SC");
        PublicKey pk = keyfact.generatePublic(pubRsaSpec);
        Log.d("getRsaPublicKey", "pubRsaKey OK " + pk.getFormat());
        return pk;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:eu.dety.burp.joseph.attacks.key_confusion.KeyConfusionInfo.java

@Override
public KeyConfusion prepareAttack(IBurpExtenderCallbacks callbacks, IHttpRequestResponse requestResponse,
        IRequestInfo requestInfo, JoseParameter parameter) throws AttackPreparationFailedException {
    this.requestResponse = requestResponse;
    this.parameter = parameter;

    this.publicKeyVariations.clear();
    this.requests.clear();

    String publicKeyValue = publicKey.getText();

    // Throw error if public key value is empty
    if (publicKeyValue.isEmpty()) {
        throw new AttackPreparationFailedException(bundle.getString("PROVIDE_PUBKEY"));
    }//from w w  w .j av a2  s.  c om

    // Parse public key according to selected format
    int publicKeyFormat = publicKeySelection.getSelectedIndex();

    switch (publicKeyFormat) {
    // JWK (JSON)
    case 1:
        // TODO: Refactor to test every key at once? Requires change of HashMap key

        loggerInstance.log(getClass(), "Key format is JWK:  " + publicKeyValue, Logger.LogLevel.DEBUG);

        HashMap<String, PublicKey> publicKeys;
        PublicKey selectedPublicKey;

        try {
            Object publickKeyValueJson = new JSONParser().parse(publicKeyValue);

            publicKeys = Converter.getRsaPublicKeysByJwkWithId(publickKeyValueJson);
        } catch (Exception e) {
            loggerInstance.log(getClass(), "Error in prepareAttack (JWK):  " + e.getMessage(),
                    Logger.LogLevel.ERROR);
            throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_JWK"));
        }

        switch (publicKeys.size()) {
        // No suitable JWK in JWK Set found
        case 0:
            loggerInstance.log(getClass(), "Error in prepareAttack (JWK): No suitable JWK",
                    Logger.LogLevel.ERROR);
            throw new AttackPreparationFailedException(bundle.getString("NO_SUITABLE_JWK"));

            // Exactly one suitable JWK found
        case 1:
            selectedPublicKey = publicKeys.entrySet().iterator().next().getValue();
            break;

        // More than one suitable JWK found. Provide dialog to select one.
        default:
            selectedPublicKey = Converter.getRsaPublicKeyByJwkSelectionPanel(publicKeys);
        }

        try {
            loggerInstance.log(getClass(),
                    "Encoded PubKey: " + Base64.encodeBase64String(selectedPublicKey.getEncoded())
                            + "\nFormat: " + selectedPublicKey.getFormat(),
                    Logger.LogLevel.DEBUG);

            // PKCS#8 / X.509
            publicKeyVariations.put(PayloadType.PKCS8,
                    transformKeyByPayload(PayloadType.PKCS8, selectedPublicKey));

            // With header/footer
            publicKeyVariations.put(PayloadType.PKCS8_WITH_HEADER_FOOTER,
                    transformKeyByPayload(PayloadType.PKCS8_WITH_HEADER_FOOTER, selectedPublicKey));

            // With line feeds
            publicKeyVariations.put(PayloadType.PKCS8_WITH_LF,
                    transformKeyByPayload(PayloadType.PKCS8_WITH_LF, selectedPublicKey));

            // With line feeds and header/footer
            publicKeyVariations.put(PayloadType.PKCS8_WITH_HEADER_FOOTER_LF,
                    transformKeyByPayload(PayloadType.PKCS8_WITH_HEADER_FOOTER_LF, selectedPublicKey));

            // With line feeds and header/footer and additional line feed at end
            publicKeyVariations.put(PayloadType.PKCS8_WITH_HEADER_FOOTER_LF_ENDING_LF, transformKeyByPayload(
                    PayloadType.PKCS8_WITH_HEADER_FOOTER_LF_ENDING_LF, selectedPublicKey));

        } catch (Exception e) {
            throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_JWK"));
        }

        break;
    // PEM (String)
    default:
        loggerInstance.log(getClass(), "Key format is PEM:  " + publicKeyValue, Logger.LogLevel.DEBUG);

        // Simple check if String has valid format
        if (!publicKeyValue.trim().startsWith("-----BEGIN") && !publicKeyValue.trim().startsWith("MI")) {
            throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_PEM"));
        }

        try {
            // No modification
            publicKeyVariations.put(PayloadType.ORIGINAL, publicKeyValue);

            // Without header/footer
            publicKeyVariations.put(PayloadType.ORIGINAL_NO_HEADER_FOOTER,
                    transformKeyByPayload(PayloadType.ORIGINAL_NO_HEADER_FOOTER, publicKeyValue));

            // Without line feeds/carriage returns
            publicKeyVariations.put(PayloadType.ORIGINAL_NO_LF,
                    transformKeyByPayload(PayloadType.ORIGINAL_NO_LF, publicKeyValue));

            // Without header/footer and line feeds/carriage returns
            publicKeyVariations.put(PayloadType.ORIGINAL_NO_HEADER_FOOTER_LF,
                    transformKeyByPayload(PayloadType.ORIGINAL_NO_HEADER_FOOTER_LF, publicKeyValue));

            publicKeyVariations.put(PayloadType.ORIGINAL_ADDITIONAL_LF,
                    transformKeyByPayload(PayloadType.ORIGINAL_ADDITIONAL_LF, publicKeyValue));

            // PKCS#1, easy but hacky transformation
            publicKeyVariations.put(PayloadType.PKCS1,
                    transformKeyByPayload(PayloadType.PKCS1, publicKeyValue));

            // PKCS#1 without header/footer
            publicKeyVariations.put(PayloadType.PKCS1_NO_HEADER_FOOTER,
                    transformKeyByPayload(PayloadType.PKCS1_NO_HEADER_FOOTER, publicKeyValue));

            // PKCS#1 without line feeds/carriage returns
            publicKeyVariations.put(PayloadType.PKCS1_NO_LF,
                    transformKeyByPayload(PayloadType.PKCS1_NO_LF, publicKeyValue));

            // PKCS#1 without header/footer and line feeds/carriage
            // returns
            publicKeyVariations.put(PayloadType.PKCS1_NO_HEADER_FOOTER_LF,
                    transformKeyByPayload(PayloadType.PKCS1_NO_HEADER_FOOTER_LF, publicKeyValue));

        } catch (Exception e) {
            throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_PEM"));
        }

        break;
    }

    for (Map.Entry<PayloadType, String> publicKey : publicKeyVariations.entrySet()) {
        for (String algorithm : algorithms) {
            try {
                // Change the "alg" header value for each of the algorithms
                // entries
                String[] components = Decoder.getComponents(this.parameter.getJoseValue());
                String decodedHeader = Decoder.getDecoded(components[0]);
                String decodedHeaderReplacedAlgorithm = decodedHeader.replaceFirst("\"alg\":\"(.+?)\"",
                        "\"alg\":\"" + algorithm + "\"");
                String encodedHeaderReplacedAlgorithm = Decoder.getEncoded(decodedHeaderReplacedAlgorithm);

                String macAlg = Crypto.getMacAlgorithmByJoseAlgorithm(algorithm, "HmacSHA256");

                // Generate signature
                String newSignature = Decoder
                        .getEncoded(Crypto.generateMac(macAlg, helpers.stringToBytes(publicKey.getValue()),
                                helpers.stringToBytes(Decoder.concatComponents(
                                        new String[] { encodedHeaderReplacedAlgorithm, components[1] }))));

                // Build new JWS String and update parameter
                String[] newComponents = { encodedHeaderReplacedAlgorithm, components[1], newSignature };
                String newComponentsConcatenated = Decoder.concatComponents(newComponents);

                byte[] tmpRequest = JoseParameter.updateRequest(this.requestResponse.getRequest(),
                        this.parameter, helpers, newComponentsConcatenated);
                requests.add(new KeyConfusionAttackRequest(tmpRequest, publicKey.getKey().ordinal(), algorithm,
                        publicKey.getValue(), publicKey.getValue().length()));
            } catch (Exception e) {
                throw new AttackPreparationFailedException(
                        "Attack preparation failed. Message: " + e.getMessage());
            }
        }
    }

    this.amountRequests = requests.size();
    return new KeyConfusion(callbacks, this);
}