Example usage for javax.crypto SecretKeyFactory generateSecret

List of usage examples for javax.crypto SecretKeyFactory generateSecret

Introduction

In this page you can find the example usage for javax.crypto SecretKeyFactory generateSecret.

Prototype

public final SecretKey generateSecret(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a SecretKey object from the provided key specification (key material).

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("keyfile"));
    DESKeySpec ks = new DESKeySpec((byte[]) ois.readObject());
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    SecretKey key = skf.generateSecret(ks);

    Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
    c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec((byte[]) ois.readObject()));
    CipherInputStream cis = new CipherInputStream(new FileInputStream("ciphertext"), c);
    BufferedReader br = new BufferedReader(new InputStreamReader(cis));
    System.out.println(br.readLine());
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DESede");
    Key sharedKey = kg.generateKey();

    String password = "password";
    byte[] salt = "salt1234".getBytes();
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20);
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
    SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey passwordKey = kf.generateSecret(keySpec);
    Cipher c = Cipher.getInstance("PBEWithMD5AndDES");
    c.init(Cipher.WRAP_MODE, passwordKey, paramSpec);
    byte[] wrappedKey = c.wrap(sharedKey);

    c = Cipher.getInstance("DESede");
    c.init(Cipher.ENCRYPT_MODE, sharedKey);
    byte[] input = "input".getBytes();
    byte[] encrypted = c.doFinal(input);

    c = Cipher.getInstance("PBEWithMD5AndDES");

    c.init(Cipher.UNWRAP_MODE, passwordKey, paramSpec);
    Key unwrappedKey = c.unwrap(wrappedKey, "DESede", Cipher.SECRET_KEY);

    c = Cipher.getInstance("DESede");
    c.init(Cipher.DECRYPT_MODE, unwrappedKey);
    System.out.println(new String(c.doFinal(encrypted)));
}

From source file:TestCipher.java

public static void main(String args[]) throws Exception {
    Set set = new HashSet();
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        Point point = new Point(random.nextInt(1000), random.nextInt(2000));
        set.add(point);/*  ww  w .  java  2 s.  c  om*/
    }
    int last = random.nextInt(5000);

    // Create Key
    byte key[] = password.getBytes();
    DESKeySpec desKeySpec = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    // Create Cipher
    Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    desCipher.init(Cipher.ENCRYPT_MODE, secretKey);

    // Create stream
    FileOutputStream fos = new FileOutputStream("out.des");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    CipherOutputStream cos = new CipherOutputStream(bos, desCipher);
    ObjectOutputStream oos = new ObjectOutputStream(cos);

    // Write objects
    oos.writeObject(set);
    oos.writeInt(last);
    oos.flush();
    oos.close();

    // Change cipher mode
    desCipher.init(Cipher.DECRYPT_MODE, secretKey);

    // Create stream
    FileInputStream fis = new FileInputStream("out.des");
    BufferedInputStream bis = new BufferedInputStream(fis);
    CipherInputStream cis = new CipherInputStream(bis, desCipher);
    ObjectInputStream ois = new ObjectInputStream(cis);

    // Read objects
    Set set2 = (Set) ois.readObject();
    int last2 = ois.readInt();
    ois.close();

    // Compare original with what was read back
    int count = 0;
    if (set.equals(set2)) {
        System.out.println("Set1: " + set);
        System.out.println("Set2: " + set2);
        System.out.println("Sets are okay.");
        count++;
    }
    if (last == last2) {
        System.out.println("int1: " + last);
        System.out.println("int2: " + last2);
        System.out.println("ints are okay.");
        count++;
    }
    if (count != 2) {
        System.out.println("Problem during encryption/decryption");
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] input = "www.java2s.com".getBytes();
    byte[] keyBytes = new byte[] { 0x73, 0x2f, 0x2d, 0x33, (byte) 0xc8, 0x01, 0x73, 0x2b, 0x72, 0x06, 0x75,
            0x6c, (byte) 0xbd, 0x44, (byte) 0xf9, (byte) 0xc1, (byte) 0xc1, 0x03, (byte) 0xdd, (byte) 0xd9,
            0x7c, 0x7c, (byte) 0xbe, (byte) 0x8e };
    byte[] ivBytes = new byte[] { (byte) 0xb0, 0x7b, (byte) 0xf5, 0x22, (byte) 0xc8, (byte) 0xd6, 0x08,
            (byte) 0xb8 };

    // encrypt the data using precalculated keys

    Cipher cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");
    cEnc.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "DESede"), new IvParameterSpec(ivBytes));

    byte[] out = cEnc.doFinal(input);
    // decrypt the data using PBE

    char[] password = "password".toCharArray();
    byte[] salt = new byte[] { 0x7d, 0x60, 0x43, 0x5f, 0x02, (byte) 0xe9, (byte) 0xe0, (byte) 0xae };
    int iterationCount = 2048;
    PBEKeySpec pbeSpec = new PBEKeySpec(password, salt, iterationCount);
    SecretKeyFactory keyFact = SecretKeyFactory.getInstance("PBEWithSHAAnd3KeyTripleDES");

    Cipher cDec = Cipher.getInstance("PBEWithSHAAnd3KeyTripleDES");
    Key sKey = keyFact.generateSecret(pbeSpec);

    cDec.init(Cipher.DECRYPT_MODE, sKey);

    System.out.println("cipher : " + new String(out));
    System.out.println("gen key: " + new String(sKey.getEncoded()));
    System.out.println("gen iv : " + new String(cDec.getIV()));
    System.out.println("plain  : " + new String(cDec.doFinal(out)));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] input = "www.java2s.com".getBytes();
    byte[] keyBytes = new byte[] { 0x73, 0x2f, 0x2d, 0x33, (byte) 0xc8, 0x01, 0x73, 0x2b, 0x72, 0x06, 0x75,
            0x6c, (byte) 0xbd, 0x44, (byte) 0xf9, (byte) 0xc1, (byte) 0xc1, 0x03, (byte) 0xdd, (byte) 0xd9,
            0x7c, 0x7c, (byte) 0xbe, (byte) 0x8e };
    byte[] ivBytes = new byte[] { (byte) 0xb0, 0x7b, (byte) 0xf5, 0x22, (byte) 0xc8, (byte) 0xd6, 0x08,
            (byte) 0xb8 };

    // encrypt the data using precalculated keys

    Cipher cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");

    cEnc.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "DESede"), new IvParameterSpec(ivBytes));

    byte[] out = cEnc.doFinal(input);

    // decrypt the data using PBE

    char[] password = "password".toCharArray();
    byte[] salt = new byte[] { 0x7d, 0x60, 0x43, 0x5f, 0x02, (byte) 0xe9, (byte) 0xe0, (byte) 0xae };
    int iterationCount = 2048;
    PBEKeySpec pbeSpec = new PBEKeySpec(password);
    SecretKeyFactory keyFact = SecretKeyFactory.getInstance("PBEWithSHAAnd3KeyTripleDES", "BC");

    Cipher cDec = Cipher.getInstance("PBEWithSHAAnd3KeyTripleDES", "BC");
    Key sKey = keyFact.generateSecret(pbeSpec);

    cDec.init(Cipher.DECRYPT_MODE, sKey, new PBEParameterSpec(salt, iterationCount));

    System.out.println("cipher : " + new String(out));
    System.out.println("gen key: " + new String(sKey.getEncoded()));
    System.out.println("gen iv : " + new String(cDec.getIV()));
    System.out.println("plain  : " + new String(cDec.doFinal(out)));
}

From source file:uk.ac.ox.webauth.crypto.DesCbcCrc.java

public static void main(String[] args) throws Exception {
    /* mod-crc-32 tests from RFC 3961 section A.5:
       mod-crc-32("foo") =                                     33 bc 32 73
       mod-crc-32("test0123456789") =                          d6 88 3e b8
       mod-crc-32("MASSACHVSETTS INSTITVTE OF TECHNOLOGY") =   f7 80 41 e3
       mod-crc-32(8000) =                                      4b 98 83 3b
       mod-crc-32(0008) =                                      32 88 db 0e
       mod-crc-32(0080) =                                      20 83 b8 ed
       mod-crc-32(80) =                                        20 83 b8 ed
       mod-crc-32(80000000) =                                  3b b6 59 ed
       mod-crc-32(00000001) =                                  96 30 07 77
    *///from   ww  w.j a  va 2s. c  om
    test_modifiedCRC32(new String(Hex.encodeHex("foo".getBytes())), "33bc3273");
    test_modifiedCRC32(new String(Hex.encodeHex("test0123456789".getBytes())), "d6883eb8");
    test_modifiedCRC32(new String(Hex.encodeHex("MASSACHVSETTS INSTITVTE OF TECHNOLOGY".getBytes())),
            "f78041e3");
    test_modifiedCRC32("8000", "4b98833b");
    test_modifiedCRC32("0008", "3288db0e");
    test_modifiedCRC32("0080", "2083b8ed");
    test_modifiedCRC32("80", "2083b8ed");
    test_modifiedCRC32("80000000", "3bb659ed");
    test_modifiedCRC32("00000001", "96300777");
    SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
    KeySpec spec = new DESKeySpec(new byte[8]);
    SecretKey secretKey = factory.generateSecret(spec);
    ASN1Encodable apo = new APOptions();
    DesCbcCrc dcc = new DesCbcCrc(secretKey);
    byte[] encrypted = dcc.encrypt(apo);
    apo = dcc.decrypt(encrypted);
    System.out.println("Encrypt-decrypt test successful.");
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {

    KeyGenerator keyGen = KeyGenerator.getInstance("DES");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    random.setSeed(101L);//w  w w .  ja  va2  s.  co  m
    keyGen.init(56, random);
    SecretKey sKey = keyGen.generateKey();
    SecretKeyFactory kfactory = SecretKeyFactory.getInstance("DES");

    DESKeySpec kspec = (DESKeySpec) kfactory.getKeySpec(sKey, DESKeySpec.class);

    System.out.println(sKey);
    FileOutputStream fos = new FileOutputStream("secretKeys");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject(kspec.getKey());

    FileInputStream fin = new FileInputStream("secretKeys");
    ObjectInputStream ois = new ObjectInputStream(fin);

    byte[] kMaterial = (byte[]) ois.readObject();

    DESKeySpec keyspec = new DESKeySpec(kMaterial);
    SecretKey newKey = kfactory.generateSecret(keyspec);
    System.out.println(newKey);
    System.out.println("Do the keys equal :" + newKey.equals(sKey));

}

From source file:com.board.games.handler.modx.MODXPokerLoginServiceImpl.java

public static void main(String[] a) {

    Verifier verifier = new Verifier();

    String dbHash = "iDxLTbkejeeaQqpPoZTqUCJfWo1ALcBf7gMlYwwMa+Y="; //"dlgQ65ruCfeVVxqHJ3Bf02j50P0Wvis7WOoTfHYV3Nk=";
    String password = "rememberme";
    String dbSalt = "008747a35b77a4c7e55ab7ea8aec3ee0";
    PasswordResponse response = new PasswordResponse();
    String salt = "008747a35b77a4c7e55ab7ea8aec3ee0";
    response.setAlgorithm(Algorithm.PBKDF2);
    response.setSalt(salt);/*from www  .j  ava 2 s  .c om*/
    response.setAlgorithmDetails(new AlgorithmDetails());
    response.getAlgorithmDetails().setIterations(1000);
    response.getAlgorithmDetails().setHashFunction("SHA256");
    response.getAlgorithmDetails().setKeySize(263);
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 1000,
            response.getAlgorithmDetails().getKeySize());
    try {
        SecretKeyFactory skf = PBKDF2Algorithms.getSecretKeyFactory(
                "PBKDF2WithHmac" + response.getAlgorithmDetails().getHashFunction().replace("-", ""));
        byte[] hash = skf.generateSecret(spec).getEncoded();

        String encodedHash = Base64.encodeBase64String(hash);
        response.setHash(encodedHash);

        System.out.println("hash " + response.getHash());
        if (verifier.verify(password, response)) {
            // Check it against database stored hash
            if (encodedHash.equals(dbHash)) {
                System.out.println("Authentication Successful");
            } else {
                System.out.println("Authentication failed");
            }

        } else {
            System.out.println("failed verification of hashing");
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:uk.ac.ox.webauth.crypto.Des3CbcSha1Kd.java

public static void main(String[] args) throws Exception {
    // test the nFold with test vectors given in RFC 3961

    /*//from   w  w  w. j av a2s.  c  om
    64-fold("012345") =
    64-fold(303132333435) = be072631276b1955
    */
    test_nFold("012345", "303132333435", "be072631276b1955", 64);

    /*
    56-fold("password") =
    56-fold(70617373776f7264) = 78a07b6caf85fa
    */
    test_nFold("password", "70617373776f7264", "78a07b6caf85fa", 56);

    /*
    64-fold("Rough Consensus, and Running Code") =
    64-fold(526f75676820436f6e73656e7375732c20616e642052756e6e696e6720436f6465) = bb6ed30870b7f0e0
    */
    test_nFold("Rough Consensus, and Running Code",
            "526f75676820436f6e73656e7375732c20616e642052756e6e696e6720436f6465", "bb6ed30870b7f0e0", 64);

    /*
    168-fold("password") =
    168-fold(70617373776f7264) = 59e4a8ca7c0385c3c37b3f6d2000247cb6e6bd5b3e
    */
    test_nFold("password", "70617373776f7264", "59e4a8ca7c0385c3c37b3f6d2000247cb6e6bd5b3e", 168);

    /*
    192-fold("MASSACHVSETTS INSTITVTE OF TECHNOLOGY")
    192-fold(4d41535341434856534554545320494e53544954565445204f4620544543484e4f4c4f4759) =
       db3b0d8f0b061e603282b308a50841229ad798fab9540c1b
    */
    test_nFold("MASSACHVSETTS INSTITVTE OF TECHNOLOGY",
            "4d41535341434856534554545320494e53544954565445204f4620544543484e4f4c4f4759",
            "db3b0d8f0b061e603282b308a50841229ad798fab9540c1b", 192);

    /*
    168-fold("Q") =
    168-fold(51) = 518a54a2 15a8452a 518a54a2 15a8452a 518a54a2 15
    */
    test_nFold("Q", "51", "518a54a215a8452a518a54a215a8452a518a54a215", 168);

    /*
    168-fold("ba") =
    168-fold(6261) = fb25d531 ae897449 9f52fd92 ea9857c4 ba24cf29 7e
    */
    test_nFold("ba", "6261", "fb25d531ae8974499f52fd92ea9857c4ba24cf297e", 168);

    /*
    key:                 dce06b1f64c857a11c3db57c51899b2cc1791008ce973b92
    usage:               0000000155
    DR:                  935079d14490a75c3093c4a6e8c3b049c71e6ee705
    DK:                  925179d04591a79b5d3192c4a7e9c289b049c71f6ee604cd
    */
    test_DR_DK("dce06b1f64c857a11c3db57c51899b2cc1791008ce973b92", "0000000155",
            "935079d14490a75c3093c4a6e8c3b049c71e6ee705", "925179d04591a79b5d3192c4a7e9c289b049c71f6ee604cd");

    /*
    key:                 5e13d31c70ef765746578531cb51c15bf11ca82c97cee9f2
    usage:               00000001aa
    DR:                  9f58e5a047d894101c469845d67ae3c5249ed812f2
    DK:                  9e58e5a146d9942a101c469845d67a20e3c4259ed913f207
    */
    test_DR_DK("5e13d31c70ef765746578531cb51c15bf11ca82c97cee9f2", "00000001aa",
            "9f58e5a047d894101c469845d67ae3c5249ed812f2", "9e58e5a146d9942a101c469845d67a20e3c4259ed913f207");

    /*
    key:                 98e6fd8a04a4b6859b75a176540b9752bad3ecd610a252bc
    usage:               0000000155
    DR:                  12fff90c773f956d13fc2ca0d0840349dbd39908eb
    DK:                  13fef80d763e94ec6d13fd2ca1d085070249dad39808eabf
    */
    test_DR_DK("98e6fd8a04a4b6859b75a176540b9752bad3ecd610a252bc", "0000000155",
            "12fff90c773f956d13fc2ca0d0840349dbd39908eb", "13fef80d763e94ec6d13fd2ca1d085070249dad39808eabf");

    /*
    key:                 622aec25a2fe2cad7094680b7c64940280084c1a7cec92b5
    usage:               00000001aa
    DR:                  f8debf05b097e7dc0603686aca35d91fd9a5516a70
    DK:                  f8dfbf04b097e6d9dc0702686bcb3489d91fd9a4516b703e
    */
    test_DR_DK("622aec25a2fe2cad7094680b7c64940280084c1a7cec92b5", "00000001aa",
            "f8debf05b097e7dc0603686aca35d91fd9a5516a70", "f8dfbf04b097e6d9dc0702686bcb3489d91fd9a4516b703e");

    /*
    key:                 d3f8298ccb166438dcb9b93ee5a7629286a491f838f802fb
    usage:               6b65726265726f73 ("kerberos")
    DR:                  2270db565d2a3d64cfbfdc5305d4f778a6de42d9da
    DK:                  2370da575d2a3da864cebfdc5204d56df779a7df43d9da43
    */
    test_DR_DK("d3f8298ccb166438dcb9b93ee5a7629286a491f838f802fb", "6b65726265726f73",
            "2270db565d2a3d64cfbfdc5305d4f778a6de42d9da", "2370da575d2a3da864cebfdc5204d56df779a7df43d9da43");

    /*
    key:                 c1081649ada74362e6a1459d01dfd30d67c2234c940704da
    usage:               0000000155
    DR:                  348056ec98fcc517171d2b4d7a9493af482d999175
    DK:                  348057ec98fdc48016161c2a4c7a943e92ae492c989175f7
    */
    test_DR_DK("c1081649ada74362e6a1459d01dfd30d67c2234c940704da", "0000000155",
            "348056ec98fcc517171d2b4d7a9493af482d999175", "348057ec98fdc48016161c2a4c7a943e92ae492c989175f7");

    /*
    key:                 5d154af238f46713155719d55e2f1f790dd661f279a7917c
    usage:               00000001aa
    DR:                  a8818bc367dadacbe9a6c84627fb60c294b01215e5
    DK:                  a8808ac267dada3dcbe9a7c84626fbc761c294b01315e5c1
    */
    test_DR_DK("5d154af238f46713155719d55e2f1f790dd661f279a7917c", "00000001aa",
            "a8818bc367dadacbe9a6c84627fb60c294b01215e5", "a8808ac267dada3dcbe9a7c84626fbc761c294b01315e5c1");

    /*
    key:                 798562e049852f57dc8c343ba17f2ca1d97394efc8adc443
    usage:               0000000155
    DR:                  c813f88b3be2b2f75424ce9175fbc8483b88c8713a
    DK:                  c813f88a3be3b334f75425ce9175fbe3c8493b89c8703b49
    */
    test_DR_DK("798562e049852f57dc8c343ba17f2ca1d97394efc8adc443", "0000000155",
            "c813f88b3be2b2f75424ce9175fbc8483b88c8713a", "c813f88a3be3b334f75425ce9175fbe3c8493b89c8703b49");

    /*
    key:                 26dce334b545292f2feab9a8701a89a4b99eb9942cecd016
    usage:               00000001aa
    DR:                  f58efc6f83f93e55e695fd252cf8fe59f7d5ba37ec
    DK:                  f48ffd6e83f83e7354e694fd252cf83bfe58f7d5ba37ec5d
    */
    test_DR_DK("26dce334b545292f2feab9a8701a89a4b99eb9942cecd016", "00000001aa",
            "f58efc6f83f93e55e695fd252cf8fe59f7d5ba37ec", "f48ffd6e83f83e7354e694fd252cf83bfe58f7d5ba37ec5d");

    SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
    KeySpec spec = new DESedeKeySpec(new byte[24]);
    SecretKey secretKey = factory.generateSecret(spec);
    ASN1Encodable apo = new APOptions();
    Des3CbcSha1Kd dcc = new Des3CbcSha1Kd(secretKey, 11);
    byte[] encrypted = dcc.encrypt(apo);
    apo = dcc.decrypt(encrypted);
    System.out.println("Encrypt-decrypt test successful.");
}

From source file:Main.java

public static Key getDESKey(byte[] key) throws Exception {
    DESKeySpec des = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    return keyFactory.generateSecret(des);
}