os/security/crypto/weakcryptospi/test/tcryptospi/testdata/symmetricdatacheck0001/gendat.java
First public contribution.
2 * Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
4 * This component and the accompanying materials are made available
5 * under the terms of the License "Eclipse Public License v1.0"
6 * which accompanies this distribution, and is available
7 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
9 * Initial Contributors:
10 * Nokia Corporation - initial contribution.
19 import java.security.*;
20 import javax.crypto.*;
21 import javax.crypto.spec.*;
24 import java.security.spec.*;
25 import javax.net.ssl.SSLServerSocket;
26 import javax.net.ssl.SSLServerSocketFactory;
27 import javax.net.ssl.SSLSocket;
30 * This program generates a AES key, retrieves its raw bytes, and
31 * then reinstantiates a AES key from the key bytes.
32 * The reinstantiated key is used to initialize a AES cipher for
33 * encryption and decryption.
39 * Turns array of bytes into string
41 * @param buf Array of bytes to convert to hex string
42 * @return Generated hex string
44 public static String asHex (byte buf[]) {
45 StringBuffer strbuf = new StringBuffer(buf.length * 2);
48 for (i = 0; i < buf.length; i++) {
49 if (((int) buf[i] & 0xff) < 0x10)
52 strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
55 return strbuf.toString();
58 public static void main(String[] args) throws Exception {
65 String outContents="";
66 String keyContents="";
69 String inPath = args[0];
70 String outPath = args[1];
71 String keyPath = args[2];
81 BufferedReader ivFile = new BufferedReader(new FileReader(ivPath));
82 ivContents = ivFile.readLine();
87 // read in the file contents
88 BufferedReader inFile = new BufferedReader(new FileReader(inPath));
89 inContents = inFile.readLine();
92 BufferedReader keyFile = new BufferedReader(new FileReader(keyPath));
93 keyContents = keyFile.readLine();
99 // Get the KeyGenerator
100 // KeyGenerator kgen = KeyGenerator.getInstance(algo);
101 // kgen.init(56); // 192 and 256 bits may not be available
104 // Generate the secret key specs.
105 // SecretKey skey = kgen.generateKey();
106 // byte[] raw = skey.getEncoded();
108 byte[] raw = keyContents.getBytes();
110 SecretKeySpec skeySpec = new SecretKeySpec(raw, algo);
112 Cipher cipher = Cipher.getInstance(composite);
114 byte[] ivBytes = ivContents.getBytes();
116 if(ivBytes.length > 0)
118 if(algo.equals("RC2"))
120 RC2ParameterSpec rc2Spec = new RC2ParameterSpec(64, ivBytes);
121 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, rc2Spec );
125 AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivBytes);
126 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, paramSpec );
131 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
133 FileOutputStream outFile = new FileOutputStream(outPath);
134 PrintStream p = new PrintStream( outFile );
137 cipher.doFinal(inContents.getBytes());
138 System.out.print("encrypted string: " + asHex(encrypted));
139 p.print(asHex(encrypted));