Java Examples for com.sun.crypto.provider.SunJCE

The following java examples will help you to understand the usage of com.sun.crypto.provider.SunJCE. These source code samples are taken from different open source projects.

Example 1
Project: jdk7u-jdk-master  File: TestKATForECB_VK.java View source code
public boolean execute() throws Exception {
    String transformation = ALGO + "/" + MODE + "/" + PADDING;
    Cipher c = Cipher.getInstance(transformation, "SunJCE");
    for (int i = 0; i < KEY_SIZES.length; i++) {
        if (KEY_SIZES[i] * 8 > Cipher.getMaxAllowedKeyLength(transformation)) {
            // configured in the jce jurisdiction policy files
            continue;
        }
        int rounds = KEY_SIZES[i] * 8;
        byte[] plainText = PT;
        byte[] cipherText = null;
        try {
            for (int j = 0; j < rounds; j++) {
                SecretKey aesKey = constructAESKey(KEY_SIZES[i], j);
                c.init(Cipher.ENCRYPT_MODE, aesKey);
                cipherText = c.doFinal(plainText);
                byte[] answer = constructByteArray(CTS[i][j]);
                if (!Arrays.equals(cipherText, answer)) {
                    throw new Exception((i + 1) + "th known answer test failed for encryption");
                }
                c.init(Cipher.DECRYPT_MODE, aesKey);
                byte[] restored = c.doFinal(cipherText);
                if (!Arrays.equals(plainText, restored)) {
                    throw new Exception((i + 1) + "th known answer test failed for decryption");
                }
            }
            System.out.println("Finished KAT for " + KEY_SIZES[i] + "-byte key");
        } catch (SecurityException se) {
            TestUtil.handleSE(se);
        }
    }
    // passed all tests...hooray!
    return true;
}
Example 2
Project: openjdk8-jdk-master  File: SunJCEGetInstance.java View source code
public static void main(String[] args) throws Exception {
    Cipher jce;
    try {
        // Remove SunJCE from Provider list
        Security.removeProvider("SunJCE");
        // Create our own instance of SunJCE provider.  Purposefully not
        // using SunJCE.getInstance() so we can have our own instance
        // for the test.
        jce = Cipher.getInstance("AES/CBC/PKCS5Padding", new com.sun.crypto.provider.SunJCE());
        jce.init(Cipher.ENCRYPT_MODE, new SecretKeySpec("1234567890abcedf".getBytes(), "AES"));
        jce.doFinal("PlainText".getBytes());
    } catch (Exception e) {
        System.err.println("Setup failure:  ");
        throw e;
    }
    // would occur on this line.
    try {
        jce.getParameters().getEncoded();
    } catch (Exception e) {
        System.err.println("Test Failure");
        throw e;
    }
    System.out.println("Passed");
}
Example 3
Project: ManagedRuntimeInitiative-master  File: TestProviderLeak.java View source code
public static void main(String[] args) throws Exception {
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1", "SunJCE");
    PBEKeySpec pbeKS = new PBEKeySpec("passPhrase".toCharArray(), new byte[] { 0 }, 5, 512);
    for (int i = 0; i <= 1000; i++) {
        try {
            skf.generateSecret(pbeKS);
            if ((i % 20) == 0) {
                // Calling gc() isn't dependable, but doesn't hurt.
                // Gives better output in leak cases.
                System.gc();
                dumpMemoryStats("Iteration " + i);
            }
        } catch (Exception e) {
            dumpMemoryStats("\nException seen at iteration " + i);
            throw e;
        }
    }
}
Example 4
Project: wycheproof-master  File: TestUtil.java View source code
public static void installOnlyOpenJDKProviders() throws Exception {
    for (Provider p : Security.getProviders()) {
        Security.removeProvider(p.getName());
    }
    installOpenJDKProvider("com.sun.net.ssl.internal.ssl.Provider");
    installOpenJDKProvider("com.sun.crypto.provider.SunJCE");
    installOpenJDKProvider("com.sun.security.sasl.Provider");
    installOpenJDKProvider("org.jcp.xml.dsig.internal.dom.XMLDSigRI");
    installOpenJDKProvider("sun.security.ec.SunEC");
    installOpenJDKProvider("sun.security.jgss.SunProvider");
    installOpenJDKProvider("sun.security.provider.Sun");
    installOpenJDKProvider("sun.security.rsa.SunRsaSign");
    installOpenJDKProvider("sun.security.smartcardio.SunPCSC");
}
Example 5
Project: des-cript-master  File: TestTripleDES.java View source code
@Override
protected void setUp() throws Exception {
    localcript = new TripleDES();
    texttocript = "Solvo Servicos de informatica";
    try {
        Cipher c = Cipher.getInstance("DESede");
        c.getAlgorithm();
    } catch (Exception e) {
        Provider sunjce = new com.sun.crypto.provider.SunJCE();
        Security.addProvider(sunjce);
    }
}
Example 6
Project: windowtester-master  File: ContactManagerSwing.java View source code
public void run() {
    // Create and set up the window.
    JFrame frame = new JFrame("Contact Manager");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    //frame.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
    JMenuBar menuBar = getInstance().createMenuBar();
    frame.setJMenuBar(menuBar);
    // Create and set up the content pane.
    ContactManagerSwing demo = getInstance();
    demo.setOpaque(true);
    frame.setContentPane(demo);
    // Display the window.
    frame.pack();
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    frame.setVisible(true);
    System.out.println(System.getProperty("java.class.path"));
}
Example 7
Project: wattzap-ce-master  File: IncryptDecrypt.java View source code
/*
	 * Lots of exceptions can be thrown here. I've chosen not to deal with them
	 * and just let the application fail. These exceptions are:
	 * javax.crypto.IllegalBlockException javax.crypto.BadPaddingException
	 * java.securty.InvalidKeyException
	 */
public static void main(String[] args) throws Exception {
    // This statement is not needed since the SunJCE is
    // (statically) installed as of SDK 1.4. Do this to
    // dynamically install another provider.
    // Security.addProvider(new com.sun.crypto.provider.SunJCE());
    // Generate a secret key for a symmetric algorithm and
    // create a Cipher instance. DESede key size is always
    // 168 bits. Other algorithms, like "blowfish", allow
    // for variable lenght keys.
    // KeyGenerator keyGenerator =
    // KeyGenerator.getInstance("DESede");
    SecretKeyFactory keyGenerator = SecretKeyFactory.getInstance("DES");
    // keyGenerator.init(168);
    DESKeySpec keySpec = new DESKeySpec("afghanistanbananstan".getBytes("UTF8"));
    SecretKey secretKey = keyGenerator.generateSecret(keySpec);
    cipher = Cipher.getInstance("DES");
    // Store the string as an array of bytes. You should
    // specify the encoding method for consistent encoding
    // and decoding across different platforms.
    String clearText = "480";
    byte[] clearTextBytes = clearText.getBytes("UTF8");
    // Initialize the cipher and encrypt this byte array
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] cipherBytes = cipher.doFinal(clearTextBytes);
    String cipherText = toHexString(cipherBytes);
    cipherBytes = toByteArray(cipherText);
    // Reinitialize the cipher an decrypt the byte array
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    byte[] decryptedBytes = cipher.doFinal(cipherBytes);
    String decryptedText = new String(decryptedBytes, "UTF8");
    System.out.println("Before encryption: " + clearText);
    System.out.println("After encryption: " + cipherText.toString());
    System.out.println("After decryption: " + decryptedText);
}
Example 8
Project: openjdk-master  File: ProviderConfig.java View source code
/**
     * Get the provider object. Loads the provider if it is not already loaded.
     */
// com.sun.net.ssl.internal.ssl.Provider has been deprecated since JDK 9
@SuppressWarnings("deprecation")
synchronized Provider getProvider() {
    // volatile variable load
    Provider p = provider;
    if (p != null) {
        return p;
    }
    if (shouldLoad() == false) {
        return null;
    }
    // Create providers which are in java.base directly
    if (provName.equals("SUN") || provName.equals("sun.security.provider.Sun")) {
        p = new sun.security.provider.Sun();
    } else if (provName.equals("SunRsaSign") || provName.equals("sun.security.rsa.SunRsaSign")) {
        p = new sun.security.rsa.SunRsaSign();
    } else if (provName.equals("SunJCE") || provName.equals("com.sun.crypto.provider.SunJCE")) {
        p = new com.sun.crypto.provider.SunJCE();
    } else if (provName.equals("SunJSSE") || provName.equals("com.sun.net.ssl.internal.ssl.Provider")) {
        p = new com.sun.net.ssl.internal.ssl.Provider();
    } else if (provName.equals("Apple") || provName.equals("apple.security.AppleProvider")) {
        // need to use reflection since this class only exists on MacOsx
        p = AccessController.doPrivileged(new PrivilegedAction<Provider>() {

            public Provider run() {
                try {
                    Class<?> c = Class.forName("apple.security.AppleProvider");
                    if (Provider.class.isAssignableFrom(c)) {
                        @SuppressWarnings("deprecation") Object tmp = c.newInstance();
                        return (Provider) tmp;
                    } else {
                        return null;
                    }
                } catch (Exception ex) {
                    if (debug != null) {
                        debug.println("Error loading provider Apple");
                        ex.printStackTrace();
                    }
                    return null;
                }
            }
        });
    } else {
        if (isLoading) {
            // happen if there is recursion.
            if (debug != null) {
                debug.println("Recursion loading provider: " + this);
                new Exception("Call trace").printStackTrace();
            }
            return null;
        }
        try {
            isLoading = true;
            tries++;
            p = doLoadProvider();
        } finally {
            isLoading = false;
        }
    }
    provider = p;
    return p;
}
Example 9
Project: WSign-master  File: ReciprocalUtils.java View source code
private static SecretKey generatorDefaultKey(String algorithm) {
    try {
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        KeyGenerator _generator = KeyGenerator.getInstance(algorithm);
        _generator.init(new SecureRandom(defaultKey.getBytes()));
        SecretKey key = _generator.generateKey();
        _generator = null;
        return key;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 10
Project: jeffaschenk-commons-master  File: FrameworkKeyStore.java View source code
// Create an empty keystore.
private void createKeyStore(String keyStoreFilename) {
    FileOutputStream fos = null;
    try {
        // Create an instance of a keystore.
        KeyStore ks;
        if (useSunJCE) {
            ks = KeyStore.getInstance("JCEKS", "SunJCE");
        } else {
            ks = KeyStore.getInstance("JCEKS");
        }
        // Convert the specified keystore password to a character array.
        char p[] = new char[keystorePassword.length()];
        keystorePassword.getChars(0, p.length, p, 0);
        // Load an empty keystore with the specified keystore password.
        ks.load(null, p);
        // Write the keystore with the specified keystore password to the specified file.
        fos = new FileOutputStream(keyStoreFilename);
        ks.store(fos, p);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception ignore) {
            }
        }
    }
}
Example 11
Project: red5-mavenized-master  File: HMACTest.java View source code
@Test
public void testHMAC() {
    HMAC h1 = new HMAC();
    assertNotNull(h1);
    try {
        Provider sp = new com.sun.crypto.provider.SunJCE();
        Security.addProvider(sp);
    } catch (Exception e) {
        fail("Problem loading crypto provider" + e);
    }
    //String[] args = new String[]{};
    //h1.processCommandLine(args);
    byte[] hmac = h1.computeMac();
    assertNull("Currently HMAC is broken since you can't actually " + "set the keyData or data elements.  This test will break once someone fixes that", hmac);
//HMAC.message("Result: " + HMAC.byteArrayToHex(hmac));
}
Example 12
Project: jPOS-master  File: JCESecurityModule.java View source code
/**
     * Initializes the JCE Security Module
     * @param jceProviderClassName
     * @param lmkFile Local Master Keys File used by JCE Security Module to store the LMKs
     * @param lmkRebuild if set to true, the lmkFile gets overwritten with newly generated keys (WARNING: this would render all your previously stored SecureKeys unusable)
     * @throws SMException
     */
private void init(String jceProviderClassName, String lmkFile, boolean lmkRebuild) throws SMException {
    File lmk = new File(lmkFile);
    try {
        keyTypeToLMKIndex = new TreeMap<String, Integer>();
        keyTypeToLMKIndex.put(SMAdapter.TYPE_ZMK, 0x000);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_ZPK, 0x001);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_PVK, 0x002);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_TPK, 0x002);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_TMK, 0x002);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_TAK, 0x003);
        //            keyTypeToLMKIndex.put(PINLMKIndex,        0x004);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_CVK, 0x402);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_ZAK, 0x008);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_BDK, 0x009);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_MK_AC, 0x109);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_MK_SMI, 0x209);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_MK_SMC, 0x309);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_MK_DAC, 0x409);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_MK_DN, 0x509);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_MK_CVC3, 0x709);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_ZEK, 0x00A);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_DEK, 0x00B);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_RSA_SK, 0x00C);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_HMAC, 0x10C);
        keyTypeToLMKIndex.put(SMAdapter.TYPE_RSA_PK, 0x00D);
        Provider provider = null;
        LogEvent evt = new LogEvent(this, "jce-provider");
        try {
            if (jceProviderClassName == null || jceProviderClassName.compareTo("") == 0) {
                evt.addMessage("No JCE Provider specified. Attempting to load default provider (SunJCE).");
                jceProviderClassName = "com.sun.crypto.provider.SunJCE";
            }
            provider = (Provider) Class.forName(jceProviderClassName).newInstance();
            Security.addProvider(provider);
            evt.addMessage("name", provider.getName());
        } catch (Exception e) {
            evt.addMessage(e);
            throw new SMException("Unable to load jce provider whose class name is: " + jceProviderClassName);
        } finally {
            Logger.log(evt);
        }
        jceHandler = new JCEHandler(provider);
        if (lmkRebuild) {
            // Creat new LMK file
            evt = new LogEvent(this, "local-master-keys");
            evt.addMessage("Rebuilding new Local Master Keys in file: \"" + lmk.getCanonicalPath() + "\".");
            Logger.log(evt);
            // Generate New random Local Master Keys
            generateLMK();
            // Write the new Local Master Keys to file
            writeLMK(lmk);
            evt = new LogEvent(this, "local-master-keys");
            evt.addMessage("Local Master Keys built successfully in file: \"" + lmk.getCanonicalPath() + "\".");
            Logger.log(evt);
        }
        if (!lmk.exists()) {
            // LMK File does not exist
            throw new SMException("Error loading Local Master Keys, file: \"" + lmk.getCanonicalPath() + "\" does not exist." + " Please specify a valid LMK file, or rebuild a new one.");
        } else {
            // Read LMK from file
            readLMK(lmk);
            evt = new LogEvent(this, "local-master-keys");
            evt.addMessage("Loaded successfully from file: \"" + lmk.getCanonicalPath() + "\"");
            Logger.log(evt);
        }
    } catch (Exception e) {
        if (e instanceof SMException) {
            throw (SMException) e;
        } else {
            throw new SMException(e);
        }
    }
}
Example 13
Project: xwiki-clams-core-master  File: TryAnOpenIDRequestAtGoogle.java View source code
private static SSLContext createEasySSLContext() {
    try {
        SSLContext context = SSLContext.getInstance("SSL", new SunJCE());
        context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);
        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new HttpClientError(e.toString());
    }
}
Example 14
Project: ToxOtis-master  File: PasswordFileManager.java View source code
private void initializeMasterPassword() {
    if (masterPassword == null || (masterPassword != null && masterPassword.length == 0)) {
        // Initialize the master password (if not already initialized)
        if (masterPasswordFile == null) {
            //Use the default password file...
            masterPasswordFile = DEFAULT_MASTER_PASSWORD_FILE;
        }
        FileReader fr = null;
        BufferedReader br = null;
        try {
            File secretFile = new File(masterPasswordFile);
            if (!secretFile.exists()) {
                throw new IllegalArgumentException(String.format("File containing the master password was not found at : '%s'", secretFile.getAbsolutePath()));
            }
            fr = new FileReader(secretFile);
            br = new BufferedReader(fr);
            String line = null;
            StringBuilder buffer = new StringBuilder();
            int count = 0;
            while ((line = br.readLine()) != null && !line.equals(MASTER_START)) {
                count++;
                if (count > MAX_COMMENT_LINES) {
                    throw new IllegalArgumentException("Invalid Master-Key file");
                }
            }
            while ((line = br.readLine()) != null && !line.equals(MASTER_END)) {
                line = line.trim();
                buffer.append(line);
            }
            masterPassword = Base64.decodeString(buffer.toString()).toCharArray();
        } catch (Exception exc) {
            throw new RuntimeException(exc);
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException ex) {
                    String message = "Unexpected error while trying to " + "close a File Reader used to read the master password of JAQPOT.";
                    throw new RuntimeException(message, ex);
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                    String message = "Unexpected error while trying to " + "close a Buffered Reader used to read the master password of JAQPOT.";
                    throw new RuntimeException(message, ex);
                }
            }
        }
        java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE());
        int iterations = cryptoIterations;
        createChipher(masterPassword, SALT, iterations);
    }
}
Example 15
Project: openbd-core-master  File: JavaPlatform.java View source code
@Override
public void init(ServletConfig config) throws ServletException {
    com.nary.Debug.SystemOff();
    javaFileIO = new JavaFileIO(config);
    spoolingMailServer = new OutgoingMailServer(cfEngine.thisInstance.getSystemParameters());
    CollectionFactory.init(cfEngine.getConfig());
    BackgroundUploader.onStart();
    // Install Sun JCE provider
    try {
        Class<?> jceClass = Class.forName("com.sun.crypto.provider.SunJCE");
        Object jceInstance = jceClass.newInstance();
        java.security.Security.addProvider((java.security.Provider) jceInstance);
    } catch (Exception e) {
        cfEngine.log("Failed to add Sun JCE provider");
    }
}
Example 16
Project: ikvm-openjdk-master  File: Security.java View source code
/*
     * Initialize to default values, if <java.home>/lib/java.security
     * is not found.
     */
private static void initializeStatic() {
    props.put("security.provider.1", "sun.security.provider.Sun");
    props.put("security.provider.2", "sun.security.rsa.SunRsaSign");
    props.put("security.provider.3", "com.sun.net.ssl.internal.ssl.Provider");
    props.put("security.provider.4", "com.sun.crypto.provider.SunJCE");
    props.put("security.provider.5", "sun.security.jgss.SunProvider");
    props.put("security.provider.6", "com.sun.security.sasl.Provider");
}
Example 17
Project: keywhiz-master  File: ContentCryptographerTest.java View source code
@Before
public void setUp() throws Exception {
    cryptographer = new ContentCryptographer(BASE_KEY, new SunJCE(), BC, FakeRandom.create());
}
Example 18
Project: java-presentation-manager-master  File: StringEncrypter.java View source code
private void setupEncryptor(String defaultEncryptionPassword, byte[] salt) {
    java.security.Security.addProvider(new SunJCE());
    char[] pass = defaultEncryptionPassword.toCharArray();
    int iterations = 3;
    init(pass, salt, iterations);
}
Example 19
Project: PayMap-master  File: AesUtils.java View source code
@SuppressWarnings("restriction")
public static Key getKey(String strKey) throws Exception {
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    while (strKey.length() < 16) {
        strKey = strKey + "0";
    }
    return getKey(strKey.getBytes());
}