Skip to content

Commit

Permalink
shiro教程
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangkaitao committed Jan 29, 2014
1 parent f6a1e12 commit d0660ce
Show file tree
Hide file tree
Showing 49 changed files with 2,233 additions and 3 deletions.
6 changes: 3 additions & 3 deletions shiro-example-chapter2/src/sql/shiro.sql
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,21 @@ create table users (
password varchar(100),
password_salt varchar(100),
constraint pk_users primary key(id)
);
) charset=utf8 ENGINE=InnoDB;
create unique index idx_users_username on users(username);

create table user_roles(
id bigint auto_increment,
username varchar(100),
role_name varchar(100),
constraint pk_user_roles primary key(id)
);
) charset=utf8 ENGINE=InnoDB;
create unique index idx_user_roles on user_roles(username, role_name);

create table roles_permissions(
id bigint auto_increment,
role_name varchar(100),
permission varchar(100),
constraint pk_roles_permissions primary key(id)
);
) charset=utf8 ENGINE=InnoDB;
create unique index idx_roles_permissions on roles_permissions(role_name, permission);
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import org.apache.shiro.mgt.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.util.ThreadContext;
import org.junit.After;

/**
* <p>User: Zhang Kaitao
Expand All @@ -15,6 +17,11 @@
public abstract class BaseTest {


@After
public void tearDown() throws Exception {
ThreadContext.unbindSubject();//退出时请解除绑定Subject到线程 否则对下次测试造成影响
}

protected void login(String configFile, String username, String password) {
//1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
Factory<org.apache.shiro.mgt.SecurityManager> factory =
Expand Down
7 changes: 7 additions & 0 deletions shiro-example-chapter5/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@
<version>0.2.23</version>
</dependency>

<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.6</version>
</dependency>


</dependencies>


Expand Down
5 changes: 5 additions & 0 deletions shiro-example-chapter5/src/sql/shiro-init-data.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
insert into users(username, password, password_salt) values('wu', '$shiro1$SHA-512$1$$PJkJr+wlNU1VHa4hWQuybjjVPyFzuNPcPu5MBH56scHri4UQPjvnumE7MbtcnDYhTcnxSkL9ei/bhIVrylxEwg==', null);
insert into users(username, password, password_salt) values('liu', 'a9a114054aa6758184314fbb959fbda4', '24520ee264eab73ec09451d0e9ea6aac');



Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.github.zhangkaitao.shiro.chapter5.hash;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.util.ThreadContext;
import org.junit.After;

/**
* <p>User: Zhang Kaitao
* <p>Date: 14-1-26
* <p>Version: 1.0
*/
public abstract class BaseTest {



@After
public void tearDown() throws Exception {
ThreadContext.unbindSubject();//退出时请解除绑定Subject到线程 否则对下次测试造成影响
}

protected void login(String configFile, String username, String password) {
//1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
Factory<org.apache.shiro.mgt.SecurityManager> factory =
new IniSecurityManagerFactory(configFile);

//2、得到SecurityManager实例 并绑定给SecurityUtils
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);

//3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);

subject.login(token);
}

public Subject subject() {
return SecurityUtils.getSubject();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
package com.github.zhangkaitao.shiro.chapter5.hash;

import junit.framework.Assert;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.*;
import org.apache.shiro.crypto.hash.*;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.junit.Test;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
* <p>User: Zhang Kaitao
* <p>Date: 14-1-27
* <p>Version: 1.0
*/
public class CodecAndCryptoTest {



@Test
public void testBase64() {
String str = "hello";
String base64Encoded = Base64.encodeToString(str.getBytes());
String str2 = Base64.decodeToString(base64Encoded);
Assert.assertEquals(str, str2);

}

@Test
public void testHex() {
String str = "hello";
String base64Encoded = Hex.encodeToString(str.getBytes());
String str2 = new String(Hex.decode(base64Encoded.getBytes()));
Assert.assertEquals(str, str2);

}

@Test
public void testCodecSupport() {
String str = "hello";
byte[] bytes = CodecSupport.toBytes(str, "utf-8");
String str2 = CodecSupport.toString(bytes, "utf-8");
Assert.assertEquals(str, str2);
}


@Test
public void testRandom() {
//生成随机数
SecureRandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
randomNumberGenerator.setSeed("123".getBytes());
System.out.println(randomNumberGenerator.nextBytes().toHex());
}



@Test
public void testMd5() {
String str = "hello";
String salt = "123";
String md5 = new Md5Hash(str, salt).toString();//还可以转换为 toBase64()/toHex()
System.out.println(md5);


}

@Test
public void testSha1() {
String str = "hello";
String salt = "123";
String sha1 = new Sha1Hash(str, salt).toString();
System.out.println(sha1);

}

@Test
public void testSha256() {
String str = "hello";
String salt = "123";
String sha1 = new Sha256Hash(str, salt).toString();
System.out.println(sha1);

}

@Test
public void testSha384() {
String str = "hello";
String salt = "123";
String sha1 = new Sha384Hash(str, salt).toString();
System.out.println(sha1);

}

@Test
public void testSha512() {
String str = "hello";
String salt = "123";
String sha1 = new Sha512Hash(str, salt).toString();
System.out.println(sha1);

}

@Test
public void testSimpleHash() {
String str = "hello";
String salt = "123";
//MessageDigest
String simpleHash = new SimpleHash("SHA-1", str, salt).toString();
System.out.println(simpleHash);

}



@Test
public void testHashService() {
DefaultHashService hashService = new DefaultHashService(); //默认算法SHA-512
hashService.setHashAlgorithmName("SHA-512");
hashService.setPrivateSalt(new SimpleByteSource("123")); //私盐,默认无
hashService.setGeneratePublicSalt(true);//是否生成公盐,默认false
hashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());//用于生成公盐。默认就这个
hashService.setHashIterations(1); //生成Hash值的迭代次数

HashRequest request = new HashRequest.Builder()
.setAlgorithmName("MD5").setSource(ByteSource.Util.bytes("hello"))
.setSalt(ByteSource.Util.bytes("123")).setIterations(2).build();
String hex = hashService.computeHash(request).toHex();
System.out.println(hex);
}


@Test
public void testAesCipherService() {
AesCipherService aesCipherService = new AesCipherService();
aesCipherService.setKeySize(128);//设置key长度

//生成key
Key key = aesCipherService.generateNewKey();

String text = "hello";

//加密
String encrptText = aesCipherService.encrypt(text.getBytes(), key.getEncoded()).toHex();
//解密
String text2 = new String(aesCipherService.decrypt(Hex.decode(encrptText), key.getEncoded()).getBytes());

Assert.assertEquals(text, text2);
}

@Test
public void testBlowfishCipherService() {
BlowfishCipherService blowfishCipherService = new BlowfishCipherService();
blowfishCipherService.setKeySize(128);

//生成key
Key key = blowfishCipherService.generateNewKey();

String text = "hello";

//加密
String encrptText = blowfishCipherService.encrypt(text.getBytes(), key.getEncoded()).toHex();
//解密
String text2 = new String(blowfishCipherService.decrypt(Hex.decode(encrptText), key.getEncoded()).getBytes());

Assert.assertEquals(text, text2);
}

@Test
public void testDefaultBlockCipherService() throws Exception {


//对称加密,使用Java的JCA(javax.crypto.Cipher)加密API,常见的如 'AES', 'Blowfish'
DefaultBlockCipherService cipherService = new DefaultBlockCipherService("AES");
cipherService.setKeySize(128);

//生成key
Key key = cipherService.generateNewKey();

String text = "hello";

//加密
String encrptText = cipherService.encrypt(text.getBytes(), key.getEncoded()).toHex();
//解密
String text2 = new String(cipherService.decrypt(Hex.decode(encrptText), key.getEncoded()).getBytes());

Assert.assertEquals(text, text2);
}


//加密/解密相关知识可参考snowolf的博客 http://snowolf.iteye.com/category/68576


}
Loading

0 comments on commit d0660ce

Please sign in to comment.