Created
July 16, 2014 04:32
-
-
Save xuyang2/a57ea05b026cadaa5c00 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import junit.framework.Assert; | |
import org.apache.commons.codec.binary.Base64; | |
import org.bouncycastle.crypto.engines.RC4Engine; | |
import org.bouncycastle.crypto.params.KeyParameter; | |
import org.bouncycastle.jce.provider.BouncyCastleProvider; | |
import org.junit.Before; | |
import org.junit.Test; | |
import javax.crypto.Cipher; | |
import javax.crypto.spec.SecretKeySpec; | |
import java.security.Security; | |
/** | |
* Created by xuy on 2014/7/16. | |
*/ | |
public class RC4Test { | |
private String secret; | |
private String plainText; | |
private String expectedCipherText; | |
@Before | |
public void setUp() throws Exception { | |
Security.addProvider(new BouncyCastleProvider()); | |
secret = "secret"; | |
plainText = "RC4测试"; | |
expectedCipherText = "v3Xm+jcvPgmn"; | |
} | |
// use RC4Engine | |
@Test | |
public void test1() throws Exception { | |
RC4Engine streamCipher = new RC4Engine(); | |
byte[] keyBytes = secret.getBytes(); | |
streamCipher.init(true, new KeyParameter(keyBytes)); | |
byte[] plainTextBytes = plainText.getBytes(); | |
byte[] cipherTextBytes = new byte[plainTextBytes.length]; | |
streamCipher.processBytes(plainTextBytes, 0, plainTextBytes.length, cipherTextBytes, 0); | |
Assert.assertEquals(expectedCipherText, Base64.encodeBase64String(cipherTextBytes)); | |
} | |
// use Cipher | |
@Test | |
public void test2() throws Exception { | |
byte[] keyBytes = secret.getBytes(); | |
SecretKeySpec key = new SecretKeySpec(keyBytes, "RC4"); | |
Cipher cipher = Cipher.getInstance("RC4", "BC"); | |
cipher.init(Cipher.ENCRYPT_MODE, key); | |
byte[] plainTextBytes = plainText.getBytes(); | |
byte[] cipherTextBytes = cipher.doFinal(plainTextBytes); | |
Assert.assertEquals(expectedCipherText, Base64.encodeBase64String(cipherTextBytes)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment