Search in sources :

Example 66 with KeyGenerator

use of javax.crypto.KeyGenerator in project android_frameworks_base by AOSPA.

the class SystemKeyStore method generateNewKey.

public byte[] generateNewKey(int numBits, String algName, String keyName) throws NoSuchAlgorithmException {
    // Check if key with similar name exists. If so, return null.
    File keyFile = getKeyFile(keyName);
    if (keyFile.exists()) {
        throw new IllegalArgumentException();
    }
    KeyGenerator skg = KeyGenerator.getInstance(algName);
    SecureRandom srng = SecureRandom.getInstance("SHA1PRNG");
    skg.init(numBits, srng);
    SecretKey sk = skg.generateKey();
    byte[] retKey = sk.getEncoded();
    try {
        // Store the key
        if (!keyFile.createNewFile()) {
            throw new IllegalArgumentException();
        }
        FileOutputStream fos = new FileOutputStream(keyFile);
        fos.write(retKey);
        fos.flush();
        FileUtils.sync(fos);
        fos.close();
        FileUtils.setPermissions(keyFile.getName(), (FileUtils.S_IRUSR | FileUtils.S_IWUSR), -1, -1);
    } catch (IOException ioe) {
        return null;
    }
    return retKey;
}
Also used : SecretKey(javax.crypto.SecretKey) FileOutputStream(java.io.FileOutputStream) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) File(java.io.File) KeyGenerator(javax.crypto.KeyGenerator)

Example 67 with KeyGenerator

use of javax.crypto.KeyGenerator in project jdk8u_jdk by JetBrains.

the class TestHmacSHAOids method runTest.

private static void runTest(DataTuple dataTuple) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    Mac mcAlgorithm = Mac.getInstance(dataTuple.algorithm, PROVIDER_NAME);
    Mac mcOid = Mac.getInstance(dataTuple.oid, PROVIDER_NAME);
    if (mcAlgorithm == null) {
        throw new RuntimeException(String.format("Test failed: Mac using algorithm " + "string %s getInstance failed.%n", dataTuple.algorithm));
    }
    if (mcOid == null) {
        throw new RuntimeException(String.format("Test failed: Mac using OID %s getInstance failed.%n", dataTuple.oid));
    }
    if (!mcAlgorithm.getAlgorithm().equals(dataTuple.algorithm)) {
        throw new RuntimeException(String.format("Test failed: Mac using algorithm string %s getInstance " + "doesn't generate expected algorithm.%n", dataTuple.algorithm));
    }
    KeyGenerator kg = KeyGenerator.getInstance(dataTuple.algorithm, PROVIDER_NAME);
    SecretKey key = kg.generateKey();
    mcAlgorithm.init(key);
    mcAlgorithm.update(INPUT);
    mcOid.init(key);
    mcOid.update(INPUT);
    // Comparison
    if (!Arrays.equals(mcAlgorithm.doFinal(), mcOid.doFinal())) {
        throw new RuntimeException("Digest comparison failed: " + "the two MACs are not the same");
    }
}
Also used : SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator) Mac(javax.crypto.Mac)

Example 68 with KeyGenerator

use of javax.crypto.KeyGenerator in project jdk8u_jdk by JetBrains.

the class TestKeyMaterial method main.

public static void main(String[] args) throws Exception {
    Provider provider = Security.getProvider("SunJCE");
    InputStream in = new FileInputStream(new File(BASE, "keymatdata.txt"));
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    int n = 0;
    int lineNumber = 0;
    byte[] master = null;
    int major = 0;
    int minor = 0;
    byte[] clientRandom = null;
    byte[] serverRandom = null;
    String cipherAlgorithm = null;
    int keyLength = 0;
    int expandedKeyLength = 0;
    int ivLength = 0;
    int macLength = 0;
    byte[] clientCipherBytes = null;
    byte[] serverCipherBytes = null;
    byte[] clientIv = null;
    byte[] serverIv = null;
    byte[] clientMacBytes = null;
    byte[] serverMacBytes = null;
    while (true) {
        String line = reader.readLine();
        lineNumber++;
        if (line == null) {
            break;
        }
        if (line.startsWith("km-") == false) {
            continue;
        }
        String data = line.substring(PREFIX_LENGTH);
        if (line.startsWith("km-master:")) {
            master = parse(data);
        } else if (line.startsWith("km-major:")) {
            major = Integer.parseInt(data);
        } else if (line.startsWith("km-minor:")) {
            minor = Integer.parseInt(data);
        } else if (line.startsWith("km-crandom:")) {
            clientRandom = parse(data);
        } else if (line.startsWith("km-srandom:")) {
            serverRandom = parse(data);
        } else if (line.startsWith("km-cipalg:")) {
            cipherAlgorithm = data;
        } else if (line.startsWith("km-keylen:")) {
            keyLength = Integer.parseInt(data);
        } else if (line.startsWith("km-explen:")) {
            expandedKeyLength = Integer.parseInt(data);
        } else if (line.startsWith("km-ivlen:")) {
            ivLength = Integer.parseInt(data);
        } else if (line.startsWith("km-maclen:")) {
            macLength = Integer.parseInt(data);
        } else if (line.startsWith("km-ccipkey:")) {
            clientCipherBytes = parse(data);
        } else if (line.startsWith("km-scipkey:")) {
            serverCipherBytes = parse(data);
        } else if (line.startsWith("km-civ:")) {
            clientIv = parse(data);
        } else if (line.startsWith("km-siv:")) {
            serverIv = parse(data);
        } else if (line.startsWith("km-cmackey:")) {
            clientMacBytes = parse(data);
        } else if (line.startsWith("km-smackey:")) {
            serverMacBytes = parse(data);
            System.out.print(".");
            n++;
            KeyGenerator kg = KeyGenerator.getInstance("SunTlsKeyMaterial", provider);
            SecretKey masterKey = new SecretKeySpec(master, "TlsMasterSecret");
            TlsKeyMaterialParameterSpec spec = new TlsKeyMaterialParameterSpec(masterKey, major, minor, clientRandom, serverRandom, cipherAlgorithm, keyLength, expandedKeyLength, ivLength, macLength, null, -1, -1);
            kg.init(spec);
            TlsKeyMaterialSpec result = (TlsKeyMaterialSpec) kg.generateKey();
            match(lineNumber, clientCipherBytes, result.getClientCipherKey());
            match(lineNumber, serverCipherBytes, result.getServerCipherKey());
            match(lineNumber, clientIv, result.getClientIv());
            match(lineNumber, serverIv, result.getServerIv());
            match(lineNumber, clientMacBytes, result.getClientMacKey());
            match(lineNumber, serverMacBytes, result.getServerMacKey());
        } else {
            throw new Exception("Unknown line: " + line);
        }
    }
    if (n == 0) {
        throw new Exception("no tests");
    }
    in.close();
    System.out.println();
    System.out.println("OK: " + n + " tests");
}
Also used : Provider(java.security.Provider) SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator)

Example 69 with KeyGenerator

use of javax.crypto.KeyGenerator in project jdk8u_jdk by JetBrains.

the class TestPRF method main.

public static void main(String[] args) throws Exception {
    Provider provider = Security.getProvider("SunJCE");
    InputStream in = new FileInputStream(new File(BASE, "prfdata.txt"));
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    int n = 0;
    int lineNumber = 0;
    byte[] secret = null;
    String label = null;
    byte[] seed = null;
    int length = 0;
    byte[] output = null;
    while (true) {
        String line = reader.readLine();
        lineNumber++;
        if (line == null) {
            break;
        }
        if (line.startsWith("prf-") == false) {
            continue;
        }
        String data = line.substring(PREFIX_LENGTH);
        if (line.startsWith("prf-secret:")) {
            secret = parse(data);
        } else if (line.startsWith("prf-label:")) {
            label = data;
        } else if (line.startsWith("prf-seed:")) {
            seed = parse(data);
        } else if (line.startsWith("prf-length:")) {
            length = Integer.parseInt(data);
        } else if (line.startsWith("prf-output:")) {
            output = parse(data);
            System.out.print(".");
            n++;
            KeyGenerator kg = KeyGenerator.getInstance("SunTlsPrf", provider);
            SecretKey inKey;
            if (secret == null) {
                inKey = null;
            } else {
                inKey = new SecretKeySpec(secret, "Generic");
            }
            TlsPrfParameterSpec spec = new TlsPrfParameterSpec(inKey, label, seed, length, null, -1, -1);
            kg.init(spec);
            SecretKey key = kg.generateKey();
            byte[] enc = key.getEncoded();
            if (Arrays.equals(output, enc) == false) {
                throw new Exception("mismatch line: " + lineNumber);
            }
        } else {
            throw new Exception("Unknown line: " + line);
        }
    }
    if (n == 0) {
        throw new Exception("no tests");
    }
    in.close();
    System.out.println();
    System.out.println("OK: " + n + " tests");
}
Also used : Provider(java.security.Provider) SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator)

Example 70 with KeyGenerator

use of javax.crypto.KeyGenerator in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_detached_signature.

static boolean test_create_detached_signature(String canonicalizationMethod, String signatureMethod, String digestMethod, String transform, KeyInfoType keyInfo, Content contentType, int port) throws Exception {
    System.out.print("Sign ...");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    // Create SignedInfo
    DigestMethod dm = fac.newDigestMethod(digestMethod, null);
    List transformList = null;
    if (transform != null) {
        TransformParameterSpec params = null;
        switch(transform) {
            case Transform.XPATH:
                params = new XPathFilterParameterSpec("//.");
                break;
            case Transform.XPATH2:
                params = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType("//.", XPathType.Filter.INTERSECT)));
                break;
            case Transform.XSLT:
                Element element = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xslt.getBytes())).getDocumentElement();
                DOMStructure stylesheet = new DOMStructure(element);
                params = new XSLTTransformParameterSpec(stylesheet);
                break;
        }
        transformList = Collections.singletonList(fac.newTransform(transform, params));
    }
    String url = String.format("http://localhost:%d/%s", port, contentType);
    List refs = Collections.singletonList(fac.newReference(url, dm, transformList, null, null));
    CanonicalizationMethod cm = fac.newCanonicalizationMethod(canonicalizationMethod, (C14NMethodParameterSpec) null);
    SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);
    Key signingKey;
    Key validationKey;
    switch(signatureMethod) {
        case SignatureMethod.DSA_SHA1:
        case SignatureMethod.RSA_SHA1:
            KeyPair kp = generateKeyPair(sm);
            validationKey = kp.getPublic();
            signingKey = kp.getPrivate();
            break;
        case SignatureMethod.HMAC_SHA1:
            KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
            signingKey = kg.generateKey();
            validationKey = signingKey;
            break;
        default:
            throw new RuntimeException("Unsupported signature algorithm");
    }
    SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
    // Create KeyInfo
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List list = null;
    if (keyInfo == KeyInfoType.KeyValue) {
        if (validationKey instanceof PublicKey) {
            KeyValue kv = kif.newKeyValue((PublicKey) validationKey);
            list = Collections.singletonList(kv);
        }
    } else if (keyInfo == KeyInfoType.x509data) {
        list = Collections.singletonList(kif.newX509Data(Collections.singletonList("cn=Test")));
    } else if (keyInfo == KeyInfoType.KeyName) {
        list = Collections.singletonList(kif.newKeyName("Test"));
    } else {
        throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);
    }
    KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;
    // Create an empty doc for detached signature
    Document doc = dbf.newDocumentBuilder().newDocument();
    DOMSignContext xsc = new DOMSignContext(signingKey, doc);
    // Generate signature
    XMLSignature signature = fac.newXMLSignature(si, ki);
    signature.sign(xsc);
    // Save signature
    String signatureString;
    try (StringWriter writer = new StringWriter()) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        Node parent = xsc.getParent();
        trans.transform(new DOMSource(parent), new StreamResult(writer));
        signatureString = writer.toString();
    }
    System.out.print("Validate ... ");
    try (ByteArrayInputStream bis = new ByteArrayInputStream(signatureString.getBytes())) {
        doc = dbf.newDocumentBuilder().parse(bis);
    }
    NodeList nodeLst = doc.getElementsByTagName("Signature");
    Node node = nodeLst.item(0);
    if (node == null) {
        throw new RuntimeException("Couldn't find Signature element");
    }
    if (!(node instanceof Element)) {
        throw new RuntimeException("Unexpected node type");
    }
    Element sig = (Element) node;
    // Validate signature
    DOMValidateContext vc = new DOMValidateContext(validationKey, sig);
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
    signature = fac.unmarshalXMLSignature(vc);
    boolean success = signature.validate(vc);
    if (!success) {
        System.out.println("Core signature validation failed");
        return false;
    }
    success = signature.getSignatureValue().validate(vc);
    if (!success) {
        System.out.println("Cryptographic validation of signature failed");
        return false;
    }
    return true;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) KeyGenerator(javax.crypto.KeyGenerator) KeyPair(java.security.KeyPair) StreamResult(javax.xml.transform.stream.StreamResult) PublicKey(java.security.PublicKey) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey)

Aggregations

KeyGenerator (javax.crypto.KeyGenerator)464 SecretKey (javax.crypto.SecretKey)343 Test (org.junit.Test)106 ArrayList (java.util.ArrayList)104 SecureRandom (java.security.SecureRandom)99 Document (org.w3c.dom.Document)98 InputStream (java.io.InputStream)95 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)93 ByteArrayOutputStream (java.io.ByteArrayOutputStream)87 NodeList (org.w3c.dom.NodeList)82 Cipher (javax.crypto.Cipher)79 ByteArrayInputStream (java.io.ByteArrayInputStream)75 XMLStreamReader (javax.xml.stream.XMLStreamReader)68 XMLSecurityProperties (org.apache.xml.security.stax.ext.XMLSecurityProperties)68 DocumentBuilder (javax.xml.parsers.DocumentBuilder)62 Key (java.security.Key)58 QName (javax.xml.namespace.QName)47 IOException (java.io.IOException)45 SecurePart (org.apache.xml.security.stax.ext.SecurePart)40 SecretKeySpec (javax.crypto.spec.SecretKeySpec)39