Java tutorial
/****************************************************************************** * Copyright (c) 2014 Fred Laderoute. * All rights reserved. This program and the accompanying * materials are made available under the terms of the GNU * Public License v3.0 which accompanies this distribution, * and is available at http://www.gnu.org/licenses/gpl.html * * Contributors: * Fred Laderoute - initial API and implementation ******************************************************************************/ package com.password.locker.cypto.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Security; import javax.crypto.NoSuchPaddingException; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.Arrays; import org.junit.Before; import org.junit.Test; import com.password.locker.crypto.SecureCryptoImpl; /** * @author fred * */ public class SecureCryptoTest { /** * Crypto implementation. */ private SecureCryptoImpl secImpl; /** * @throws java.lang.Exception * if an error occurs. */ @Before public final void setUp() throws Exception { Security.addProvider(new BouncyCastleProvider()); String password = "password"; secImpl = new SecureCryptoImpl(password.toCharArray()); } /** * Main test. * @throws NoSuchPaddingException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException * @throws InvalidKeyException */ @Test public final void testEncryptStrings() throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException { String data = "Plain text data."; String enc = secImpl.encrypt(data); String plain = secImpl.decrypt(enc); assertEquals(data, plain); assertFalse(enc.equals(plain)); } /** * Main test. * @throws NoSuchPaddingException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException * @throws InvalidKeyException */ @Test public final void testEncryptBytes() throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException { byte[] data = { (byte) 0x1, (byte) 0x1, (byte) 0x1, (byte) 0x1, (byte) 0x1 }; byte[] enc = secImpl.encrypt(data); byte[] plain = secImpl.decrypt(enc); assertTrue(Arrays.areEqual(plain, data)); assertFalse(Arrays.areEqual(plain, enc)); } }