通过密码 加密解密算法,java

本文介绍了一种简单的16进制文本加密方法,该方法通过将明文和密钥转换为16进制形式并进行特定的字符运算来实现加密。此外,还提供了详细的解密过程,并附带完整的Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


加密原理:把要加密的内容和密码转换为16进制文本(16进制文本内容为0-F之间,Unicode代码点范围为200内,数字小运算起来不会超出char类型的最大值,达到内容“变身”的效果)加密内容的16进制 和 密码的16进制 相互计算形成新的字符(Unicode代码点改变后的字符);


先说下流程:

加密1:将密码和内容转到16进制字符串

加密2:将加密1得到的内容和密码的16进制字符串的每个字符的Unicode运算得到一个新的字符串(加密完成)

加密3:再将加密2后的字符串内容转到 16进制(开发时可以省略,直接使用加密过的内容)


解密1:将加密3的十六进制内容还原到加密2的内容,即是加密过的内容(如果加密3没使用,这个也不要)

解密2:将加密过的内容和密码每个字符的Unicode值通过加密2的反运算得到原来内容Unicode16进制字符值

解密3:将解密2得到的16进制字符串还原(解密完成)


再有一个小问题:在加密解密运行时换行符加密解密出错,自定义一个格式替代加密,解密后替代回来就可以啦


下面是本人写的java代码:


import java.io.File;

public class Test1 {
	public static void main(String[] args) {
		// 密码
		String paw = "密码";
		// 内容
		String text = "helloworld 你是我的小啊小苹果,怎么咬你都不嫌多\n换行了 OK了";
		File file = new File("D:\\eclipse\\Test\\src\\Test1.java");//读入文件内容
		System.out.println("***内容:" + text);
		// 换行符 装换失效 用符号替代
		text = text.replaceAll("\n", "&abcs");

		// 16进制文本内容
		StringBuffer textHex = formatHex(text);
		StringBuffer pawHex = formatHex(paw);
		System.out.println("***原始十六进制:" + textHex);
		// 加密后
		String strC = charEncryption(textHex, pawHex);
		System.out.println("***加密:" + strC);

		StringBuffer s = formatHex(strC);
		System.out.println("***加密后的十六进制:" + s.toString());
		System.out
				.println("\n加密\n------------------------------------------------\n解密\n");
		String aText = toStringHex(s.toString());
		System.out.println("***还原加密的内容:" + aText);

		String str = charDecryption(aText, pawHex);
		System.out.println("***还原原始十六进制:" + str);
		// 还原 换行符
		String result = toStringHex(str).replaceAll("&abcs", "\n");
		System.out.println("***解密:" + result);
		// System.out.println(0xff & Integer.parseInt("39", 16));
	}

	/**
	 * 解密数据
	 * 
	 * @param text
	 *            加密的文本
	 * @param pawHex
	 *            密码
	 * @return
	 */
	private static String charDecryption(String text, StringBuffer pawHex) {
		char[] textChars = text.toString().toCharArray();
		char[] pawChars = pawHex.toString().toCharArray();

		for (int i = 0; i < textChars.length; i++) {
			//解密 通过加密的反运算得到原数据
			textChars[i] = (char) (textChars[i] - pawChars[i % pawChars.length] * 2);
		}

		return new String(textChars);
	}

	/**
	 * 
	 * @param textBin
	 *            要加密16进制内容
	 * @param pawBin
	 *            16的密码内容<br>
	 *            16进制文本范围在0-F 不影响加密超出范围损失数据
	 * @return
	 */
	private static String charEncryption(StringBuffer textBin,
			StringBuffer pawBin) {
		char[] textChars = textBin.toString().toCharArray();
		char[] pawChars = pawBin.toString().toCharArray();
		for (int i = 0; i < textChars.length; i++) {
			// 加密就这一行 +号改变Unicode的值 % 作用是使密码内容都用上
			// *2代表Unicode*2 可以自定义 但要保证不要超出 char 类型范围 解密的时候别忘了改一致
			textChars[i] = (char) (textChars[i] + pawChars[i % pawChars.length] * 2);
		}

		return new String(textChars);
	}

	/**
	 * 转为十六进制
	 * 
	 * @param text
	 * @return
	 */
	private static StringBuffer formatHex(String text) {
		StringBuffer sb = new StringBuffer();
		byte[] by = text.getBytes();
		String str;
		for (int i = 0; i < by.length; i++) {
			str = Integer.toHexString(by[i]);
			str = str.toUpperCase();

			while (str.startsWith("F")) {
				str = str.substring(1, str.length());
			}

			sb.append(str);
		}

		return sb;
	}

	public static String toStringHex(String s) {
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(
						s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		try {
			s = new String(baKeyword, "utf-8");// UTF-16le:Not
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}
}


文件加密解密算法(Java源码) java,file,算法,加密解密,java源码 package com.crypto.encrypt; import java.security.SecureRandom; import java.io.*; import javax.crypto.spec.DESKeySpec; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.Cipher; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.NoSuchPaddingException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import java.lang.reflect.Constructor; import java.security.spec.KeySpec; import java.lang.reflect.InvocationTargetException; public class EncryptData { private String keyfile=null; public EncryptData() { } public EncryptData(String keyfile) { this.keyfile=keyfile; } /** * 加密文件 * @param filename String 源路径 * @param filenamekey String 加密后的路径 */ public void createEncryptData(String filename,String filenamekey) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException { //验证keyfile if(keyfile==null || keyfile.equals("")) { throw new NullPointerException("无效的key文件路径"); } encryptData(filename,filenamekey); } /** * 加密类文件 * @param filename String 原始的类文件 * @param encryptfile String 加密后的类文件 * @throws IOException * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws IllegalStateException */ private void encryptData(String filename,String encryptfile) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, IllegalStateException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException { byte data[]=Util.readFile(filename); // 执行加密操作 byte encryptedClassData[] = getencryptData(data); // 保存加密后的文件,覆盖原有的类文件。 Util.writeFile(encryptedClassData,encryptfile); } /** * 直接获得加密数据 * @param bytes byte[] * @throws IllegalStateException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws InstantiationException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws SecurityException * @throws ClassNotFoundException * @throws IOException * @return byte[] */ public byte[] createEncryptData(byte[] bytes) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IOException { bytes=getencryptData(bytes); return bytes; } private byte[] getencryptData(byte[] bytes) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IllegalStateException { // 产生一个可信任的随机数源 SecureRandom sr = new SecureRandom(); //从密钥文件key Filename中得到密钥数据 byte[] rawKeyData = Util.readFile(keyfile); // 从原始密钥数据创建DESKeySpec对象 Class classkeyspec=Class.forName(Util.getValue("keyspec")); Constructor constructor = classkeyspec.getConstructor(new Class[]{byte[].class}); KeySpec dks = (KeySpec) constructor.newInstance(new Object[]{rawKeyData}); // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Util.getAlgorithm()); SecretKey key = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(Util.getAlgorithm()); // 用密钥初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, key, sr); // 执行加密操作 bytes = cipher.doFinal(bytes); // 返回字节数组 return bytes; } /** * 设置key文件路径 * @param keyfile String */ public void setKeyFile(String keyfile) { this.keyfile=keyfile; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值