技术标签: 数据安全 Java 加密解密 base64 md5
数据的安全传输要从以下几方面入手
现代计算机加密技术已经成为一门学科,基于数学理论,很难!这部分可以做了解
import java.util.Base64;
public class SecBase64 {
public static void main(String[] args) throws Exception {
String original = "Hello\u00ff编码测试";
String b64 = Base64.getEncoder().encodeToString(original.getBytes("UTF-8"));
System.out.println(b64);// 如何要转成适合URL传输的文本,需要使用getUrlEncoder()
String ori = new String(Base64.getDecoder().decode(b64), "UTF-8");
System.out.println(ori);
}
}
import java.math.BigInteger;
import java.security.MessageDigest;
public class MD5Salt {
public static byte[] toMD5(byte[] input) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");// SHA-1 SHA-256
} catch (Exception e) {
throw new RuntimeException(e);
}
md.update(input);
return md.digest();
}
public static void main(String[] args) throws Exception {
String passwd = "helloworld";
String salt = "Random salt";
byte[] r = MD5Salt.toMD5((salt + passwd).getBytes("UTF-8"));// 只接受字节类型,需要转化
System.out.println(String.format("%032x", new BigInteger(1, r)));// 转成16进制显示
}
}
import java.security.MessageDigest;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
public class Digest {
public static byte[] digest(String hashAlgorithm, byte[] input) {
MessageDigest md;
try {
md = MessageDigest.getInstance(hashAlgorithm);
} catch (Exception e) {
throw new RuntimeException(e);
}
md.update(input);
return md.digest();
}
public static void main(String[] args) throws Exception {
// 把BouncyCastle作为Provider添加到java.security:
Security.addProvider(new BouncyCastleProvider());// 动态导入jar包到工程,这里注册
String s = "Java摘要算法测试";
byte[] input = s.getBytes("UTF-8");
byte[] r1 = digest("MD5", input);
System.out.println(r1.length + ": " + ByteUtils.toHexString(r1));
byte[] r2 = digest("SHA-1", input);
System.out.println(r2.length + ": " + ByteUtils.toHexString(r2));
byte[] r3 = digest("SHA-256", input);
System.out.println(r3.length + ": " + ByteUtils.toHexString(r3));
byte[] r4 = digest("RipeMD160", input); // JDK没有的算法,有BouncyCastle提供
System.out.println(r4.length + ": " + ByteUtils.toHexString(r4));
}
}
import java.math.BigInteger;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
public class Hmac {
public static byte[] hmac(String hmacAlgorithm, SecretKey skey, byte[] input) throws Exception {
Mac mac = Mac.getInstance(hmacAlgorithm);
mac.init(skey);
mac.update(input);
return mac.doFinal();
}
public static void main(String[] args) throws Exception {
// http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html#Mac
String algorithm = "HmacSHA1";
// 原始数据:
String data = "helloworld";
// 随机生成一个Key:
KeyGenerator keyGen = KeyGenerator.getInstance(algorithm);
SecretKey skey = keyGen.generateKey();
// 打印Key:
byte[] key = skey.getEncoded();
System.out.println(String.format("Key: %0" + (key.length * 2) + "x", new BigInteger(1, key)));
// 用这个Key计算HmacSHA1:
byte[] result = hmac(algorithm, skey, data.getBytes("UTF-8"));
System.out.println(String.format("Hash: %0" + (result.length * 2) + "x", new BigInteger(1, result)));
}
}
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES_CBC_Cipher {
// 指明算法名称/工作模式/填充模式
static final String CIPHER_NAME = "AES/CBC/PKCS5Padding";
// 加密:
public static byte[] encrypt(byte[] key, byte[] input) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance(CIPHER_NAME);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
// CBC模式需要生成一个16 bytes的initialization vector:
SecureRandom sr = SecureRandom.getInstanceStrong();
byte[] iv = sr.generateSeed(16);
IvParameterSpec ivps = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivps);
byte[] data = cipher.doFinal(input);
// IV不需要保密,把IV和密文一起返回:
return join(iv, data);
}
// 解密:
public static byte[] decrypt(byte[] key, byte[] input) throws GeneralSecurityException {
// 把input分割成IV和密文:
byte[] iv = new byte[16];
byte[] data = new byte[input.length - 16];
System.arraycopy(input, 0, iv, 0, 16);
System.arraycopy(input, 16, data, 0, data.length);
// 解密:
Cipher cipher = Cipher.getInstance(CIPHER_NAME);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivps = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivps);
return cipher.doFinal(data);
}
public static byte[] join(byte[] bs1, byte[] bs2) {
byte[] r = new byte[bs1.length + bs2.length];
System.arraycopy(bs1, 0, r, 0, bs1.length);
System.arraycopy(bs2, 0, r, bs1.length, bs2.length);
return r;
}
public static void main(String[] args) throws Exception {
// 原文:
String message = "Hello, world! encrypted using AES!";
System.out.println("Message: " + message);
// 128位密钥 = 16 bytes Key:
byte[] key = "1234567890abcdef".getBytes("UTF-8");
// 加密:
byte[] data = message.getBytes(StandardCharsets.UTF_8);
byte[] encrypted = encrypt(key, data);
System.out.println("Encrypted data: " + Base64.getEncoder().encodeToString(encrypted));
// 解密:
byte[] decrypted = decrypt(key, encrypted);
System.out.println("Decrypted data: " + new String(decrypted, "UTF-8"));
}
}
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
class Person {
public final String name;
public PublicKey publicKey;
private PrivateKey privateKey;
private SecretKey secretKey;
public Person(String name) {
this.name = name;
}
// 生成本地KeyPair:
public void generateKeyPair() {
try {
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DH");// DH算法的KeyPair
kpGen.initialize(512);
KeyPair kp = kpGen.generateKeyPair();
this.privateKey = kp.getPrivate();
this.publicKey = kp.getPublic();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
public void generateSecretKey(byte[] receivedPubKeyBytes) {
try {
// 从byte[]恢复PublicKey:
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(receivedPubKeyBytes);
KeyFactory kf = KeyFactory.getInstance("DH");
PublicKey receivedPublicKey = kf.generatePublic(keySpec);
// 生成本地密钥:
KeyAgreement keyAgreement = KeyAgreement.getInstance("DH");
keyAgreement.init(this.privateKey); // 自己的PrivateKey
keyAgreement.doPhase(receivedPublicKey, true); // 对方的PublicKey
// 生成AES密钥:
this.secretKey = keyAgreement.generateSecret("AES");
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
public void printKeys() {
System.out.printf("Name: %s\n", this.name);
System.out.printf("Private key: %x\n", new BigInteger(1, this.privateKey.getEncoded()));
System.out.printf("Public key: %x\n", new BigInteger(1, this.publicKey.getEncoded()));
System.out.printf("Secret key: %x\n", new BigInteger(1, this.secretKey.getEncoded()));
}
// 发送加密消息:
public String sendMessage(String message) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, this.secretKey);
byte[] data = cipher.doFinal(message.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(data);
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException(e);
}
}
// 接收加密消息并解密:
public String receiveMessage(String message) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, this.secretKey);
byte[] data = cipher.doFinal(Base64.getDecoder().decode(message));
return new String(data, "UTF-8");
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException(e);
}
}
}
public class DH {
public static void main(String[] args) {
// Bob和Alice:
Person bob = new Person("Bob");
Person alice = new Person("Alice");
// 各自生成KeyPair:
bob.generateKeyPair();
alice.generateKeyPair();
// 双方交换各自的PublicKey:
// Bob根据Alice的PublicKey生成自己的本地密钥:
bob.generateSecretKey(alice.publicKey.getEncoded());
// Alice根据Bob的PublicKey生成自己的本地密钥:
alice.generateSecretKey(bob.publicKey.getEncoded());
// 检查双方的本地密钥是否相同:
bob.printKeys();
alice.printKeys();
// 双方的SecretKey相同,后续通信将使用SecretKey作为密钥进行AES加解密:
String msgBobToAlice = bob.sendMessage("Hello, Alice!");
System.out.println("Bob -> Alice: " + msgBobToAlice);
String aliceDecrypted = alice.receiveMessage(msgBobToAlice);
System.out.println("Alice decrypted: " + aliceDecrypted);
}
}
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class SecRSASignature {
PrivateKey sk;
PublicKey pk;
public SecRSASignature() throws GeneralSecurityException {
// 还是要获得密钥对
// generate key pair:
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
kpGen.initialize(1024);
KeyPair kp = kpGen.generateKeyPair();
this.sk = kp.getPrivate();
this.pk = kp.getPublic();
}
public SecRSASignature(byte[] pk, byte[] sk) throws GeneralSecurityException {
// create from bytes:
KeyFactory kf = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pkSpec = new X509EncodedKeySpec(pk);
this.pk = kf.generatePublic(pkSpec);
PKCS8EncodedKeySpec skSpec = new PKCS8EncodedKeySpec(sk);
this.sk = kf.generatePrivate(skSpec);
}
public byte[] getPrivateKey() {
return this.sk.getEncoded();
}
public byte[] getPublicKey() {
return this.pk.getEncoded();
}
public byte[] sign(byte[] message) throws GeneralSecurityException {
// sign by sk:
Signature signature = Signature.getInstance("SHA1withRSA");// MD5withRSA SHA256withRSA
signature.initSign(this.sk);
signature.update(message);
return signature.sign();
}
public boolean verify(byte[] message, byte[] sign) throws GeneralSecurityException {
// verify by pk:
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(this.pk);
signature.update(message);
return signature.verify(sign);
}
public static void main(String[] args) throws Exception {
byte[] message = "Hello,使用SHA1withRSA算法进行数字签名!".getBytes("UTF-8");
SecRSASignature rsas = new SecRSASignature();
byte[] sign = rsas.sign(message);
System.out.println("sign: " + Base64.getEncoder().encodeToString(sign));
boolean verified = rsas.verify(message, sign);
System.out.println("verify: " + verified);
// 用另一个公钥验证:
boolean verified2 = new SecRSASignature().verify(message, sign);
System.out.println("verify with another public key: " + verified2);
// 修改原始信息:
message[0] = 100;
boolean verified3 = rsas.verify(message, sign);
System.out.println("verify changed message: " + verified3);
}
}
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.Base64;
import javax.crypto.Cipher;
public class X509 {
private final PrivateKey privateKey;
public final X509Certificate certificate;
public X509(KeyStore ks, String certName, String password) {
try {
this.privateKey = (PrivateKey) ks.getKey(certName, password.toCharArray());
this.certificate = (X509Certificate) ks.getCertificate(certName);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
public byte[] encrypt(byte[] message) {
try {
Cipher cipher = Cipher.getInstance(this.privateKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, this.privateKey);
return cipher.doFinal(message);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
public byte[] decrypt(byte[] data) {
try {
PublicKey publicKey = this.certificate.getPublicKey();
Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
public byte[] sign(byte[] message) {
try {
Signature signature = Signature.getInstance(this.certificate.getSigAlgName());
signature.initSign(this.privateKey);
signature.update(message);
return signature.sign();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
public boolean verify(byte[] message, byte[] sig) {
try {
Signature signature = Signature.getInstance(this.certificate.getSigAlgName());
signature.initVerify(this.certificate);
signature.update(message);
return signature.verify(sig);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
static KeyStore loadKeyStore(String keyStoreFile, String password) {
try (InputStream input = new BufferedInputStream(new FileInputStream(keyStoreFile))) {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(input, password.toCharArray());
return ks;
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
byte[] message = "Hello,使用X.509证书进行加密和签名!".getBytes("UTF-8");
// 读取KeyStore:
KeyStore ks = loadKeyStore("my.keystore", "456789");// 根据命令行命令生成证书,证书密码
// 读取证书:
X509 x509 = new X509(ks, "mycert", "123456");
// 加密:
byte[] encrypted = x509.encrypt(message);
System.out.println("encrypted: " + Base64.getEncoder().encodeToString(encrypted));
// 解密:
byte[] decrypted = x509.decrypt(encrypted);
System.out.println("decrypted: " + new String(decrypted, "UTF-8"));
// 签名:
byte[] sign = x509.sign(message);
System.out.println("sign: " + Base64.getEncoder().encodeToString(sign));
// 验证签名:
boolean verified = x509.verify(message, sign);
System.out.println("verify: " + verified);
}
}
// 如果要应用于网站,域名需保证一致
keytool -genkeypair -keyalg RSA -keysize 1024 -sigalg SHA1withRSA -validity 36500 -alias mycert -keystore my.keystore -dname "CN=www.sample.com, OU=sample, O=sample, L=BJ, ST=BJ, C=CN" -keypass 123456 -storepass 456789
// 查看证书命令
keytool -list -keystore my.keystore -storepass 456789
安全问题是网络通信的重难点,如果能到研究这一步,算是学有所成了吧!
错误场景介绍做的有一个项目使用JDBC手动创建Connection实现了一个简单的自定义数据库连接池,用来支持Canal解析数据库Binlog指定业务库的插入修改SQL来进行数据库分表备份(按照月份)操作.但是发现当一个一段时间(较长)没有进行数据库操作时,连接都失效了,导致SQL执行失败失效提示为No operations allowed after connection closed查明原因经过搜索发现这个问题是由于Mysql默认一个已创建的长连接28800秒(八小时)内没有任何动作则会断
一.在SwithA和SwithB上配置Smart Link组1.配置SwitchA###Smart Link协议和STP协议互斥,所以要先关闭端口的STP功能。[SwithA]interface gigabitethernet0/0/1[SwithA-GigabitEthernet0/0/1]stp disable[SwithA-GigabitEthernet0/0/1]interface gigabitethernet0/0/2[SwithA-GigabitEthernet0/0/2]s..
链表实现选择排序有两种方法,一种是交换节点内的数据,比较简单。我这里使用的是第二种方法,交换节点。#include<stdio.h>#include<stdlib.h>#include<string.h>#include<math.h>#pragma warning(disable:4996)typedef struct Node {...
(注:不准抄,谁抄谁是居居)1.打开立创商城设计页面;找出需要的原理图和封装(可以先在商城搜索需要地元器件,复制编号就可以直接找到对应的封装);放置在新建的原理图和PCB上并分别导出为对应格式;打开AD新建工程存入原理图和PCB;直接生成库;想要以后方便的话,可以将同类元器件放在一个工程里面然后生成一个类库,删去原来很多的小库就可以很方便地使用了。缺点:如果一...
原文地址:http://blog.163.com/donfang_jianping/blog/static/136473951201410228567115/在http://blog.163.com/donfang_jianping/blog/static/136473951201311111384468/,http://blog.163.com/donfang_jianping/blog
https://github.com/FrDH/jQuery.mmenu https://github.com/kamens/jQuery-menu-aim https://github.com/onokumus/metismenu
Effective C++学习笔记1.让自己习惯使用C++条款01:视c++为一个语言联邦条款02:尽量以const,enum,inline来替换#define功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数...
一、bash命令处理的12个步骤;1、将命令行分成由固定元字符集分隔的记号;SPACE, TAB, NEWLINE, ; , (, ),, |,&记号类型包括单词,关键字,I/O重定向符和分号。2、检测每个命令的第一个记号,查看是否
1、cd webjboss/standalone/configuration 进入该目录2、修改两个文件,如下:修改logging.properties 将最后一句中的HH:mm:ss,SSS 替换为 yyyy-MM-dd HH:mm:ss,SSS。 修改standalone.xml,找到下面一段,同上将HH:mm:ss,SSS 替换为 yyyy-MM-dd HH:mm:...
1.为什么不直接使用pycuda.autoinit?import pycuda.autoinit答:自动初始化很多时候不好使,比如多线程等。2.能正常运行,退出时候报错,什么原因?PyCUDA ERROR: The context stack was not empty upon module cleanup.A context was still active when the context stack was beingcleaned up. At this point in our
从DH算法我们可以看到,公钥-私钥组成的密钥对是非常有用的加密方式,因为公钥是可以公开的,而私钥是完全保密的,由此奠定了非对称加密的基础。非对称加密就是加密和解密使用的不是相同的密钥:只有同一个公钥-私钥对才能正常加解密。因此,如果小明要加密一个文件发送给小红,他应该首先向小红索取她的公钥,然后,他用小红的公钥加密,把加密文件发送给小红,此文件只能由小红的私钥解开,因为小红的私钥在她自己手里,所以...
一、Hive自定义函数类型UDF(User-Defined-Function)函数一对一的关系,输入一个值经过函数以后输出一个值在Hive中继承UDF类,方法名称为evaluate,返回值不能为void,其实就是实现一个方法UDAF(User-Defined Aggregation Function) 聚合函数多对一的关系,输入多个值输出一个值,通常与groupBy联合使用UDTF(User-Defined Table-Generating Functions) 函数一对多的关