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

📄 rsatools.java

📁 Java实现RSA DES SHA算法以完成一个加密组件
💻 JAVA
📖 第 1 页 / 共 2 页
字号:

			byte[] input = this.getByteFromStream(fis);

			byte[] output = this.basicSignature(input);

			//System.out.println("数字签名信息" + Base64.encode(output));

			String cipherFilePath = file.getPath() + ".sig";     //存储签名信息的文件路径

			File fileOut = new File(cipherFilePath);

			fos = new FileOutputStream(fileOut);

			for (int i = 0; i < output.length; i++)
			{
				fos.write((int) output[i]);
			}
			System.out.println("数字签名成功");
			return fileOut;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw e;

		}
		finally
		{
			this.closeStream();
		}
	}

	/**
	 * 验证签名信息,对.sig存有签名信息的文件进行验证
	 * @param plainText 明文
	 * @param signMessage 签名信息文件,扩展名为.sig
	 * @param key   验证签名所需公钥key
	 * @return      验证结果
	 *               true 签名正确
	 *               false签名错误
	 * @throws Exception
	 */
	public boolean validateSignature(File plainText, File signMessage, Key key) throws Exception
	{
		if (plainText == null)
		{
			return false;
		}
		if (!plainText.exists() || plainText.isDirectory())
		{
			return false;
		}
		if (key == null)
		{
			return false;
		}

		this.pubKey = (PublicKey) key;

		FileInputStream fis2 = null;
		try
		{
			String signPath = signMessage.getPath();
			if (!signPath.substring(signPath.length() - 4).toLowerCase().equals(".sig"))//判断签名信息文件护展名是否为.sig
			{
				return false;
			}
			fis = new FileInputStream(plainText);

			byte[] plain = this.getByteFromStream(fis);

			fis2 = new FileInputStream(signMessage);

			byte[] input = this.getByteFromStream(fis2);

			return this.basicValidateSign(plain, input);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (fis2 != null)
			{
				fis.close();
			}
			this.closeStream();
		}
		return false;
	}
	
	/**
	 * 数字签名 
	 * @param plainStream   存有明文信息的输入流
	 * @param key           数字签名所需的私钥
	 * @param signPath      存放签名信息的文件路径
	 * @return   存有签名信息的文件
	 * @throws Exception
	 */
	public File digitalSignature(InputStream plainStream, Key key,String signPath) throws Exception
	{
		if (plainStream == null)
		{
			return null;
		}

		this.setKeyPairWhenSignature(key);

		try
		{
			byte[] input = this.getByteFromStream(plainStream);

			byte[] output = this.basicSignature(input);

			File outSignMessage = new File(signPath);  // 存有签名信息的文件
			
			fos = new FileOutputStream(outSignMessage);
			for (int i = 0; i < output.length; i++)
			{
				fos.write((int) output[i]);
			}
			
			System.out.println("签名成功");
			return outSignMessage;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		finally
		{
			this.closeStream();
		}
	}
	
	/**
	 * 验证签名信息
	 * @param plainStream 存有明文信息的输入流
	 * @param signStream  存有签名信息的输入流
	 * @param key         验证签名所需的公钥key
	 * @return            验证结果
	 *                    true 签名正确
	 *                    false签名错误
	 * @throws Exception
	 */
	public boolean validateSignature(InputStream plainStream, InputStream signStream, Key key) throws Exception
	{
		if (plainStream == null || signStream == null || key == null)
		{
			return false;
		}
		this.pubKey = (PublicKey) key;

		byte[] plain = this.getByteFromStream(plainStream);
		byte[] input = this.getByteFromStream(signStream);

		System.out.println("验证结束");
		return this.basicValidateSign(plain, input);
	}

	/**
	 * 返回密钥对
	 */
	public KeyPair getKeyPair() throws Exception
	{
		return this.rsaKeyPair;
	}

	/**
	 * 返回私钥
	 */
	public Key getPrivateKey() throws Exception
	{
		return this.priKey;
	}
	
	/**
	 * 返回公钥
	 */
	public Key getPublicKey() throws Exception
	{
		return this.pubKey;
	}

	/**
	 * 生成RSA密钥对
	 * @return 密钥对KeyPair
	 * @throws Exception
	 */
	private KeyPair generateKeyPair() throws Exception
	{
		KeyPair kPair = null;
		try
		{
			// 根据加密算法获得KeyPairGenerator对象 
			KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
			// 设置密钥长度
			keyGen.initialize(1024);
			kPair = keyGen.generateKeyPair();

		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
			throw e;
		}
		return kPair;
	}

	/**
	 * 加密操作时,设置加密公钥
	 * 如果key 为null,则自动生成一个密钥对,用其中的公钥进行加密
	 * 如果不为null,则作为公钥进行加密操作
	 * @param key   密钥
	 * @return     加密所需公钥是否设置成功
	 * @throws Exception
	 */
	private Boolean setKeyPairWhenEncrypt(Key key) throws Exception
	{

		try
		{
			if (key == null)
			{
				this.rsaKeyPair = this.generateKeyPair();
				this.pubKey = this.rsaKeyPair.getPublic();
				this.priKey = this.rsaKeyPair.getPrivate();
			}
			else
			{
				this.pubKey = (PublicKey) key;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		return true;
	}
	
	/**
	 * 数字签名时,设置签名操作所用密钥
	 * 如果密钥key不为空,则作为私钥存储
	 * 如果为null,则自动生成一组密钥对,用其中的私钥进行签名操作
	 * @param key  密钥
	 * @return  私钥是否设置成功
	 * @throws Exception
	 */
	private Boolean setKeyPairWhenSignature(Key key) throws Exception
	{

		try
		{
			if (key == null)
			{
				this.rsaKeyPair = this.generateKeyPair();
				this.pubKey = this.rsaKeyPair.getPublic();
				this.priKey = this.rsaKeyPair.getPrivate();
			}
			else
			{
				this.priKey = (PrivateKey) key;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		return true;
	}
	
	/**
	 * 实现基本的加密功能,供其它方法调用
	 * @param input 要进行加密的字节数据
	 * @return      加密处理后的密文数据(字节数组形式) 
	 * @throws Exception
	 */
	private byte[] basicEncrypt(byte[] input) throws Exception
	{
		Cipher cipher = null;
		try
		{
			cipher = Cipher.getInstance(algorithm);

			cipher.init(Cipher.ENCRYPT_MODE, this.pubKey); // 用公钥pubKey初始化此Cipher

			return cipher.doFinal(input);                 //加密
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw e;
		}

	}
	
	/**
	 * 基本的解密方法,供其它方法调用
	 * @param input   要进行解密的字节数据
	 * @return   解密处理后的密文数据(字节数组形式)
	 * @throws Exception
	 */
	private byte[] basicDecrypt(byte[] input) throws Exception
	{
		Cipher cipher = null;
		try
		{
			cipher = Cipher.getInstance(algorithm);

			cipher.init(Cipher.DECRYPT_MODE, this.priKey); // 用私钥priKey初始化此cipher

			return cipher.doFinal(input);                  //解密
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 实现基本的数字签名功能,供其它方法调用
	 * @param input
	 *           要进行签名的字节数据
	 * @return  字节数组形式的签名信息
	 * @throws Exception
	 */
	private byte[] basicSignature(byte[] input) throws Exception
	{
		try
		{
			Signature sig = Signature.getInstance(SIGNALGORITHM);

			sig.initSign(this.priKey);  //用此私钥初始化此签名对象Signature

			sig.update(input);          

			return sig.sign();          //签名
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 实现基本的签名验证功能,供其它方法调用
	 * @param plain
	 *            明文的字节数据
	 * @param input
	 *            签名信息
	 * @return   验证结果
	 * 			true 签名正确  false签名错误
	 * @throws Exception
	 */
	private boolean basicValidateSign(byte[] plain, byte[] input) throws Exception
	{
		try
		{
			Signature sig = Signature.getInstance(SIGNALGORITHM);

			sig.initVerify(this.pubKey);  // 用公钥pubKey初始化此用于Signature对象。

			sig.update(plain);           

			return sig.verify(input);     //签名验证 
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 获取输入流中的数据,以字节数组形式返回
	 * 
	 * @param is   输入流
	 * @return     以字节数组形式返回输入流中的数据
	 * @throws Exception
	 */
	private byte[] getByteFromStream(InputStream is) throws Exception
	{
		int length = -1;
		ArrayList temp = new ArrayList();

		while ((length = is.read()) != -1)
		{
			temp.add((byte) length);
		}

		byte[] out = new byte[temp.size()];
		for (int i = 0; i < temp.size(); i++)
		{
			Byte byt = (Byte) temp.get(i);
			out[i] = byt.byteValue();
		}
		return out;
	}
	
	/**
	 * 关闭流
	 * @throws Exception
	 */
	private void closeStream() throws Exception
	{
		if(fis!=null)
		{
			fis.close();
		}
		if(fos!=null)
		{
			fos.close();
		}
	}
	
}

⌨️ 快捷键说明

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