⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch12.txt

📁 精通Java网络编程代码全部
💻 TXT
📖 第 1 页 / 共 2 页
字号:
	public SecurityManagerFrame()
	{
		setTitle("SecurityManagerTest");
		//设置大小宽度
		setSize(WIDTH, HEIGHT);
		
		fileNameField = new JTextField(20);
        JPanel panel = new JPanel();//设置控制版面
        panel.add(new JLabel("Text file:"));
        panel.add(fileNameField);//添加各种按钮
        JButton openButton = new JButton("Open");
		panel.add(openButton);
        openButton.addActionListener(new
			ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
                loadFile(fileNameField.getText());
			}
        });
		//添加组件
		Container contentPane = getContentPane();
		contentPane.add(panel, "North");
		
		fileText = new JTextArea();
        contentPane.add(new JScrollPane(fileText), "Center");
	}
	
    /**
	将下载的文件放入到文本框中
	@param filename the file name
	*/
	public void loadFile(String filename)
	{
        try
		{
			fileText.setText("");
			BufferedReader in
				= new BufferedReader(new FileReader(filename));
			String s;
			while ((s = in.readLine()) != null)
				fileText.append(s + "\n");
			in.close();
		}
		catch (IOException e)
		{
			fileText.append(e + "\n");
		}
		catch (SecurityException e)
		{
			//输出错误信息
			fileText.append("I am sorry, but I cannot do that.");
		}
	}
	
	private JTextField fileNameField;
	private JTextArea fileText;
    private static final int WIDTH = 400;
	private static final int HEIGHT = 300;
}

/* 代码12-6
 * Created on 2005-5-22
 */

import java.io.*;
import java.security.*;

/**
检测是否遇到的了“坏话”
*/
public class WordCheckSecurityManager extends SecurityManager
{
	public void checkPermission(Permission p)
	{
        if (p instanceof FilePermission
			&& p.getActions().equals("read"))
        {
			if (inSameManager())
				return;
			String fileName = p.getName();//获取文件名
			if (containsBadWords(fileName))
				throw new SecurityException("Bad words in "
                + fileName);
		}
		else super.checkPermission(p);
	}
	
    public boolean inSameManager()
    {
		Class[] cc = getClassContext();
		
		//跳出此程序
		int i = 0;
		while (i < cc.length && cc[0] == cc[i])
			i++;
		
		// 检测是否有另一个调用
		while (i < cc.length)
		{
			if (cc[0] == cc[i]) return true;
			i++;
		}
		return false;
	}
	
	/**
	检测文件是否有“坏话”
	@param fileName the name of the file
	@return true if the file name ends with .txt and it
	contains at least one bad word.
    */
    boolean containsBadWords(String fileName)
    {
		if (!fileName.toLowerCase().endsWith(".txt")) return false;
		// 只是检测文本文件
		BufferedReader in = null;
		try
		{
			in = new BufferedReader(new FileReader(fileName));
			String s;
			while ((s = in.readLine()) != null)
			{
				for (int i = 0; i < badWords.length; i++)
					if (s.toLowerCase().indexOf(badWords[i]) != -1)
						return true;
			}
			in.close();//关闭输入流
			return false;
		}
		catch(IOException e)
		{
			return true;
		}
		finally
		{
			if (in != null)
				try { in.close(); } catch (IOException e) {}
		}
	}
	
    private String[] badWords = { "sex", "drugs", "c++" };
}

/* 代码12-7
 * Created on 2005-5-22
 */

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;

public class FileReadApplet extends JApplet
{
    public FileReadApplet()
    {
		fileNameField = new JTextField(20);
		JPanel panel = new JPanel();//设置控制版面
		panel.add(new JLabel("File name:"));//添加标志位
		panel.add(fileNameField);
		JButton openButton = new JButton("Open");
		panel.add(openButton);
		openButton.addActionListener(new
			ActionListener()
		{
			public void actionPerformed(ActionEvent event)
            {
                loadFile(fileNameField.getText());
			}
		});
		
		Container contentPane = getContentPane();
		contentPane.add(panel, "North");
		
		fileText = new JTextArea();
		contentPane.add(new JScrollPane(fileText), "Center");
    }
	
    /**
	将下载的文件放入文本框中
	@param filename the file name
    */
    public void loadFile(String filename)
	{
		try
		{  fileText.setText("");
		BufferedReader in
			= new BufferedReader(new FileReader(filename));//设置缓冲区
		String s;
		while ((s = in.readLine()) != null)
			fileText.append(s + "\n");
		in.close();
		}
		catch (IOException e)
		{
			fileText.append(e + "\n");
		}
		catch (SecurityException e)
		{
			fileText.append("I am sorry, but I cannot do that.");//打印错误信息
		}
	}
	
    private JTextField fileNameField;
	private JTextArea fileText;
}

/* 代码12-8
 * Created on 2005-5-22
 */

Certificate ::= SWQUENCE {
tbsCertificate       TBSCertificate,
signatureAlgorithm   AlgorithmIdentifier,
signature            BIT STRING)

TBSCertificate  ::= SEQUENCE {
version         [0]  EXPLICIT Version DEFAULT v1,
serialNumber         CertificateSerialNumber,
signature            AlgorithmIdentifier,
issuer               Name,
validity             Validity,
subject              Name,
subjectPublicKeyInfo SubjectPublicKeyInfo,
issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
-- If present, version must be v2 or
v3
subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
-- If present, version must be v2 or
v3
extensions      [3]  EXPLICIT Extensions OPTIONAL
--If present, version must be v3
}
Version  ::= INTEGER { v1(0), v2(1), v3(2) }
CertificationSerialNumber ::= INTEGER
Validity ::= SEQUENCE {
notBefore      CertificateValidityDate,
notAfter       CertificateValidityDate}
CertificateValidityDate ::= CHOICE {
utcTime        UTCTime,
generalTime    GeneralizedTime}
UniqueIdentifier  ::= BIT STRING

SubjectPublicKeyInfo ::= SEQUENCE{
algorithm         AlgorithmIdentifier,
subjectPublicKey  BIT STRING}

Extensions ::= SEQUENCE OF Extension

Extension  ::= SEQUENCE {
extnID    OBJECT IDENTIFIER,
critical  BOOLEAN DEFAULT FALSE,
extnValue OCTET STRING}

/* 代码12-9
 * Created on 2005-5-22
 */

import java.io.*;
import java.security.*;
import java.security.cert.*;
import java.util.*;

import sun.security.x509.X509CertInfo;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X500Name;
import sun.security.x509.CertificateIssuerName;

/**
此程序给出认证
*/
public class CertificateSigner
{
	public static void main(String[] args)
	{
        String ksname = null; //  keystore名字
        String alias = null; // 私有的别名
        String inname = null; // 输入的文件名
		String outname = null; //输出的文件名
        for (int i = 0; i < args.length; i += 2)
		{
			if (args[i].equals("-keystore"))
				ksname = args[i + 1];
			else if (args[i].equals("-alias"))
				alias = args[i + 1];
			else if (args[i].equals("-infile"))
				inname = args[i + 1];
			else if (args[i].equals("-outfile"))
				outname = args[i + 1];
			else usage();
        }
		
		if (ksname == null || alias == null ||
			inname == null || outname == null) usage();
		
        try
        {
			PushbackReader console = new PushbackReader(new
				InputStreamReader(System.in));
			
			KeyStore store = KeyStore.getInstance("JKS", "SUN");
			InputStream in = new FileInputStream(ksname);
			System.out.print("Keystore password: ");
			System.out.flush();
			char[] password = readPassword(console);
			store.load(in, password);
			Arrays.fill(password, ' ');
			in.close();
			
			System.out.print("Key password for " + alias + ": ");
			System.out.flush();
			char[] keyPassword = readPassword(console);
			PrivateKey issuerPrivateKey
				= (PrivateKey)store.getKey(alias, keyPassword);
			Arrays.fill(keyPassword, ' ');
			
			if (issuerPrivateKey == null)
				error("No such private key");
			
			in = new FileInputStream(inname);
			
			CertificateFactory factory
				= CertificateFactory.getInstance("X.509");
			
			X509Certificate inCert
				= (X509Certificate)factory.generateCertificate(in);
			in.close();
			byte[] inCertBytes = inCert.getTBSCertificate();
			
			X509Certificate issuerCert
				= (X509Certificate)store.getCertificate(alias);
			Principal issuer = issuerCert.getSubjectDN();
			String issuerSigAlg = issuerCert.getSigAlgName();
			
			FileOutputStream out = new FileOutputStream(outname);
			
			X509CertInfo info = new X509CertInfo(inCertBytes);
			info.set(X509CertInfo.ISSUER,
				new CertificateIssuerName((X500Name)issuer));
			
			X509CertImpl outCert = new X509CertImpl(info);
			outCert.sign(issuerPrivateKey, issuerSigAlg);
			outCert.derEncode(out);
			
			out.close();
        }
        catch (Exception exception)
        {
			exception.printStackTrace();
        }
	}
	
	/**
	读入密码
	*/
    public static char[] readPassword(PushbackReader in)
		throws IOException
    {
		final int MAX_PASSWORD_LENGTH = 100;//设置密码最大位
		int length = 0;
		char[] buffer = new char[MAX_PASSWORD_LENGTH];
		
		while (true)
		{
			int ch = in.read();
			if (ch == '\r' || ch == '\n' || ch == -1
				|| length == MAX_PASSWORD_LENGTH)
			{
				if (ch == '\r') // handle DOS "\r\n" line ends
				{
					ch = in.read();
					if (ch != '\n' && ch != -1) in.unread(ch);
				}
				char[] password = new char[length];//设置密码
				System.arraycopy(buffer, 0, password, 0, length);
				Arrays.fill(buffer, ' ');
				return password;
			}
			else
			{
				buffer[length] = (char)ch;
				length++;
			}
		}
    }
	
    /**
	打印错误信息并退出
	@param message
	*/
	public static void error(String message)
	{
		System.out.println(message);
		System.exit(1);
    }
	
	/**
	打印有用信息
	*/
    public static void usage()
    {
		System.out.println("Usage: java CertificateSigner"
			+ " -keystore keyStore -alias issuerKeyAlias"
			+ " -infile inputFile -outfile outputFile");
		System.exit(1);
    }
  }

/* 代码12-9
 * Created on 2005-5-22
 */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -