使用策略文件的方法如下。
创建一个可以特权使用的Java文件:
package egPriv;import java.io.FileReader;import java.io.IOException;import java.io.Reader;import java.security.AccessController;import java.security.PrivilegedActionException;import java.security.PrivilegedExceptionAction;public class PrivCat { public void cat(String file) throws IOException { cat(new FileReader(file)); } private void cat(Reader r) throws IOException { int c; while( (c = r.read()) != -1 ) { System.out.print((char) c); } r.close(); } public void catPriv(final String file) throws IOException { Reader r; try { r = AccessController.doPrivileged(new PrivilegedExceptionAction<Reader>() { public Reader run() throws IOException { return new FileReader(file); } }); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); } cat(r); }}
创建一个常规文件进行演示
package eg;import egPriv.PrivCat;import java.io.IOException;public class Cat extends PrivCat { public static void main(String[] args) throws IOException { Cat eg2 = new Cat(); System.out.println("Processing with privilege:"); eg2.catPriv(args[0]); System.out.println("Processing normally"); eg2.cat(args[0]); }}
创建sample.policy文件:
grant { permission java.io.FilePermission "${user.dir}", "read,write,execute";};grant { permission java.io.FilePermission "${user.dir}grant prebase "file:egPriv.jar" { permission java.io.FilePermission "<<ALL FILES>>", "read,write,execute,delete";};
编译然后测试:
jar cvf egPriv.jar egPrivjar cvf eg.jar egecho 'Restricted' > ..file.txtjava -cp eg.jar;egPriv.jar -Djava.security.manager -Djava.security.policy=sample.policy eg.Cat ..file.txtecho 'Open' > file.txtjava -cp eg.jar;egPriv.jar -Djava.security.manager -Djava.security.policy=sample.policy eg.Cat file.txt
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)