Source Code Cross Referenced for cryptbig.java in  » Search-Engine » yacy » de » anomic » tools » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Search Engine » yacy » de.anomic.tools 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        // crypt.java 
002:        // -------------------------------------
003:        // (C) by Michael Peter Christen; mc@anomic.de
004:        // first published on http://www.anomic.de
005:        // Frankfurt, Germany, 2004
006:        // last major change: 13.05.2004
007:        //
008:        // This program is free software; you can redistribute it and/or modify
009:        // it under the terms of the GNU General Public License as published by
010:        // the Free Software Foundation; either version 2 of the License, or
011:        // (at your option) any later version.
012:        //
013:        // This program is distributed in the hope that it will be useful,
014:        // but WITHOUT ANY WARRANTY; without even the implied warranty of
015:        // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016:        // GNU General Public License for more details.
017:        //
018:        // You should have received a copy of the GNU General Public License
019:        // along with this program; if not, write to the Free Software
020:        // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
021:        //
022:        // Using this software in any meaning (reading, learning, copying, compiling,
023:        // running) means that you agree that the Author(s) is (are) not responsible
024:        // for cost, loss of data or any harm that may be caused directly or indirectly
025:        // by usage of this softare or this documentation. The usage of this software
026:        // is on your own risk. The installation and usage (starting/running) of this
027:        // software may allow other people or application to access your computer and
028:        // any attached devices and is highly dependent on the configuration of the
029:        // software which must be done by the user of the software; the author(s) is
030:        // (are) also not responsible for proper configuration and usage of the
031:        // software, even if provoked by documentation provided together with
032:        // the software.
033:        //
034:        // Any changes to this file according to the GPL as documented in the file
035:        // gpl.txt aside this file in the shipment you received can be done to the
036:        // lines that follows this copyright notice here, but changes must not be
037:        // done inside the copyright notive above. A re-distribution must contain
038:        // the intact and unchanged copyright notice.
039:        // Contributions and changes to the program code must be marked as such.
040:
041:        package de.anomic.tools;
042:
043:        import java.io.BufferedInputStream;
044:        import java.io.BufferedOutputStream;
045:        import java.io.File;
046:        import java.io.FileInputStream;
047:        import java.io.FileNotFoundException;
048:        import java.io.FileOutputStream;
049:        import java.io.IOException;
050:        import java.io.InputStream;
051:        import java.io.OutputStream;
052:        import java.io.UnsupportedEncodingException;
053:        import java.security.Provider;
054:        import java.security.Security;
055:        import java.text.ParsePosition;
056:        import java.text.SimpleDateFormat;
057:        import java.util.Date;
058:        import java.util.HashSet;
059:        import java.util.Iterator;
060:        import java.util.Locale;
061:        import java.util.Random;
062:        import java.util.Set;
063:
064:        import javax.crypto.BadPaddingException;
065:        import javax.crypto.Cipher;
066:        import javax.crypto.CipherInputStream;
067:        import javax.crypto.CipherOutputStream;
068:        import javax.crypto.IllegalBlockSizeException;
069:        import javax.crypto.SecretKey;
070:        import javax.crypto.SecretKeyFactory;
071:        import javax.crypto.spec.PBEKeySpec;
072:        import javax.crypto.spec.PBEParameterSpec;
073:
074:        import de.anomic.kelondro.kelondroBase64Order;
075:        import de.anomic.server.serverCodings;
076:
077:        public class cryptbig {
078:
079:            // --------------------------------------------------------
080:            // Section: random salt generation
081:            // --------------------------------------------------------
082:
083:            private static long saltcounter = 0;
084:            private static Random saltrandom = new Random(System
085:                    .currentTimeMillis());
086:
087:            public static String randomSalt() {
088:                // generate robust 48-bit random number
089:                long salt = (saltrandom.nextLong() & 0XffffffffffffL)
090:                        + (System.currentTimeMillis() & 0XffffffffffffL)
091:                        + ((1001 * saltcounter) & 0XffffffffffffL);
092:                saltcounter++;
093:                // we generate 48-bit salt values, that are represented as 8-character
094:                // b64-encoded strings
095:                return kelondroBase64Order.standardCoder.encodeLong(
096:                        salt & 0XffffffffffffL, 8);
097:            }
098:
099:            // --------------------------------------------------------
100:            // Section: PBE + PublicKey based on passwords encryption
101:            // --------------------------------------------------------
102:
103:            public static final String vDATE = "20030925";
104:            public static final String copyright = "[ 'crypt' v" + vDATE
105:                    + " by Michael Christen / www.anomic.de ]";
106:            public static final String magicString = "crypt|anomic.de|0"; // magic identifier inside every '.crypt' - file
107:            public static final SimpleDateFormat dateFormatter = new SimpleDateFormat(
108:                    "yyyyMMddHHmmssSSS", Locale.ENGLISH);
109:
110:            String cryptMethod; // one of ["TripleDES", "Blowfish", "DESede", "DES"]
111:            private static final String defaultMethod = "PBEWithMD5AndDES"; //"DES";
112:
113:            Cipher ecipher;
114:            Cipher dcipher;
115:
116:            public cryptbig(String pbe) {
117:                // this is possible, but not recommended
118:                this (pbe, (pbe + "XXXXXXXX").substring(0, 8));
119:            }
120:
121:            public cryptbig(String pbe, String salt) {
122:                this (pbe, salt, defaultMethod);
123:            }
124:
125:            private cryptbig(String pbe, String salt, String method) {
126:                // a Password-Based Encryption. The SecretKey is created on the fly
127:                PBEKeySpec keySpec = new PBEKeySpec(pbe.toCharArray());
128:                try {
129:                    if (salt.length() > 8)
130:                        salt = salt.substring(0, 8);
131:                    if (salt.length() < 8)
132:                        salt = (salt + "XXXXXXXX").substring(0, 8);
133:
134:                    // create the PBE key
135:                    SecretKeyFactory keyFactory = SecretKeyFactory
136:                            .getInstance(method);
137:                    SecretKey key = keyFactory.generateSecret(keySpec);
138:
139:                    // create parameter spec for PBE
140:                    PBEParameterSpec paramSpec = new PBEParameterSpec(salt
141:                            .getBytes(), 1000 /*ITERATIONS*/);
142:
143:                    // Create a cipher and initialize it for encrypting end decrypting
144:                    cryptMethod = method;
145:                    ecipher = Cipher.getInstance(cryptMethod);
146:                    dcipher = Cipher.getInstance(cryptMethod);
147:                    ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); // paramSpec only for PBE!
148:                    dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
149:                } catch (javax.crypto.NoSuchPaddingException e) {
150:                } catch (java.security.InvalidKeyException e) {
151:                } catch (java.security.NoSuchAlgorithmException e) {
152:                } catch (java.security.spec.InvalidKeySpecException e) {
153:                } catch (java.security.InvalidAlgorithmParameterException e) {
154:                }
155:            }
156:
157:            // Encode a string into a new string using utf-8, crypt and b64
158:            public String encryptString(String str) {
159:                try {
160:                    byte[] utf = str.getBytes("UTF8");
161:                    byte[] enc = encryptArray(utf);
162:                    if (enc == null)
163:                        return null;
164:                    return kelondroBase64Order.standardCoder.encode(enc);
165:                } catch (UnsupportedEncodingException e) {
166:                }
167:                return null;
168:            }
169:
170:            // Decode a string into a new string using b64, crypt and utf-8
171:            public String decryptString(String str) {
172:                try {
173:                    byte[] b64dec = kelondroBase64Order.standardCoder.decode(
174:                            str, "de.anomic.tools.cryptbig.decryptString()");
175:                    if (b64dec == null)
176:                        return null; // error in input string (inconsistency)
177:                    byte[] dec = decryptArray(b64dec);
178:                    if (dec == null)
179:                        return null;
180:                    return new String(dec, "UTF-8");
181:                } catch (UnsupportedEncodingException e) {
182:                }
183:                return null;
184:            }
185:
186:            // Encode a byte array into a new byte array
187:            public byte[] encryptArray(byte[] b) {
188:                if (b == null)
189:                    return null;
190:                try {
191:                    return ecipher.doFinal(b);
192:                } catch (javax.crypto.BadPaddingException e) {
193:                } catch (IllegalBlockSizeException e) {
194:                }
195:                return null;
196:            }
197:
198:            // Decode a string into a new string using b64, crypt and utf-8
199:            public byte[] decryptArray(byte[] b) {
200:                if (b == null)
201:                    return null;
202:                try {
203:                    return dcipher.doFinal(b);
204:                } catch (javax.crypto.BadPaddingException e) {
205:                } catch (IllegalBlockSizeException e) {
206:                }
207:                return null;
208:            }
209:
210:            // This method returns the available implementations for a service type
211:            public static Set<String> listCryptoMethods(String serviceType) {
212:                Set<String> result = new HashSet<String>();
213:
214:                // All providers
215:                Provider[] providers = Security.getProviders();
216:                for (int i = 0; i < providers.length; i++) {
217:                    // Get services provided by each provider
218:                    Set<?> keys = providers[i].keySet();
219:                    for (Iterator<?> it = keys.iterator(); it.hasNext();) {
220:                        String key = (String) it.next();
221:                        key = key.split(" ")[0];
222:                        if (key.startsWith(serviceType + ".")) {
223:                            result.add(key.substring(serviceType.length() + 1));
224:                        } else if (key.startsWith("Alg.Alias." + serviceType
225:                                + ".")) {
226:                            // This is an alias
227:                            result
228:                                    .add(key
229:                                            .substring(serviceType.length() + 11));
230:                        }
231:                    }
232:                }
233:                return result;
234:            }
235:
236:            public static void testCryptMethods(Set<String> methods) {
237:                String method;
238:                Iterator<String> i = methods.iterator();
239:                while (i.hasNext()) {
240:                    method = (String) i.next();
241:                    System.out.print(method + " : ");
242:                    try {
243:                        cryptbig crypter = new cryptbig("abrakadabra", method);
244:                        String encrypted = crypter
245:                                .encryptString("nicht verraten abc 1234567890");
246:                        System.out.print(encrypted + "/");
247:                        String decrypted = crypter.decryptString(encrypted);
248:                        System.out.println(decrypted);
249:                    } catch (Exception e) {
250:                        System.out.println("Exception: " + e.getMessage());
251:                        e.printStackTrace();
252:                    }
253:                }
254:            }
255:
256:            public void encryptFile(String inFileName, String outFileName,
257:                    boolean compress) {
258:                /*
259:                  File-Format of encrypted file:
260:                  Filename: b64-of-encryption-of-<encryption-date: YYYYMMddHHmmSSsss> plus extension ".crypt"
261:                  File Content:
262:                  <original file name>
263:                  <original file date>
264:                  <original file size>
265:                  <compressed-before-encryption-flag>
266:                  <compressed-after-encryption-flag>
267:                  <binary>
268:                 */
269:                try {
270:                    File inFile = new File(inFileName);
271:                    String inFileDate = dateFormatter.format(new Date(inFile
272:                            .lastModified())); // 17 byte
273:                    String encryptionDate = dateFormatter.format(new Date()); // 17 byte
274:                    String inFileSize = kelondroBase64Order.standardCoder
275:                            .encodeLong(inFile.length(), 11); // 64 / 6 = 11; 11 byte
276:                    String flag = "1"; // 1 byte
277:                    //int    inFileNameLength = inFileName.length(); // 256
278:                    String X = inFileDate + encryptionDate + inFileSize + flag
279:                            + inFileName;
280:
281:                    System.out.println("TEST: preserving inFileDate    : "
282:                            + dateFormatter.parse(inFileDate,
283:                                    new ParsePosition(0)));
284:                    System.out.println("TEST: preserving encryptionDate: "
285:                            + dateFormatter.parse(encryptionDate,
286:                                    new ParsePosition(0)));
287:                    System.out.println("TEST: preserving inFileLength  : "
288:                            + inFile.length());
289:                    System.out.println("TEST: preserving flag          : "
290:                            + flag);
291:                    System.out.println("TEST: preserving inFileName    : "
292:                            + inFileName);
293:                    System.out.println("TEST: preserving X-String      : " + X);
294:
295:                    // start encryption
296:                    InputStream fin = new CipherInputStream(
297:                            new FileInputStream(inFile), ecipher);
298:                    OutputStream fout = new FileOutputStream(outFileName);
299:
300:                    // write magic and properties of original file
301:                    // - we encrypt the original date, the encryption date, the file size, the flag
302:                    //   and file name together to the string A and calculate the length AL of that string
303:                    // - the length of the file name is therefore equal to AL-(17+17+11+1) = AL-46
304:                    // - AL is then b64-ed and also encrypted which results into string B
305:                    // - the length of B is BL; BL is then b64-ed to a string C of fixed length 1
306:                    // - after the magic String we write C, B and A
307:                    try {
308:                        String A = new String(ecipher.doFinal(X
309:                                .getBytes("UTF8")));
310:                        String B = new String(ecipher
311:                                .doFinal(kelondroBase64Order.standardCoder
312:                                        .encodeLong(A.length(), 2).getBytes(
313:                                                "UTF8"))); // most probable not longer than 4
314:                        String C = kelondroBase64Order.standardCoder
315:                                .encodeLong(B.length(), 1); // fixed length 1 (6 bits, that should be enough)
316:                        fout.write(magicString.getBytes()); // the magic string, used to identify a 'crypt'-file
317:                        fout.write(C.getBytes());
318:                        fout.write(B.getBytes());
319:                        fout.write(A.getBytes());
320:
321:                        // write content of file
322:                        copy(fout, fin, 512);
323:                    } catch (javax.crypto.IllegalBlockSizeException e) {
324:                        System.err.println("ERROR:" + e.getMessage());
325:                    } catch (javax.crypto.BadPaddingException e) {
326:                        System.err.println("ERROR:" + e.getMessage());
327:                    }
328:                    // finished files
329:                    fin.close();
330:                    fout.close();
331:                } catch (FileNotFoundException e) {
332:                    System.err.println("ERROR: file '" + inFileName
333:                            + "' not found");
334:                } catch (IOException e) {
335:                    System.err.println("ERROR: IO trouble");
336:                }
337:            }
338:
339:            public void decryptFile(String inFileName, String outFileName) {
340:                InputStream fin = null;
341:                OutputStream fout = null;
342:                try {
343:                    // Start opening the files
344:                    fin = new BufferedInputStream(new FileInputStream(
345:                            inFileName), 4096);
346:
347:                    // read the file properties
348:                    byte[] this Magic = new byte[magicString.length()];
349:                    fin.read(this Magic);
350:
351:                    if (!((new String(this Magic)).equals(magicString))) {
352:                        // this is not an crypt file, so dont do anything
353:                        fin.close();
354:                        return;
355:                    }
356:                    byte[] C = new byte[1];
357:                    fin.read(C); // the length of the following String, encoded as b64
358:                    byte[] B = new byte[(int) kelondroBase64Order.standardCoder
359:                            .decodeLong(new String(C))];
360:                    fin.read(B); // this is again the length of the following string, as encrypted b64-ed integer
361:                    byte[] A = new byte[(int) kelondroBase64Order.standardCoder
362:                            .decodeLong(new String(dcipher.doFinal(B), "UTF8"))];
363:                    fin.read(A);
364:                    String X = new String(dcipher.doFinal(A), "UTF8");
365:
366:                    System.out.println("TEST: detecting X-String      : " + X);
367:
368:                    // reconstruct the properties
369:                    Date inFileDate = dateFormatter.parse(X.substring(0, 17),
370:                            new ParsePosition(0));
371:                    Date encryptionDate = dateFormatter.parse(X.substring(17,
372:                            34), new ParsePosition(0));
373:                    long inFileSize = kelondroBase64Order.standardCoder
374:                            .decodeLong(X.substring(34, 45));
375:                    String flag = X.substring(45, 46);
376:                    String origFileName = X.substring(46);
377:
378:                    System.out.println("TEST: detecting inFileDate    : "
379:                            + inFileDate);
380:                    System.out.println("TEST: detecting encryptionDate: "
381:                            + encryptionDate);
382:                    System.out.println("TEST: detecting inFileLength  : "
383:                            + inFileSize);
384:                    System.out.println("TEST: detecting flag          : "
385:                            + flag);
386:                    System.out.println("TEST: detecting inFileName    : "
387:                            + origFileName);
388:
389:                    // open the output file
390:                    fout = new BufferedOutputStream(new CipherOutputStream(
391:                            new FileOutputStream(outFileName), dcipher), 4096);
392:
393:                    // read and decrypt the file
394:                    copy(fout, fin, 512);
395:
396:                    // close the files
397:                    fin.close();
398:                    fout.close();
399:
400:                    // do postprocessing
401:                } catch (BadPaddingException e) {
402:                    System.err.println("ERROR: decryption of '" + inFileName
403:                            + "' not possible: " + e.getMessage());
404:                } catch (IllegalBlockSizeException e) {
405:                    System.err.println("ERROR: decryption of '" + inFileName
406:                            + "' not possible: " + e.getMessage());
407:                } catch (FileNotFoundException e) {
408:                    System.err.println("ERROR: file '" + inFileName
409:                            + "' not found");
410:                } catch (IOException e) {
411:                    System.err.println("ERROR: IO trouble");
412:                    try {
413:                        fin.close();
414:                        fout.close();
415:                    } catch (Exception ee) {
416:                    }
417:                }
418:            }
419:
420:            private static void copy(OutputStream out, InputStream in,
421:                    int bufferSize) throws IOException {
422:                InputStream bIn = new BufferedInputStream(in, bufferSize);
423:                OutputStream bOut = new BufferedOutputStream(out, bufferSize);
424:                byte[] buf = new byte[bufferSize];
425:                int n;
426:                while ((n = bIn.read(buf)) > 0)
427:                    bOut.write(buf, 0, n);
428:                bIn.close();
429:                bOut.close();
430:            }
431:
432:            public static String scrambleString(String key, String s) {
433:                // we perform several operations
434:                // - generate salt
435:                // - gzip string
436:                // - crypt string with key and salt
437:                // - base64-encode result
438:                // - attach salt and return
439:                String salt = randomSalt();
440:                //System.out.println("Salt=" + salt);
441:                cryptbig c = new cryptbig(key, salt);
442:                boolean gzFlag = true;
443:                byte[] gz = gzip.gzipString(s);
444:                if (gz.length > s.length()) {
445:                    // revert compression
446:                    try {
447:                        gz = s.getBytes("UTF8");
448:                        gzFlag = false;
449:                    } catch (UnsupportedEncodingException e) {
450:                        return null;
451:                    }
452:                }
453:                //System.out.println("GZIP length=" + gz.length);
454:                if (gz == null)
455:                    return null;
456:                byte[] enc = c.encryptArray(gz);
457:                if (enc == null)
458:                    return null;
459:                return salt + ((gzFlag) ? "1" : "0")
460:                        + kelondroBase64Order.enhancedCoder.encode(enc);
461:            }
462:
463:            public static String descrambleString(String key, String s) {
464:                String salt = s.substring(0, 8);
465:                boolean gzFlag = (s.charAt(8) == '1');
466:                s = s.substring(9);
467:                cryptbig c = new cryptbig(key, salt);
468:                byte[] b64dec = kelondroBase64Order.enhancedCoder.decode(s,
469:                        "de.anomic.tools.cryptbig.descrambleString()");
470:                if (b64dec == null)
471:                    return null; // error in input string (inconsistency)
472:                byte[] dec = c.decryptArray(b64dec);
473:                if (dec == null)
474:                    return null;
475:                if (gzFlag)
476:                    return gzip.gunzipString(dec);
477:                else
478:                    try {
479:                        return new String(dec, "UTF8");
480:                    } catch (UnsupportedEncodingException e) {
481:                        return null;
482:                    }
483:
484:            }
485:
486:            // --------------------------------------------------------
487:            // Section: simple Codings
488:            // --------------------------------------------------------
489:
490:            public static String simpleEncode(String content) {
491:                return simpleEncode(content, null, 'b');
492:            }
493:
494:            public static String simpleEncode(String content, String key) {
495:                return simpleEncode(content, key, 'b');
496:            }
497:
498:            public static String simpleEncode(String content, String key,
499:                    char method) {
500:                if (key == null)
501:                    key = "NULL";
502:                if (method == 'p')
503:                    return "p|" + content;
504:                if (method == 'b')
505:                    return "b|"
506:                            + kelondroBase64Order.enhancedCoder
507:                                    .encodeString(content);
508:                if (method == 'z')
509:                    return "z|"
510:                            + kelondroBase64Order.enhancedCoder.encode(gzip
511:                                    .gzipString(content));
512:                if (method == 'c')
513:                    return "c|" + scrambleString(key, content);
514:                return null;
515:            }
516:
517:            public static String simpleDecode(String encoded, String key) {
518:                if ((encoded == null) || (encoded.length() < 3))
519:                    return null;
520:                if (encoded.charAt(1) != '|')
521:                    return encoded; // not encoded
522:                char method = encoded.charAt(0);
523:                encoded = encoded.substring(2);
524:                if (method == 'p')
525:                    return encoded;
526:                if (method == 'b')
527:                    return kelondroBase64Order.enhancedCoder.decodeString(
528:                            encoded, "de.anomic.tools.cryptbig.simpleDecode()");
529:                if (method == 'z')
530:                    return gzip.gunzipString(kelondroBase64Order.enhancedCoder
531:                            .decode(encoded,
532:                                    "de.anomic.tools.cryptbig.simpleDecode()"));
533:                if (method == 'c')
534:                    return descrambleString(key, encoded);
535:                return null;
536:            }
537:
538:            // --------------------------------------------------------
539:            // Section: one-way encryption
540:            // --------------------------------------------------------
541:
542:            public static String oneWayEncryption(String key) {
543:                cryptbig crypter = new cryptbig(key);
544:                String e = crypter.encryptString(key);
545:                if (e.length() == 0)
546:                    e = "0XXXX";
547:                if (e.length() % 2 == 1)
548:                    e += "X";
549:                while (e.length() < 32)
550:                    e = e + e;
551:                char[] r = new char[16];
552:                for (int i = 0; i < 16; i++)
553:                    r[i] = e.charAt(2 * i + 1);
554:                return new String(r);
555:            }
556:
557:            // --------------------------------------------------------
558:            // Section: command interface
559:            // --------------------------------------------------------
560:
561:            private static void help() {
562:                System.out.println("AnomicCrypt (2003) by Michael Christen");
563:                System.out.println("Password-based encryption using the "
564:                        + defaultMethod + "-method in standard java");
565:                System.out.println("usage: crypt -h | -help");
566:                System.out.println("       crypt -1 <passwd>");
567:                System.out.println("       crypt -md5 <file>");
568:                System.out
569:                        .println("       crypt ( -es64 | -ds64 | -ec64 | -dc64 ) <string>");
570:                System.out.println("       crypt ( -e | -d ) <key> <string>");
571:                System.out.println("       crypt -enc <key> <file>  \\");
572:                System.out
573:                        .println("                   [-o <target-file> | -preserveFilename]  \\");
574:                System.out
575:                        .println("                   [-d <YYYYMMddHHmmSSsss> | -preserveDate] [-noZip]");
576:                System.out.println("       crypt -dec <key> <file>  \\");
577:                System.out
578:                        .println("                   [-o <target-file> | -preserveFilename]  \\");
579:                System.out
580:                        .println("                   [-d <YYYYMMddHHmmSSsss> | -preserveDate]");
581:                System.out
582:                        .println("       crypt ( -info | -name | -size | -date | -edate )  \\");
583:                System.out.println("                   <key> <encrypted-file>");
584:            }
585:
586:            private static void longhelp() {
587:                // --line-help--   *---------------------------------------------------------------
588:                System.out.println("AnomicCrypt (2003) by Michael Christen");
589:                System.out.println("");
590:                System.out.println("");
591:                System.out.println("crypt -1 <passwd>");
592:                System.out.println("");
593:                System.out
594:                        .println("   One-way encryption of the given password.");
595:                System.out
596:                        .println("   The result is computed by encoding the word with the word as");
597:                System.out
598:                        .println("   the password and repeating it until the length is greater");
599:                System.out
600:                        .println("   than 32. Then every second character is taken to compose the");
601:                System.out
602:                        .println("   result which has always the length of 16 characters.");
603:                System.out.println("");
604:                System.out.println("");
605:                System.out.println("crypt -md5 <file>");
606:                System.out.println("");
607:                System.out
608:                        .println("   MD5 digest according to RFC 1321. The resulting bytes are");
609:                System.out
610:                        .println("   encoded as two-digit hex and concatenated to a single string.");
611:                System.out.println("");
612:                System.out.println("");
613:                System.out.println("crypt -ec64 <cardinal>");
614:                System.out.println("");
615:                System.out
616:                        .println("   Encoding of a cardianal (a positive long integer) with the");
617:                System.out
618:                        .println("   built-in non-standard base-64 algorithm.");
619:                System.out.println("");
620:                System.out.println("");
621:                System.out.println("crypt -dc64 <string>");
622:                System.out.println("");
623:                System.out
624:                        .println("   Decoding of the given b64-coded string to a cardinal number.");
625:                System.out.println("");
626:                System.out.println("");
627:                System.out.println("crypt -es64 <string>");
628:                System.out.println("");
629:                System.out
630:                        .println("   Encoding of a given String to a b64 string.");
631:                System.out.println("");
632:                System.out.println("");
633:                System.out.println("crypt -ds64 <string>");
634:                System.out.println("");
635:                System.out
636:                        .println("   Decoding of a given b64-coded string to a normal string.");
637:                System.out.println("");
638:                System.out.println("");
639:                System.out.println("crypt -e <key> <string>");
640:                System.out.println("");
641:                System.out.println("   Encryption of a given Unicode-String.");
642:                System.out
643:                        .println("   The given string is first encoded to an UTF-8 byte stream, then");
644:                System.out
645:                        .println("   encoded using a password based encryption and then finaly");
646:                System.out
647:                        .println("   encoded to b64 to generate a printable form.");
648:                System.out.println("   The PBE method is " + defaultMethod
649:                        + ".");
650:                System.out.println("");
651:                System.out.println("");
652:                System.out.println("crypt -d <key> <string>");
653:                System.out.println("");
654:                System.out.println("   Decryption of a string.");
655:                System.out.println("   The string is b64-decoded, "
656:                        + defaultMethod + "-decrypted, ");
657:                System.out
658:                        .println("   and then transformed to an unicode string.");
659:                System.out.println("");
660:                System.out.println("");
661:                System.out.println("crypt -enc <key> <file>  \\");
662:                System.out
663:                        .println("            [-o <target-file> | -preserveFilename]  \\");
664:                System.out
665:                        .println("            [-d <target-date YYYYMMddHHmmSSsss> | -preserveDate] [-noZip]");
666:                System.out.println("");
667:                System.out.println("");
668:                System.out.println("");
669:                System.out.println("");
670:                System.out.println("crypt -dec <key> <file>  \\");
671:                System.out
672:                        .println("            [-o <target-file> | -preserveFilename]  \\");
673:                System.out
674:                        .println("            [-d <target-date YYYYMMddHHmmSSsss> | -preserveDate]");
675:                System.out.println("");
676:                System.out.println("");
677:                System.out
678:                        .println("crypt ( -info | -name | -size | -date | -edate ) <key> <encrypted-file>");
679:                System.out.println("");
680:                System.out.println("");
681:            }
682:
683:            public static void main(String[] s) {
684:                if (s.length == 0) {
685:                    help();
686:                    System.exit(0);
687:                }
688:                if ((s[0].equals("-h")) || (s[0].equals("-help"))) {
689:                    longhelp();
690:                    System.exit(0);
691:                }
692:                if (s[0].equals("-tc")) {
693:                    // list all available crypt mehtods:
694:                    Set<String> methods = listCryptoMethods("Cipher");
695:                    System.out.println(methods.size() + " crypt methods:"
696:                            + methods.toString());
697:                    testCryptMethods(methods);
698:                    System.exit(0);
699:                }
700:                if (s[0].equals("-random")) {
701:                    int count = ((s.length == 2) ? (Integer.parseInt(s[1])) : 1);
702:                    for (int i = 0; i < count; i++)
703:                        System.out.println(randomSalt());
704:                    System.exit(0);
705:                }
706:                if (s[0].equals("-1")) {
707:                    if (s.length != 2) {
708:                        help();
709:                        System.exit(-1);
710:                    }
711:                    System.out.println(oneWayEncryption(s[1]));
712:                    System.exit(0);
713:                }
714:                if (s[0].equals("-ec64")) {
715:                    // generate a b64 encoding from a given cardinal
716:                    if (s.length != 2) {
717:                        help();
718:                        System.exit(-1);
719:                    }
720:                    System.out.println(kelondroBase64Order.standardCoder
721:                            .encodeLong(Long.parseLong(s[1]), 0));
722:                    System.exit(0);
723:                }
724:                if (s[0].equals("-dc64")) {
725:                    // generate a b64 decoding from a given cardinal
726:                    if (s.length != 2) {
727:                        help();
728:                        System.exit(-1);
729:                    }
730:                    System.out.println(kelondroBase64Order.standardCoder
731:                            .decodeLong(s[1]));
732:                    System.exit(0);
733:                }
734:                if (s[0].equals("-es64")) {
735:                    // generate a b64 encoding from a given string
736:                    if (s.length != 2) {
737:                        help();
738:                        System.exit(-1);
739:                    }
740:                    System.out.println(kelondroBase64Order.standardCoder
741:                            .encodeString(s[1]));
742:                    System.exit(0);
743:                }
744:                if (s[0].equals("-ds64")) {
745:                    // generate a b64 decoding from a given string
746:                    if (s.length != 2) {
747:                        help();
748:                        System.exit(-1);
749:                    }
750:                    System.out.println(kelondroBase64Order.standardCoder
751:                            .decodeString(s[1], ""));
752:                    System.exit(0);
753:                }
754:                if (s[0].equals("-ess")) {
755:                    // 'scramble' string
756:                    if (s.length != 3) {
757:                        help();
758:                        System.exit(-1);
759:                    }
760:                    long t = System.currentTimeMillis();
761:                    System.out.println(scrambleString(s[1], s[2]));
762:                    System.out.println("Calculation time: "
763:                            + (System.currentTimeMillis() - t)
764:                            + " milliseconds");
765:                    System.exit(0);
766:                }
767:                if (s[0].equals("-dss")) {
768:                    // 'descramble' string
769:                    if (s.length != 3) {
770:                        help();
771:                        System.exit(-1);
772:                    }
773:                    long t = System.currentTimeMillis();
774:                    System.out.println(descrambleString(s[1], s[2]));
775:                    System.out.println("Calculation time: "
776:                            + (System.currentTimeMillis() - t)
777:                            + " milliseconds");
778:                    System.exit(0);
779:                }
780:                if (s[0].equals("-e")) {
781:                    if (s.length != 3) {
782:                        help();
783:                        System.exit(-1);
784:                    }
785:                    System.out
786:                            .println((new cryptbig(s[1])).encryptString(s[2]));
787:                    System.exit(0);
788:                }
789:                if (s[0].equals("-d")) {
790:                    if (s.length != 3) {
791:                        help();
792:                        System.exit(-1);
793:                    }
794:                    System.out
795:                            .println((new cryptbig(s[1])).decryptString(s[2]));
796:                    System.exit(0);
797:                }
798:                if (s[0].equals("-md5")) {
799:                    // generate a public key from a password that can be used for encryption
800:                    if (s.length != 2) {
801:                        help();
802:                        System.exit(-1);
803:                    }
804:                    String md5s = serverCodings.encodeMD5Hex(new File(s[1]));
805:                    System.out.println(md5s);
806:                    System.exit(0);
807:                }
808:                if (s[0].equals("-enc")) {
809:                    if ((s.length < 3) || (s.length > 4)) {
810:                        help();
811:                        System.exit(-1);
812:                    }
813:                    String target;
814:                    if (s.length == 3)
815:                        target = s[2] + ".crypt";
816:                    else
817:                        target = s[3];
818:                    (new cryptbig(s[1]))
819:                            .encryptFile(s[2], target, true /*compress*/);
820:                    System.exit(0);
821:                }
822:                if (s[0].equals("-dec")) {
823:                    if ((s.length < 3) || (s.length > 4)) {
824:                        help();
825:                        System.exit(-1);
826:                    }
827:                    String target;
828:                    if (s.length == 3) {
829:                        if (s[2].endsWith(".crypt"))
830:                            target = s[2].substring(0, s[2].length() - 7);
831:                        else
832:                            target = s[2] + ".decoded";
833:                    } else {
834:                        target = s[3];
835:                    }
836:                    (new cryptbig(s[1])).decryptFile(s[2], target);
837:                    System.exit(0);
838:                }
839:                help();
840:                System.exit(-1);
841:            }
842:
843:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.