1 package org.apache.fulcrum.crypto.provider;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import java.util.Random;
23
24 import org.apache.fulcrum.crypto.CryptoAlgorithm;
25
26 /**
27 * Implements Standard Unix crypt(3) for use with the Crypto Service.
28 *
29 * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
30 * @version $Id$
31 */
32 public class UnixCrypt implements CryptoAlgorithm
33 {
34
35 /** The seed to use */
36 private String seed = null;
37
38 /** standard Unix crypt chars (64) */
39 private static final char[] SALT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"
40 .toCharArray();
41
42 /**
43 * Constructor
44 */
45 public UnixCrypt()
46 {
47 }
48
49 /**
50 * This class never uses anything but UnixCrypt, so it is just a dummy (Fixme:
51 * Should we throw an exception if something is requested that we don't support?
52 *
53 * @param cipher Cipher (ignored)
54 */
55 public void setCipher(String cipher)
56 {
57 /* dummy */
58 }
59
60 /**
61 * Setting the seed for the UnixCrypt algorithm. If a null value is supplied, or
62 * no seed is set, then a random seed is used.
63 *
64 * @param seed The seed value to use.
65 */
66 public void setSeed(String seed)
67 {
68 this.seed = seed;
69 }
70
71 /**
72 * Encrypt the supplied string with the requested cipher
73 *
74 * @param value The value to be encrypted
75 * @return The encrypted value
76 * @throws Exception An Exception of the underlying implementation.
77 */
78 public String encrypt(String value) throws Exception
79 {
80 if (seed == null)
81 {
82 Random randomGenerator = new Random();
83 int numSaltChars = SALT_CHARS.length;
84 StringBuilder sb = new StringBuilder();
85 sb.append(SALT_CHARS[Math.abs(randomGenerator.nextInt() % numSaltChars)])
86 .append(SALT_CHARS[Math.abs(randomGenerator.nextInt() % numSaltChars)]).toString();
87 seed = sb.toString();
88 }
89
90 // use commons-codec to do the encryption
91 return org.apache.commons.codec.digest.UnixCrypt.crypt(value, seed);
92 }
93 }