RSA
java
依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
RSACoder
package com.zzhua.rsa2;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public class RSACoder {
public static final String KEY_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";
public static byte[] decryptBASE64(String key) {
return Base64.decodeBase64(key);
}
public static String encryptBASE64(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = decryptBASE64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data);
return encryptBASE64(signature.sign());
}
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = decryptBASE64(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);
return signature.verify(decryptBASE64(sign));
}
public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception{
byte[] keyBytes = decryptBASE64(key);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
public static byte[] decryptByPrivateKey(String data, String key)
throws Exception {
return decryptByPrivateKey(decryptBASE64(data),key);
}
public static byte[] decryptByPublicKey(byte[] data, String key)
throws Exception {
byte[] keyBytes = decryptBASE64(key);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
public static byte[] encryptByPublicKey(String data, String key)
throws Exception {
byte[] keyBytes = decryptBASE64(key);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data.getBytes());
}
public static byte[] encryptByPrivateKey(byte[] data, String key)
throws Exception {
byte[] keyBytes = decryptBASE64(key);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
public static String getPrivateKey(Map<String, Key> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return encryptBASE64(key.getEncoded());
}
public static String getPublicKey(Map<String, Key> keyMap)
throws Exception {
Key key = keyMap.get(PUBLIC_KEY);
return encryptBASE64(key.getEncoded());
}
public static Map<String, Key> initKey() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
Map<String, Key> keyMap = new HashMap(2);
keyMap.put(PUBLIC_KEY, keyPair.getPublic());
keyMap.put(PRIVATE_KEY, keyPair.getPrivate());
return keyMap;
}
}
RSACoderTest
package com.zzhua.rsa2;
import org.junit.Before;
import org.junit.Test;
import java.security.Key;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class RSACoderTest {
private String publicKey;
private String privateKey;
@Before
public void setUp() throws Exception {
Map<String, Key> keyMap = RSACoder.initKey();
publicKey = RSACoder.getPublicKey(keyMap);
privateKey = RSACoder.getPrivateKey(keyMap);
System.err.println("公钥: \n\r" + publicKey);
System.err.println("私钥: \n\r" + privateKey);
}
@Test
public void test() throws Exception {
System.err.println("公钥加密——私钥解密");
String inputStr = "abc";
byte[] encodedData = RSACoder.encryptByPublicKey(inputStr, publicKey);
byte[] decodedData = RSACoder.decryptByPrivateKey(encodedData,privateKey);
String outputStr = new String(decodedData);
System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);
assertEquals(inputStr, outputStr);
}
@Test
public void testSign() throws Exception {
System.err.println("私钥加密——公钥解密");
String inputStr = "sign";
byte[] data = inputStr.getBytes();
byte[] encodedData = RSACoder.encryptByPrivateKey(data, privateKey);
byte[] decodedData = RSACoder.decryptByPublicKey(encodedData, publicKey);
String outputStr = new String(decodedData);
System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);
assertEquals(inputStr, outputStr);
System.err.println("私钥签名——公钥验证签名");
String sign = RSACoder.sign(encodedData, privateKey);
System.err.println("签名:" + sign);
boolean status = RSACoder.verify(encodedData, publicKey, sign);
System.err.println("状态:" + status);
assertTrue(status);
}
}
js示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用jsencrypt执行OpenSSL的RSA加密,解密</title>
</head>
<!--引入jsencrypt.js-->
<script src="https://cdn.bootcss.com/jsencrypt/3.0.0-beta.1/jsencrypt.js"></script>
<script type="text/javascript">
var PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLVWtmmXadwWbKAuvXWLzCY3A844s6eJ1I19JTEmMrbmaQP4hC6/4ks6Ix+BJPF/ikpVDie6gBg4qsSbrBjckA8AvflYU0ixw0rEzd+tv2o0d+afZEJdIW2SL/+78FUuGdu7ChYeUX9DLEM8dScIdWYoVREey0ei+H9dIQcLyiswIDAQAB';
var PRIVATE_KEY = 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAItVa2aZdp3BZsoC69dYvMJjcDzjizp4nUjX0lMSYytuZpA/iELr/iSzojH4Ek8X+KSlUOJ7qAGDiqxJusGNyQDwC9+VhTSLHDSsTN362/ajR35p9kQl0hbZIv/7vwVS4Z27sKFh5Rf0MsQzx1Jwh1ZihVER7LR6L4f10hBwvKKzAgMBAAECgYAPXWURlFzDOr+WCUpuned63DJVVJZW5VQa40nbRUzQTkVbJNZm4tVMwM5jCkMim7ccmOpZf19gg1v4ccz5aSRAHpZ4ZwbUI4D1eHUygXeiWkGsY4oPfRiMRB/Rv3Fsd4HlaMt4Cxkg0cxvg4FwknoPGHsUBDBWXntiQhtuO9BtOQJBAOp9TuFi2B+vo6YU4YtLfk27C6tORknV0sDicbkvp+NQCez0bU4oaHiooz5uIt/YL1ofbdb03AFJcfR0a2JkCi0CQQCYHX8Lp9P1o9y+SXNlrSs5CExx/Ev1/AFVov/+OThZxVU5/93WjlHvC0TX/A6Ey5Oep6934fhS3Q/3URfRJcxfAkA2J/qv00RXDRmeofP1V9oz2Z84UTuqkde69JGPU5JSzYl9UHZuNqbqNwh8wrMLP8Kv7dJQcvzczzmiW8DxWGmBAkBWx50O/TPC0zS/qg+XVe9unflendyH/LiWLmN0mRg4vocci4f3O0Iq6Xbg8P8nayxQOsGz1spgG5VcNnsr6jBpAkEA5VwKRVtRxr5ibHZEHL6vHyhvnaXQaTNOjZiAdjt5iG67PX93+nvHHhmwOrvGrsQizznbe+HwrEWPIdI0jYQSvw==';
var encrypt = new JSEncrypt();
encrypt.setPublicKey(PUBLIC_KEY);
console.log(encrypt.encrypt('device002'))
</script>
</html>
DES
示例一
js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/core.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/cipher-core.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/mode-ecb.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/tripledes.min.js"></script>
</head>
<body>
</body>
<script>
var key = '1qaz@WSX';
function encryptByDES(message) {
var keyHex = CryptoJS.enc.Utf8.parse(key);
var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.ciphertext.toString();
}
console.log(encryptByDES("device001"))
</script>
</html>
java
package com.zzhua.des;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Locale;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class DESUtils {
private static final String DES_ALGORITHM = "DES";
public static String decryption(String secretData, String secretKey) throws Exception {
Cipher cipher = null;
try {
cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, generateKey(secretKey));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new Exception("NoSuchAlgorithmException", e);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
throw new Exception("NoSuchPaddingException", e);
} catch (Exception e) {
e.printStackTrace();
}
try {
byte[] buf = cipher.doFinal(hexStr2Bytes(secretData));
int num = 0;
for (byte b: buf) {
String name = b+"";
if (name.length() == 1) {
num++;
}
}
byte[] bytes = new byte[buf.length-num];
for (int i =0; i < buf.length; i++) {
String name = buf[i]+"";
if (name.length() != 1) {
bytes[i] = buf[i];
}
}
return new String(bytes, "utf-8");
} catch (Exception e) {
e.printStackTrace();
throw new Exception("IllegalBlockSizeException", e);
}
}
public static byte[] hexStr2Bytes(String src) {
src = src.trim().replace(" ", "").toUpperCase(Locale.US);
int m = 0, n = 0;
int iLen = src.length() / 2;
byte[] ret = new byte[iLen];
for (int i = 0; i < iLen; i++) {
m = i * 2 + 1;
n = m + 1;
ret[i] = (byte) (Integer.decode("0X" + src.substring(i * 2, m) + src.substring(m, n)) & 0xFF);
}
return ret;
}
private static SecretKey generateKey(String secretKey)
throws Exception {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes());
keyFactory.generateSecret(keySpec);
return keyFactory.generateSecret(keySpec);
}
}
示例2
参照:https://www.jianshu.com/p/24691c8d722c
js
var CryptoJS = require("crypto-js");
const secretKey = "q9rx*a.SjzH";
var afterEncrypt = CryptoJS.DES.encrypt(
"device_001",
CryptoJS.enc.Utf8.parse(secretKey),
{
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}
).toString();
console.log(afterEncrypt);
var afterDecrypt = CryptoJS.DES.decrypt(
afterEncrypt,
CryptoJS.enc.Utf8.parse(secretKey),
{
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}
).toString(CryptoJS.enc.Utf8);
console.log(afterDecrypt);
},
java
package com.zzhua.des2;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
public class DesCipherUtil {
private DesCipherUtil() {
throw new AssertionError("No DesCipherUtil instances for you!");
}
static {
Security.addProvider(new BouncyCastleProvider());
}
public static String encrypt(String encryptText, String key) {
if (encryptText == null || key == null) {
throw new IllegalArgumentException("encryptText or key must not be null");
}
try {
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(encryptText.getBytes(Charset.forName("UTF-8")));
return Base64.getEncoder().encodeToString(bytes);
} catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | NoSuchPaddingException
| BadPaddingException | NoSuchProviderException | IllegalBlockSizeException e) {
throw new RuntimeException("encrypt failed", e);
}
}
public static String decrypt(String decryptText, String key) {
if (decryptText == null || key == null) {
throw new IllegalArgumentException("decryptText or key must not be null");
}
try {
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(decryptText));
return new String(bytes, Charset.forName("UTF-8"));
} catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | NoSuchPaddingException
| BadPaddingException | NoSuchProviderException | IllegalBlockSizeException e) {
throw new RuntimeException("decrypt failed", e);
}
}
public static void main(String[] args) {
String fromWeb = "7aokwkzN+gxMdyOFAUEBVg==";
String key = "q9rx*a.SjzH";
String afterDecrypt = DesCipherUtil.decrypt(fromWeb, key);
System.out.println(afterDecrypt);
System.out.println(DesCipherUtil.encrypt("device_001", key));
}
}
|