java基础/数据加解密(Mooc)
一。消息摘要算法
常用摘要算法:
以下 (HEX)内容:bc指Bouncy Castle | cc指:Apache commons Codec
1。消息摘要算法MD5及MD族(MD2,MD4)
消息摘要算法应用:
MD算法实现:
package com.imooc.security.md; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security; import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider; public class ImoocMD { private static String src = "imooc security md"; public static void main(String[] args) {
jdkMD5();
jdkMD2();
bcMD4();
bcMD5();
ccMD5();
ccMD2();
} public static void jdkMD5() {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5Bytes = md.digest(src.getBytes());
System.out.println("JDK MD5 : " + Hex.encodeHexString(md5Bytes));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
} public static void jdkMD2() {
try {
MessageDigest md = MessageDigest.getInstance("MD2");
byte[] md2Bytes = md.digest(src.getBytes());
System.out.println("JDK MD2 : " + Hex.encodeHexString(md2Bytes));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
} public static void bcMD5() {
Digest digest = new MD5Digest();
digest.update(src.getBytes(), , src.getBytes().length);
byte[] md5Bytes = new byte[digest.getDigestSize()];
digest.doFinal(md5Bytes, );
System.out.println("BC MD5 : " + org.bouncycastle.util.encoders.Hex.toHexString(md5Bytes));
} public static void bcMD4() {
try {
Security.addProvider(new BouncyCastleProvider());
MessageDigest md = MessageDigest.getInstance("MD4");
byte[] md5Bytes = md.digest(src.getBytes());
System.out.println("BC MD4 : " + Hex.encodeHexString(md5Bytes));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
} public static void ccMD5() {
System.out.println("CC MD5 : " + DigestUtils.md5Hex(src.getBytes()));
} public static void ccMD2() {
System.out.println("CC MD2 : " + DigestUtils.md2Hex(src.getBytes()));
} }
2。消息摘要算法SHA(安全散列算法)
SHA算法实现:
package com.imooc.security.sha; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security; import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA224Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider; public class ImoocSHA { private static String src = "imooc security sha"; public static void main(String[] args) {
jdkSHA1();
bcSHA1();
bcSHA224();
ccSHA1();
} public static void jdkSHA1() {
try {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(src.getBytes());
System.out.println("jdk sha-1 : " + Hex.encodeHexString(md.digest()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
} public static void bcSHA1() {
Digest digest = new SHA1Digest();
digest.update(src.getBytes(), , src.getBytes().length);
byte[] sha1Bytes = new byte[digest.getDigestSize()];
digest.doFinal(sha1Bytes, );
System.out.println("bc sha-1 : " + org.bouncycastle.util.encoders.Hex.toHexString(sha1Bytes));
} public static void bcSHA224() {
Digest digest = new SHA224Digest();
digest.update(src.getBytes(), , src.getBytes().length);
byte[] sha224Bytes = new byte[digest.getDigestSize()];
digest.doFinal(sha224Bytes, );
System.out.println("bc sha-224 : " + org.bouncycastle.util.encoders.Hex.toHexString(sha224Bytes));
} public static void bcSHA224_2() {
Security.addProvider(new BouncyCastleProvider());
//...练习内容,^_^
} public static void ccSHA1() {
System.out.println("cc sha1 - 1 :" + DigestUtils.sha1Hex(src.getBytes()));
System.out.println("cc sha1 - 2 :" + DigestUtils.sha1Hex(src));
} //384、256、512。。。。。。 }
SHA算法应用
3。消息摘要算法--MAC
HMAC算法实现:
package com.imooc.security.hmac; import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter; public class ImoocHmac { private static String src = "imooc security hmac"; public static void main(String[] args) {
jdkHmacMD5();
bcHmacMD5();
} public static void jdkHmacMD5() {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");//初始化KeyGenerator
SecretKey secretKey = keyGenerator.generateKey();//产生密钥
// byte[] key = secretKey.getEncoded();//获得密钥
byte[] key = Hex.decodeHex(new char[] {'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'}); SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5");//还原密钥
Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm());//实例化MAC
mac.init(restoreSecretKey);//初始化Mac
byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());//执行摘要
System.out.println("jdk hmacMD5 : " + Hex.encodeHexString(hmacMD5Bytes));
} catch (Exception e) {
e.printStackTrace();
}
} public static void bcHmacMD5() {
HMac hmac = new HMac(new MD5Digest());
hmac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("aaaaaaaaaa")));
hmac.update(src.getBytes(), , src.getBytes().length); byte[] hmacMD5Bytes = new byte[hmac.getMacSize()];//执行摘要
hmac.doFinal(hmacMD5Bytes, ); System.out.println("bc hmacMD5 : " + org.bouncycastle.util.encoders.Hex.toHexString(hmacMD5Bytes)); } }
HMAC算法应用:
二。数字签名
数字签名算法--RSA(经典)
RSA是数字签名的经典算法,包括:MD/SHA两类。
数字签名算法实现--RSA
package com.imooc.security.rsa2; 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.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec; import org.apache.commons.codec.binary.Hex; public class ImoocRSA { private static String src = "imooc security rsa"; public static void main(String[] args) {
jdkRSA();
} public static void jdkRSA() {
try {
//1.初始化密钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize();
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey)keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate(); //2.执行签名
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(privateKey);
signature.update(src.getBytes());
byte[] result = signature.sign();
System.out.println("jdk rsa sign : " + Hex.encodeHexString(result)); //3.验证签名
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
signature = Signature.getInstance("MD5withRSA");
signature.initVerify(publicKey);
signature.update(src.getBytes());
boolean bool = signature.verify(result);
System.out.println("jdk rsa verify : " + bool);
} catch (Exception e) {
e.printStackTrace();
}
} }
数字签名算法RSA应用:
数字签名算法实现--DSA
DSA与RSA区别: DSA仅包含数字签名,使用DSA这种算法的证书无法进行加密通信。 RSA算法既包括加解密,同时也有数字签名算法。
DSA算法实现:
package com.imooc.security.dsa; 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.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec; import org.apache.commons.codec.binary.Hex; public class ImoocDSA { private static String src = "imooc security dsa"; public static void main(String[] args) {
jdkDSA();
} public static void jdkDSA() {
try {
//1.初始化密钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
keyPairGenerator.initialize();
KeyPair keyPair = keyPairGenerator.generateKeyPair();
DSAPublicKey dsaPublicKey = (DSAPublicKey) keyPair.getPublic();
DSAPrivateKey dsaPrivateKey = (DSAPrivateKey)keyPair.getPrivate(); //2.执行签名
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(dsaPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Signature signature = Signature.getInstance("SHA1withDSA");
signature.initSign(privateKey);
signature.update(src.getBytes());
byte[] result = signature.sign();
System.out.println("jdk dsa sign : " + Hex.encodeHexString(result)); //3.验证签名
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(dsaPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("DSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
signature = Signature.getInstance("SHA1withDSA");
signature.initVerify(publicKey);
signature.update(src.getBytes());
boolean bool = signature.verify(result);
System.out.println("jdk dsa verify : " + bool);
} catch (Exception e) {
e.printStackTrace();
}
} }
DSA应用:
数字签名算法实现--ECDSA
package com.imooc.security.ecdsa; import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec; import org.apache.commons.codec.binary.Hex; public class ImoocECDSA { private static String src = "imooc security ecdsa"; public static void main(String[] args) {
jdkECDSA();
} public static void jdkECDSA() {
try {
//1.初始化密钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
keyPairGenerator.initialize();
KeyPair keyPair = keyPairGenerator.generateKeyPair();
ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic();
ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate(); //2.执行签名
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Signature signature = Signature.getInstance("SHA1withECDSA");
signature.initSign(privateKey);
signature.update(src.getBytes());
byte[] result = signature.sign();
System.out.println("jdk ecdsa sign : " + Hex.encodeHexString(result)); //3.验证签名
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("EC");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
signature = Signature.getInstance("SHA1withECDSA");
signature.initVerify(publicKey);
signature.update(src.getBytes());
boolean bool = signature.verify(result);
System.out.println("jdk ecdsa verify : " + bool);
} catch (Exception e) {
e.printStackTrace();
} } }
ECDSA应用:
三。BASE64加密算法
加解密基础与base64算法
1。密码常用术语
注:md5只能加密,不能解密.
2。加解密基础
【1】密码分类
【2】散列函数(单向函数):用来验证数据完整性(而不是用来加解密)
散列函数据相关算法:
【3】数字签名:
【4】OSI与TCP/IP安全体系
【5】Java安全组成、包及第三方扩展
(1)JCA:提供基本的加密框架,如消息摘要、数字签名等。
(2)JCE:JCA基础上扩展,提供加密算法、消息摘要、密钥管理功能。(JDK包中)
(3)JSSE:保证在网络传输的数据定全
(4)JAAS:基于Java平台基于身份验证功能(系统安全/权限)
Java安装目录/security/java.security文件
3。实现base64算法
package com.imooc.security.base64; import java.io.IOException; import org.apache.commons.codec.binary.Base64; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; public class ImoocBase64 { private static String src = "imooc security base64"; public static void main(String[] args) {
jdkBase64();
commonsCodesBase64();
bouncyCastleBase64();
} public static void jdkBase64() {
try {
BASE64Encoder encoder = new BASE64Encoder();
String encode = encoder.encode(src.getBytes());
System.out.println("encode : " + encode); BASE64Decoder decoder = new BASE64Decoder();
System.out.println("decode : " + new String(decoder.decodeBuffer(encode)));
} catch (IOException e) {
e.printStackTrace();
}
} public static void commonsCodesBase64() {
byte[] encodeBytes = Base64.encodeBase64(src.getBytes());
System.out.println("encode : " + new String(encodeBytes)); byte[] decodeBytes = Base64.decodeBase64(encodeBytes);
System.out.println("decode : " + new String(decodeBytes));
} public static void bouncyCastleBase64() {
byte[] encodeBytes = org.bouncycastle.util.encoders.Base64.encode(src.getBytes());
System.out.println("encode : " + new String(encodeBytes)); byte[] decodeBytes = org.bouncycastle.util.encoders.Base64.decode(encodeBytes);
System.out.println("decode : " + new String(decodeBytes));
} }
注:Base64Encoder不建议使用。
Base64算法应用场景
四。对称加密算法
1.Java对称加密算法--DES
package com.imooc.security.des; import java.security.Key;
import java.security.Security; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec; import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider; public class ImoocDES { private static String src = "imooc security des"; public static void main(String[] args) {
jdkDES();
bcDES();
} public static void jdkDES() {
try {
//生成KEY
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init();
SecretKey secretKey = keyGenerator.generateKey();
byte[] bytesKey = secretKey.getEncoded(); //KEY转换
DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
Key convertSecretKey = factory.generateSecret(desKeySpec); //加密
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("jdk des encrypt : " + Hex.encodeHexString(result)); //解密
cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
result = cipher.doFinal(result);
System.out.println("jdk des decrypt : " + new String(result));
} catch (Exception e) {
e.printStackTrace();
}
} public static void bcDES() {
try {
Security.addProvider(new BouncyCastleProvider()); //生成KEY
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES", "BC");
keyGenerator.getProvider();
keyGenerator.init();
SecretKey secretKey = keyGenerator.generateKey();
byte[] bytesKey = secretKey.getEncoded(); //KEY转换
DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
Key convertSecretKey = factory.generateSecret(desKeySpec); //加密
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("bc des encrypt : " + Hex.encodeHexString(result)); //解密
cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
result = cipher.doFinal(result);
System.out.println("bc des decrypt : " + new String(result));
} catch (Exception e) {
e.printStackTrace();
}
} }
对称加密算法应用场景
2.Java对称加密算法--3DES
package com.imooc.security.des; import java.security.Key;
import java.security.SecureRandom; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec; import org.apache.commons.codec.binary.Base64; public class Imooc3DES { private static String src = "imooc security 3des"; public static void main(String[] args) {
jdk3DES();
} public static void jdk3DES() {
try {
//生成KEY
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
// keyGenerator.init(168);
keyGenerator.init(new SecureRandom());//默认长度
SecretKey secretKey = keyGenerator.generateKey();
byte[] bytesKey = secretKey.getEncoded(); //KEY转换
DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
Key convertSecretKey = factory.generateSecret(desKeySpec); //加密
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("jdk 3des encrypt : " + Base64.encodeBase64String(result)); //解密
cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
result = cipher.doFinal(result);
System.out.println("jdk 3des decrypt : " + new String(result));
} catch (Exception e) {
e.printStackTrace();
}
} public static void bc3DES() {
//TODO
} }
3.Java对称加密算法--AES (应用最多(DES替代者))
package com.imooc.security.aes; import java.security.Key; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class ImoocAES { private static String src = "imooc security aes"; public static void main(String[] args) {
jdkAES();
} public static void jdkAES() {
try {
//生成KEY
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init();
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyBytes = secretKey.getEncoded(); //key转换
Key key = new SecretKeySpec(keyBytes, "AES"); //加密
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("jdk aes encrypt : " + Base64.encodeBase64String(result)); //解密
cipher.init(Cipher.DECRYPT_MODE, key);
result = cipher.doFinal(result);
System.out.println("jdk aes desrypt : " + new String(result));
} catch (Exception e) {
e.printStackTrace();
}
} public static void bcAES() {
//TODO
} }
4.Java对称加密算法--PBE
package com.imooc.security.pbe; import java.security.Key;
import java.security.SecureRandom; import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec; import org.apache.commons.codec.binary.Base64; public class ImoocPBE { private static String src = "imooc security pbe"; public static void main(String[] args) {
jdkPBE();
} public static void jdkPBE() {
try {
//初始化盐
SecureRandom random = new SecureRandom();
byte[] salt = random.generateSeed(); //口令与密钥
String password = "imooc";
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWITHMD5andDES");
Key key = factory.generateSecret(pbeKeySpec); //加密
PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, );
Cipher cipher = Cipher.getInstance("PBEWITHMD5andDES");
cipher.init(Cipher.ENCRYPT_MODE, key, pbeParameterSpec);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("jdk pbe encrypt : " + Base64.encodeBase64String(result)); //解密
cipher.init(Cipher.DECRYPT_MODE, key, pbeParameterSpec);
result = cipher.doFinal(result);
System.out.println("jdk pbe decrypt : " + new String(result));
} catch (Exception e) {
e.printStackTrace();
}
} }
五。非对称加密算法
1。DH:密钥交换算法
【1】。KeyFactory
【2】。X509EncodedKeySpec
package com.imooc.security.dh; 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 javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec; import org.apache.commons.codec.binary.Base64; import com.sun.org.apache.xalan.internal.utils.Objects; public class ImoocDH { private static String src = "imooc security dh"; public static void main(String[] args) {
jdkDH();
} public static void jdkDH() {
try {
//1.初始化发送方密钥
KeyPairGenerator senderKeyPairGenerator = KeyPairGenerator.getInstance("DH");
senderKeyPairGenerator.initialize();
KeyPair senderKeyPair = senderKeyPairGenerator.generateKeyPair();
byte[] senderPublicKeyEnc = senderKeyPair.getPublic().getEncoded();//发送方公钥,发送给接收方(网络、文件。。。) //2.初始化接收方密钥
KeyFactory receiverKeyFactory = KeyFactory.getInstance("DH");
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(senderPublicKeyEnc);
PublicKey receiverPublicKey = receiverKeyFactory.generatePublic(x509EncodedKeySpec);
DHParameterSpec dhParameterSpec = ((DHPublicKey)receiverPublicKey).getParams();
KeyPairGenerator receiverKeyPairGenerator = KeyPairGenerator.getInstance("DH");
receiverKeyPairGenerator.initialize(dhParameterSpec);
KeyPair receiverKeypair = receiverKeyPairGenerator.generateKeyPair();
PrivateKey receiverPrivateKey = receiverKeypair.getPrivate();
byte[] receiverPublicKeyEnc = receiverKeypair.getPublic().getEncoded(); //3.密钥构建
KeyAgreement receiverKeyAgreement = KeyAgreement.getInstance("DH");
receiverKeyAgreement.init(receiverPrivateKey);
receiverKeyAgreement.doPhase(receiverPublicKey, true);
SecretKey receiverDesKey = receiverKeyAgreement.generateSecret("DES"); KeyFactory senderKeyFactory = KeyFactory.getInstance("DH");
x509EncodedKeySpec = new X509EncodedKeySpec(receiverPublicKeyEnc);
PublicKey senderPublicKey = senderKeyFactory.generatePublic(x509EncodedKeySpec);
KeyAgreement senderKeyAgreement = KeyAgreement.getInstance("DH");
senderKeyAgreement.init(senderKeyPair.getPrivate());
senderKeyAgreement.doPhase(senderPublicKey, true);
SecretKey senderDesKey = senderKeyAgreement.generateSecret("DES");
if (Objects.equals(receiverDesKey, senderDesKey)) {
System.out.println("双方密钥相同");
} //4.加密
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, senderDesKey);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("jdk dh encrypt : " + Base64.encodeBase64String(result)); //5.解密
cipher.init(Cipher.DECRYPT_MODE, receiverDesKey);
result = cipher.doFinal(result);
System.out.println("jdk dh decrypt : " + new String(result));
} catch (Exception e) {
e.printStackTrace();
}
} }
2。非对称加密算法--RSA算法(广泛应用)
package com.imooc.security.rsa; import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import org.apache.commons.codec.binary.Base64; public class ImoocRSA { private static String src = "imooc security rsa"; public static void main(String[] args) {
jdkRSA();
} public static void jdkRSA() {
try {
//1.初始化密钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize();
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey)keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate();
System.out.println("Public Key : " + Base64.encodeBase64String(rsaPublicKey.getEncoded()));
System.out.println("Private Key : " + Base64.encodeBase64String(rsaPrivateKey.getEncoded())); //2.私钥加密、公钥解密——加密
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("私钥加密、公钥解密——加密 : " + Base64.encodeBase64String(result)); //3.私钥加密、公钥解密——解密
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
result = cipher.doFinal(result);
System.out.println("私钥加密、公钥解密——解密:" + new String(result)); //4.公钥加密、私钥解密——加密
x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
keyFactory = KeyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
result = cipher.doFinal(src.getBytes());
System.out.println("公钥加密、私钥解密——加密 : " + Base64.encodeBase64String(result)); //5.公钥加密、私钥解密——解密
pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
keyFactory = KeyFactory.getInstance("RSA");
privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
result = cipher.doFinal(result);
System.out.println("公钥加密、私钥解密——解密:" + new String(result));
} catch (Exception e) {
e.printStackTrace();
}
} }
3。非对称加密算法--EIGamal
总结:《区块链核心技术与应用》--数据加密算法
数据加密算法主要分为两大类:
(一)。对称加密算法
对称加密算法主要用于对区块链的交易和区块链进行加密。
加密钥匙和解密钥匙为同一把。(数字指纹:哈希计算的值)
说明:
为保证交易信息或区块信息内容完整性,需要:
将传递的交易信息或区块信息通过HASH计算得到一串哈希码h,
并将哈希码h和传递的交易信息或区块信息的密文一起发送给对方。
对方接收到信息并解密后,重新对解密后的明文进行哈希计算得到一个新的哈希码h`,
然后对h 和 h`进行比较.若h=h`,则说明信息在传递过程中没有被篡改。
(二)。非对称加密算法
1.公钥加密,私钥解密。--数字信封
目的:安全传递密钥
说明:
为了实现交易信息或者区块信息的密钥安全传输保障,需要将对称加密所用的对称加密密钥K通过使用
接收者的公钥进行加密,形成数字信封。该数字信封通过网络传递到接收方。
接收方使用自己的私钥对该数字信封进行解密,从而得到解密所需的对称解密密钥K。因为在解密过程中,
只有接收者自己的私钥能够解开该数字信封,任何其他人的钥匙都不能解开该信封,所以数字信封可以保证整个密钥的传递安全性。
2.私钥加密,公钥解密。--数字签名
目的:用于作为签名使用,防止各种抵赖
数字签名主要目标:用来确认信息发送者认可自己曾经的行为(自己所签署)。
说明:
为了实现交易信息或者区块信息的来源可靠性保障,需要将:
传递的交易信息或者区块信息通过哈希计算得到相应的数字摘要,
然后使用发送者的私钥进行加密,得到相应的数字签名,并将数字签名通过网络传递到接收方。
如果接收方使用发送方的公钥能够解开该数字签名,则证明该数字签名的确为该发送者所签署,来源可靠;
如果接收方使用发送者的公钥不能解开该数字签名,则证明该数字签名不是该发送者所签署,来源不可靠。
java基础/数据加解密(Mooc)的更多相关文章
- java安全与加解密
1 安全 安全性相关内容分为认证.授权和审计(发现安全问题时可以查看相关历史记录) 用户认证 java API表示主体的是javax.security.auth.Subject类型,表示用户身份标识的 ...
- 【转】 Java 进行 RSA 加解密时不得不考虑到的那些事儿
[转] Java 进行 RSA 加解密时不得不考虑到的那些事儿 1. 加密的系统不要具备解密的功能,否则 RSA 可能不太合适 公钥加密,私钥解密.加密的系统和解密的系统分开部署,加密的系统不应该同时 ...
- shiro框架学习-6-Shiro内置的Filter过滤器及数据加解密
1. shiro的核心过滤器定义在枚举类DefaultFilter 中,一共有11个 ,配置哪个路径对应哪个拦截器进行处理 // // Source code recreated from a .c ...
- ASP.NET Core 6框架揭秘实例演示[19]:数据加解密与哈希
数据保护(Data Protection)框架旨在解决数据在传输与持久化存储过程中的一致性(Integrity)和机密性(confidentiality)问题,前者用于检验接收到的数据是否经过篡改,后 ...
- 一个java的DES加解密类转换成C#
原文:一个java的DES加解密类转换成C# 一个java的des加密解密代码如下: //package com.visionsky.util; import java.security.*; //i ...
- T-SQL问题解决集锦——数据加解密(2)
原文:T-SQL问题解决集锦--数据加解密(2) 问题三.如何让指定用户可以对数据表进行Truncate操作? Truncate在对大表全删除操作时,会明显比Delete语句更快更有效,但是因为它不需 ...
- T-SQL问题解决集锦——数据加解密
原文:T-SQL问题解决集锦--数据加解密 以下代码已经在SQLServer2008上的示例数据库测试通过 问题一:如何为数据进行加密与解密,避免使用者窃取机密数据? 对于一些敏感数据,如密码.卡号, ...
- odoo基础数据加载
odoo 基础数据加载 这里介绍的odoo基础数据加载分两种方式,一种是演示数据加载,一种是默认数据加载,下面就是详细介绍 首先,当然是创建一个date文件夹 项目目录,右键自定义一个文件夹 XML数 ...
- Java 进行 RSA 加解密时不得不考虑到的那些事儿
1. 加密的系统不要具备解密的功能,否则 RSA 可能不太合适 公钥加密,私钥解密.加密的系统和解密的系统分开部署,加密的系统不应该同时具备解密的功能,这样即使黑客攻破了加密系统,他拿到的也只是一堆无 ...
随机推荐
- Tronado【第2篇】:tronado自定义Form组件
Tronado自定义Form组件 一.获取类里面的静态属性以及动态属性的方法 方式一: # ===========方式一================ class Foo(object): user ...
- 关于 html button 点击刷新页面的问题
如果不想点击button 刷新页面的话,需要加个属性 type="button" 如下: <button class="layui-btn" type ...
- centos6.5下修改系统的roo用户/非root用户的密码
1.修改系统root用户的密码 [........~]# passwd然后输入新密码,若提示密码太简单,无需理会,直接敲回车: 然后再次输入新密码,即可修改成功. 2.修改系统非root用户的密码:e ...
- SpringBoot框架(3)--条件装配
场景:需要根据系统的编码格式有选择装配类. 分析:最直接的实现方式,定义各种编码格式对应的处理类,可以通过System.getProperty("file.encoding")获得 ...
- webpack-第一个demo
1.webpack概念 webpack是前端的一个项目构建工具,它是基于node.js开发出来的一个前端工具:借助webpack这个前端自动化构建工具,可以完美实现资源的合并.打包.压缩.混淆等诸多功 ...
- java大文件上传
上次遇到这样一个问题,客户上传高清视频(1G以上)的时候上传失败. 一开始以为是session过期或者文件大小受系统限制,导致的错误.查看了系统的配置文件没有看到文件大小限制,web.xml中sees ...
- 【canvas学习笔记八】像素操作
ImageData对象 ImageData对象包含了一个区域内的canvas的像素信息.它包含以下可读属性: width canvas的宽度,单位是像素. height canvas的高度,单位是像素 ...
- jQuery_完成表格的隔行换色
表格的颜色一样不利于区分,而利用jQuery则可以很方便的进行表格的隔行换色操作,原表如下: 这样看着很不方便,但是隔行换色之后非常便捷清楚. 代码如下: <!DOCTYPE html> ...
- Java的格式化输出
在java中除了有System.out.println();和System.out.print();之外还有一种格式化的输出,用来限制宽度,保留小数点后的位数,还有对齐方式. 代码: package ...
- 利用word宏功能一键导出数据库表结构
前言: 需求是: 为了完成<数据库设计文档>中的表结构展示,需要导出所有的表结构,包括字段名.长度.注释等必要标题. 数据库:MySQL 我选择的方法是——用word的宏功能导出.很多博客 ...