Example usage for javax.crypto SecretKeyFactory getInstance

List of usage examples for javax.crypto SecretKeyFactory getInstance

Introduction

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

Prototype

public static final SecretKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SecretKeyFactory object that converts secret keys of the specified algorithm.

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("DES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    Class spec = Class.forName("javax.crypto.spec.DESKeySpec");
    DESKeySpec ks = (DESKeySpec) skf.getKeySpec(key, spec);
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("keyfile"));
    oos.writeObject(ks.getKey());//from  w  ww.jav  a 2 s  . c om

    Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, key);
    CipherOutputStream cos = new CipherOutputStream(new FileOutputStream("ciphertext"), c);
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(cos));
    pw.println("Stand and unfold yourself");
    pw.close();
    oos.writeObject(c.getIV());
    oos.close();
}

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:MainClass.java

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

    KeyGenerator keyGen = KeyGenerator.getInstance("DES");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    random.setSeed(101L);//  ww  w  .j ava2 s  .c om
    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: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);//from  www. j a  va 2s .c o m
    }
    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:DataStudioCrak.java

public static void main(String[] args) {
    String company = "labthink";
    byte[] companyByteArray = company.getBytes();
    byte[] companyByteIntArray = intToByteArray(compute(companyByteArray, companyByteArray.length));
    // byte[] ff = "zhulixia".getBytes();
    byte[] snByte = new byte[32];
    byte[] byte1 = new byte[] { 7, 1 };
    byte[] byte2 = "zhaodapengpojiehahahahahaha".getBytes();
    byte[] byte3 = new byte[] { 127 };
    byte[] snMain = new byte[24];
    System.arraycopy(byte1, 0, snMain, 0, 2);
    System.arraycopy(byte2, 0, snMain, 2, 17);
    System.arraycopy(companyByteIntArray, 0, snMain, 19, 4);
    System.arraycopy(byte3, 0, snMain, 23, 1);
    //  1 - single license,2 - site license ,3 educational license
    snMain[2] = (byte) 1;
    int intSn = compute(snMain, snMain.length);
    System.out.println("intSn=" + intSn);
    byte[] key1 = "dddd".getBytes();
    byte[] key2 = intToByteArray(intSn);
    byte[] key = new byte[8];
    System.arraycopy(key1, 0, key, 0, 4);
    System.arraycopy(key2, 0, key, 4, 4);

    byte encodedSnMain[] = new byte[snMain.length];
    try {//  w  ww  .  j ava 2  s . c om
        DESKeySpec deskeyspec = new DESKeySpec(key);
        javax.crypto.SecretKey secretkey = SecretKeyFactory.getInstance("DES").generateSecret(deskeyspec);
        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, secretkey);
        cipher.update(snMain, 0, snMain.length, encodedSnMain);
        cipher.doFinal();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    System.arraycopy(key1, 0, snByte, 0, 4);
    System.arraycopy(key2, 0, snByte, 28, 4);
    System.arraycopy(encodedSnMain, 0, snByte, 4, 24);
    char[] snCharArray = Hex.encodeHex(snByte);
    String sn = new String(snCharArray);
    System.out.println("sn=" + sn);
}

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:net.labthink.run.DataStudioCrak.java

public static void main(String[] args) {
    String company = "Labthink";
    byte[] companyByteArray = company.getBytes();
    byte[] companyByteIntArray = intToByteArray(compute(companyByteArray, companyByteArray.length));
    // byte[] ff = "zhulixia".getBytes();
    byte[] snByte = new byte[32];
    byte[] byte1 = new byte[] { 7, 1 };
    byte[] byte2 = "zhaodapengpojiehahahahahaha".getBytes();
    byte[] byte3 = new byte[] { 127 };
    byte[] snMain = new byte[24];
    System.arraycopy(byte1, 0, snMain, 0, 2);
    System.arraycopy(byte2, 0, snMain, 2, 17);
    System.arraycopy(companyByteIntArray, 0, snMain, 19, 4);
    System.arraycopy(byte3, 0, snMain, 23, 1);
    //  1 - single license,2 - site license ,3 educational license
    snMain[2] = (byte) 1;
    int intSn = compute(snMain, snMain.length);
    System.out.println("intSn=" + intSn);
    byte[] key1 = "dddd".getBytes();
    byte[] key2 = intToByteArray(intSn);
    byte[] key = new byte[8];
    System.arraycopy(key1, 0, key, 0, 4);
    System.arraycopy(key2, 0, key, 4, 4);

    byte encodedSnMain[] = new byte[snMain.length];
    try {//from w  w w.j a  va2 s  .  c o  m
        DESKeySpec deskeyspec = new DESKeySpec(key);
        javax.crypto.SecretKey secretkey = SecretKeyFactory.getInstance("DES").generateSecret(deskeyspec);
        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, secretkey);
        cipher.update(snMain, 0, snMain.length, encodedSnMain);
        cipher.doFinal();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    System.arraycopy(key1, 0, snByte, 0, 4);
    System.arraycopy(key2, 0, snByte, 28, 4);
    System.arraycopy(encodedSnMain, 0, snByte, 4, 24);
    char[] snCharArray = Hex.encodeHex(snByte);
    String sn = new String(snCharArray);
    System.out.println("sn=" + sn);
}

From source file:org.apache.juddi.samples.DES.java

public static void main(String[] args) throws Exception {
    DES des = new DES();
    KeyGenerator kgen;/*  w  w  w . j  a  v  a 2s . c o  m*/
    try {
        kgen = KeyGenerator.getInstance(DESEDE_ENCRYPTION_SCHEME);
        kgen.init(168);
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        myEncryptionKey = new String(Base64.encodeBase64(raw));
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        ks = new DESedeKeySpec(arrayBytes);
        skf = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = skf.generateSecret(ks);

        System.out.println(new String(Base64.encodeBase64(raw)));
        System.out.println(des.encrypt("password"));
        System.out.println(des.decrypt(des.encrypt("password")));
    } catch (Exception ex) {
        ex.printStackTrace();
        ;
    }

}

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  w  ww  . j a  va  2s  .  com
    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.");
}