001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.codec.digest;
018
019import static org.junit.Assert.assertEquals;
020import static org.junit.Assert.assertNotNull;
021import static org.junit.Assert.assertTrue;
022
023import org.junit.Test;
024
025public class CryptTest {
026
027    @Test
028    public void testCrypt() {
029        assertNotNull(new Crypt()); // just for Test Coverage
030    }
031
032    @Test
033    public void testDefaultCryptVariant() {
034        // If salt is null or completely omitted, a random "$6$" is used.
035        assertTrue(Crypt.crypt("secret").startsWith("$6$"));
036        assertTrue(Crypt.crypt("secret", null).startsWith("$6$"));
037    }
038
039    @Test
040    public void testCryptWithBytes() {
041        final byte[] keyBytes = new byte[] { 'b', 'y', 't', 'e' };
042        final String hash = Crypt.crypt(keyBytes);
043        assertEquals(hash, Crypt.crypt("byte", hash));
044    }
045
046    /**
047     * An empty string as salt is invalid.
048     *
049     * The C and Perl implementations return an empty string, PHP threads it
050     * as NULL. Our implementation should throw an Exception as any resulting
051     * hash would not be verifyable with other implementations of crypt().
052     */
053    @Test(expected = IllegalArgumentException.class)
054    public void testCryptWithEmptySalt() {
055        Crypt.crypt("secret", "");
056    }
057
058}