区块链使用的加密和解密技术(JAVA版)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了区块链使用的加密和解密技术(JAVA版)相关的知识,希望对你有一定的参考价值。

加密和解密是区块链数据传输中不可缺少的技术点,现代密码学包括对称性加密和非对称性加密两个概念,区块链系统里面一般常用到的是非对称加密。这里把相关知识记录一下。

(一)对称加密(Symmetric Cryptography)

对称加密是最快速、最简单的一种加密方式,加密(encryption)与解密(decryption)用的是同样的密钥(secret key)。对称加密有很多种算法,由于它效率很高,所以被广泛使用在很多加密协议的核心当中。

对称加密通常使用的是相对较小的密钥,一般小于256 bit。因为密钥越大,加密越强,但加密与解密的过程越慢。如果你只用1 bit来做这个密钥,那们可以先试着用0来解密,不行的话就再用1解;但如果你的密钥有1 MB大,们可能永远也无法破解,但加密和解密的过程要花费很长的时间。密钥的大小既要照顾到安全性,也要照顾到效率,是一个trade-off。

所谓对称加密算法即:加密和解密使用相同密钥的算法。常见的有DES、3DES、AES、PBE等加密算法,这几种算法安全性依次是逐渐增强的。

DES加密

DES是一种对称加密算法,是一种非常简便的加密算法,但是密钥长度比较短。DES加密算法出自IBM的研究,后来被美国政府正式采用,之后开始广泛流传,但是近些年使用越来越少,因为DES使用56位密钥,以现代计算能力,24小时内即可被破解。

虽然如此,在某些简单应用中,我们还是可以使用DES加密算法.

简单的DES加密算法JAVA实现:

public class DESUtil {

private static final String KEY_ALGORITHM = "DES";
private static final String DEFAULT_CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";//默认的加密算法

/**
 * DES 加密操作
 *
 * @param content 待加密内容
 * @param key 加密密钥
 * @return 返回Base64转码后的加密数据
 */
public static String encrypt(String content, String key) {
    try {
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器

        byte[] byteContent = content.getBytes("utf-8");

        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));// 初始化为加密模式的密码器

        byte[] result = cipher.doFinal(byteContent);// 加密

        return Base64.encodeBase64String(result);//通过Base64转码返回
    } catch (Exception ex) {
        Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

/**
 * DES 解密操作
 *
 * @param content
 * @param key
 * @return
 */
public static String decrypt(String content, String key) {

    try {
        //实例化
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

        //使用密钥初始化,设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));

        //执行操作
        byte[] result = cipher.doFinal(Base64.decodeBase64(content));

        return new String(result, "utf-8");
    } catch (Exception ex) {
        Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

/**
 * 生成加密秘钥
 *
 * @return
 */
private static SecretKeySpec getSecretKey(final String key) {
    //返回生成指定算法密钥生成器的 KeyGenerator 对象
    KeyGenerator kg = null;

    try {
        kg = KeyGenerator.getInstance(KEY_ALGORITHM);

        //DES 要求密钥长度为 56
        kg.init(56, new SecureRandom(key.getBytes()));

        //生成一个密钥
        SecretKey secretKey = kg.generateKey();

        return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为DES专用密钥
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

public static void main(String[] args) {
    String content = "hello,您好";
    String key = "[email protected]*^hsff%dfs$r344&df8543*er";
    System.out.println("content:" + content);
    String s1 = DESUtil.encrypt(content, key);
    System.out.println("s1:" + s1);
    System.out.println("s2:"+ DESUtil.decrypt(s1, key));

}

}

3DES加密

3DES是一种对称加密算法,在 DES 的基础上,使用三重数据加密算法,对数据进行加密,它相当于是对每个数据块应用三次 DES 加密算法。由于计算机运算能力的增强,原版 DES 密码的密钥长度变得容易被暴力破解;3DES 即是设计用来提供一种相对简单的方法,即通过增加 DES 的密钥长度来避免类似的***,而不是设计一种全新的块密码算法这样来说,破解的概率就小了很多。缺点由于使用了三重数据加密算法,可能会比较耗性能。简单的3DES加密算法实现:
(略)

(二)非对称加密

非对称加密算法需要两个密钥:公开密钥(publickey)和私有密钥(privatekey)。公开密钥与私有密钥是一对,如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密;如果用私有密钥对数据进行加密,那么只有用对应的公开密钥才能解密。一般公钥是公开的,私钥是自己保存。因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。安全性相对对称加密来说更高,是一种高级加密方式。

RSA加密

RSA是一种非对称加密算法.RSA有两个密钥,一个是公开的,称为公开密钥;一个是私密的,称为私密密钥。公开密钥是对大众公开的,私密密钥是服务器私有的,两者不能互推得出。用公开密钥对数据进行加密,私密密钥可解密;私密密钥对数据加密,公开密钥可解密。速度较对称加密慢。

简单的RSA加密算法JAVA实现:

/**

  • <p>
  • RSA公钥/私钥/签名工具包
  • </p>
  • <p>
  • 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
  • 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
  • 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的效率和安全
  • </p>
  • */
    public class RSAUtils {

    /**

    • 加密算法RSA
      */
      public static final String KEY_ALGORITHM = "RSA";

    /**

    • 签名算法
      */
      public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**

    • 获取公钥的key
      */
      private static final String PUBLIC_KEY = "RSAPublicKey";

    /**

    • 获取私钥的key
      */
      private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**

    • RSA最大加密明文大小
      */
      private static final int MAX_ENCRYPT_BLOCK = 117;

    /**

    • RSA最大解密密文大小
      */
      private static final int MAX_DECRYPT_BLOCK = 128;

    /**

    • <p>
    • 生成密钥对(公钥和私钥)
    • </p>
    • @return
    • @throws Exception
      */
      public static Map<String, Object> genKeyPair() throws Exception {
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
      keyPairGen.initialize(1024);
      KeyPair keyPair = keyPairGen.generateKeyPair();
      RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
      RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
      Map<String, Object> keyMap = new HashMap<String, Object>(2);
      keyMap.put(PUBLIC_KEY, publicKey);
      keyMap.put(PRIVATE_KEY, privateKey);
      return keyMap;
      }

    /**

    • <p>
    • 用私钥对信息生成数字签名
    • </p>
    • @param data 已加密数据
    • @param privateKey 私钥(BASE64编码)
    • @return
    • @throws Exception
      */
      public static String sign(byte[] data, String privateKey) throws Exception {
      byte[] keyBytes = Base64Utils.decode(privateKey);
      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
      Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
      signature.initSign(privateK);
      signature.update(data);
      return Base64Utils.encode(signature.sign());
      }

    /**

    • <p>
    • 校验数字签名
    • </p>
    • @param data 已加密数据
    • @param publicKey 公钥(BASE64编码)
    • @param sign 数字签名
    • @return
    • @throws Exception
    • */
      public static boolean verify(byte[] data, String publicKey, String sign)
      throws Exception {
      byte[] keyBytes = Base64Utils.decode(publicKey);
      X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      PublicKey publicK = keyFactory.generatePublic(keySpec);
      Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
      signature.initVerify(publicK);
      signature.update(data);
      return signature.verify(Base64Utils.decode(sign));
      }

    /**

    • <P>
    • 私钥解密
    • </p>
    • @param encryptedData 已加密数据
    • @param privateKey 私钥(BASE64编码)
    • @return
    • @throws Exception
      /
      public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
      throws Exception {
      byte[] keyBytes = Base64Utils.decode(privateKey);
      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.DECRYPT_MODE, privateK);
      int inputLen = encryptedData.length;
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int offSet = 0;
      byte[] cache;
      int i = 0;
      // 对数据分段解密
      while (inputLen - offSet > 0) {
      if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
      cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
      } else {
      cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
      }
      out.write(cache, 0, cache.length);
      i++;
      offSet = i
      MAX_DECRYPT_BLOCK;
      }
      byte[] decryptedData = out.toByteArray();
      out.close();
      return decryptedData;
      }

    /**

    • <p>
    • 公钥解密
    • </p>
    • @param encryptedData 已加密数据
    • @param publicKey 公钥(BASE64编码)
    • @return
    • @throws Exception
      /
      public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
      throws Exception {
      byte[] keyBytes = Base64Utils.decode(publicKey);
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      Key publicK = keyFactory.generatePublic(x509KeySpec);
      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.DECRYPT_MODE, publicK);
      int inputLen = encryptedData.length;
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int offSet = 0;
      byte[] cache;
      int i = 0;
      // 对数据分段解密
      while (inputLen - offSet > 0) {
      if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
      cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
      } else {
      cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
      }
      out.write(cache, 0, cache.length);
      i++;
      offSet = i
      MAX_DECRYPT_BLOCK;
      }
      byte[] decryptedData = out.toByteArray();
      out.close();
      return decryptedData;
      }

    /**

    • <p>
    • 公钥加密
    • </p>
    • @param data 源数据
    • @param publicKey 公钥(BASE64编码)
    • @return
    • @throws Exception
      /
      public static byte[] encryptByPublicKey(byte[] data, String publicKey)
      throws Exception {
      byte[] keyBytes = Base64Utils.decode(publicKey);
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      Key publicK = keyFactory.generatePublic(x509KeySpec);
      // 对数据加密
      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, publicK);
      int inputLen = data.length;
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int offSet = 0;
      byte[] cache;
      int i = 0;
      // 对数据分段加密
      while (inputLen - offSet > 0) {
      if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
      cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
      } else {
      cache = cipher.doFinal(data, offSet, inputLen - offSet);
      }
      out.write(cache, 0, cache.length);
      i++;
      offSet = i
      MAX_ENCRYPT_BLOCK;
      }
      byte[] encryptedData = out.toByteArray();
      out.close();
      return encryptedData;
      }

    /**

    • <p>
    • 私钥加密
    • </p>
    • @param data 源数据
    • @param privateKey 私钥(BASE64编码)
    • @return
    • @throws Exception
      /
      public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
      throws Exception {
      byte[] keyBytes = Base64Utils.decode(privateKey);
      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, privateK);
      int inputLen = data.length;
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int offSet = 0;
      byte[] cache;
      int i = 0;
      // 对数据分段加密
      while (inputLen - offSet > 0) {
      if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
      cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
      } else {
      cache = cipher.doFinal(data, offSet, inputLen - offSet);
      }
      out.write(cache, 0, cache.length);
      i++;
      offSet = i
      MAX_ENCRYPT_BLOCK;
      }
      byte[] encryptedData = out.toByteArray();
      out.close();
      return encryptedData;
      }

    /**

    • <p>
    • 获取私钥
    • </p>
    • @param keyMap 密钥对
    • @return
    • @throws Exception
      */
      public static String getPrivateKey(Map<String, Object> keyMap)
      throws Exception {
      Key key = (Key) keyMap.get(PRIVATE_KEY);
      return Base64Utils.encode(key.getEncoded());
      }

    /**

    • <p>
    • 获取公钥
    • </p>
    • @param keyMap 密钥对
    • @return
    • @throws Exception
      */
      public static String getPublicKey(Map<String, Object> keyMap)
      throws Exception {
      Key key = (Key) keyMap.get(PUBLIC_KEY);
      return Base64Utils.encode(key.getEncoded());
      }

}

/**

  • <p>
  • RSA公钥/私钥/签名工具包
  • </p>
  • <p>
  • 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
  • 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
  • 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
  • </p>
  • */
    public class RSAUtils {

    /**

    • 加密算法RSA
      */
      public static final String KEY_ALGORITHM = "RSA";

    /**

    • 签名算法
      */
      public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**

    • 获取公钥的key
      */
      private static final String PUBLIC_KEY = "RSAPublicKey";

    /**

    • 获取私钥的key
      */
      private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**

    • RSA最大加密明文大小
      */
      private static final int MAX_ENCRYPT_BLOCK = 117;

    /**

    • RSA最大解密密文大小
      */
      private static final int MAX_DECRYPT_BLOCK = 128;

    /**

    • <p>
    • 生成密钥对(公钥和私钥)
    • </p>
    • @return
    • @throws Exception
      */
      public static Map<String, Object> genKeyPair() throws Exception {
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
      keyPairGen.initialize(1024);
      KeyPair keyPair = keyPairGen.generateKeyPair();
      RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
      RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
      Map<String, Object> keyMap = new HashMap<String, Object>(2);
      keyMap.put(PUBLIC_KEY, publicKey);
      keyMap.put(PRIVATE_KEY, privateKey);
      return keyMap;
      }

    /**

    • <p>
    • 用私钥对信息生成数字签名
    • </p>
    • @param data 已加密数据
    • @param privateKey 私钥(BASE64编码)
    • @return
    • @throws Exception
      */
      public static String sign(byte[] data, String privateKey) throws Exception {
      byte[] keyBytes = Base64Utils.decode(privateKey);
      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
      Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
      signature.initSign(privateK);
      signature.update(data);
      return Base64Utils.encode(signature.sign());
      }

    /**

    • <p>
    • 校验数字签名
    • </p>
    • @param data 已加密数据
    • @param publicKey 公钥(BASE64编码)
    • @param sign 数字签名
    • @return
    • @throws Exception
    • */
      public static boolean verify(byte[] data, String publicKey, String sign)
      throws Exception {
      byte[] keyBytes = Base64Utils.decode(publicKey);
      X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      PublicKey publicK = keyFactory.generatePublic(keySpec);
      Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
      signature.initVerify(publicK);
      signature.update(data);
      return signature.verify(Base64Utils.decode(sign));
      }

    /**

    • <P>
    • 私钥解密
    • </p>
    • @param encryptedData 已加密数据
    • @param privateKey 私钥(BASE64编码)
    • @return
    • @throws Exception
      /
      public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
      throws Exception {
      byte[] keyBytes = Base64Utils.decode(privateKey);
      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.DECRYPT_MODE, privateK);
      int inputLen = encryptedData.length;
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int offSet = 0;
      byte[] cache;
      int i = 0;
      // 对数据分段解密
      while (inputLen - offSet > 0) {
      if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
      cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
      } else {
      cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
      }
      out.write(cache, 0, cache.length);
      i++;
      offSet = i
      MAX_DECRYPT_BLOCK;
      }
      byte[] decryptedData = out.toByteArray();
      out.close();
      return decryptedData;
      }

    /**

    • <p>
    • 公钥解密
    • </p>
    • @param encryptedData 已加密数据
    • @param publicKey 公钥(BASE64编码)
    • @return
    • @throws Exception
      /
      public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
      throws Exception {
      byte[] keyBytes = Base64Utils.decode(publicKey);
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      Key publicK = keyFactory.generatePublic(x509KeySpec);
      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.DECRYPT_MODE, publicK);
      int inputLen = encryptedData.length;
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int offSet = 0;
      byte[] cache;
      int i = 0;
      // 对数据分段解密
      while (inputLen - offSet > 0) {
      if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
      cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
      } else {
      cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
      }
      out.write(cache, 0, cache.length);
      i++;
      offSet = i
      MAX_DECRYPT_BLOCK;
      }
      byte[] decryptedData = out.toByteArray();
      out.close();
      return decryptedData;
      }

    /**

    • <p>
    • 公钥加密
    • </p>
    • @param data 源数据
    • @param publicKey 公钥(BASE64编码)
    • @return
    • @throws Exception
      /
      public static byte[] encryptByPublicKey(byte[] data, String publicKey)
      throws Exception {
      byte[] keyBytes = Base64Utils.decode(publicKey);
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      Key publicK = keyFactory.generatePublic(x509KeySpec);
      // 对数据加密
      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, publicK);
      int inputLen = data.length;
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int offSet = 0;
      byte[] cache;
      int i = 0;
      // 对数据分段加密
      while (inputLen - offSet > 0) {
      if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
      cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
      } else {
      cache = cipher.doFinal(data, offSet, inputLen - offSet);
      }
      out.write(cache, 0, cache.length);
      i++;
      offSet = i
      MAX_ENCRYPT_BLOCK;
      }
      byte[] encryptedData = out.toByteArray();
      out.close();
      return encryptedData;
      }

    /**

    • <p>
    • 私钥加密
    • </p>
    • @param data 源数据
    • @param privateKey 私钥(BASE64编码)
    • @return
    • @throws Exception
      /
      public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
      throws Exception {
      byte[] keyBytes = Base64Utils.decode(privateKey);
      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, privateK);
      int inputLen = data.length;
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int offSet = 0;
      byte[] cache;
      int i = 0;
      // 对数据分段加密
      while (inputLen - offSet > 0) {
      if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
      cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
      } else {
      cache = cipher.doFinal(data, offSet, inputLen - offSet);
      }
      out.write(cache, 0, cache.length);
      i++;
      offSet = i
      MAX_ENCRYPT_BLOCK;
      }
      byte[] encryptedData = out.toByteArray();
      out.close();
      return encryptedData;
      }

    /**

    • <p>
    • 获取私钥
    • </p>
    • @param keyMap 密钥对
    • @return
    • @throws Exception
      */
      public static String getPrivateKey(Map<String, Object> keyMap)
      throws Exception {
      Key key = (Key) keyMap.get(PRIVATE_KEY);
      return Base64Utils.encode(key.getEncoded());
      }

    /**

    • <p>
    • 获取公钥
    • </p>
    • @param keyMap 密钥对
    • @return
    • @throws Exception
      */
      public static String getPublicKey(Map<String, Object> keyMap)
      throws Exception {
      Key key = (Key) keyMap.get(PUBLIC_KEY);
      return Base64Utils.encode(key.getEncoded());
      }

}

public class Base64Utils {

/**
 * 文件读取缓冲区大小
 */
private static final int CACHE_SIZE = 1024;

/**
 * <p>
 * BASE64字符串解码为二进制数据
 * </p>
 *
 * @param base64
 * @return
 * @throws Exception
 */
public static byte[] decode(String base64) throws Exception {
    return Base64.decode(base64.getBytes());
}

/**
 * <p>
 * 二进制数据编码为BASE64字符串
 * </p>
 *
 * @param bytes
 * @return
 * @throws Exception
 */
public static String encode(byte[] bytes) throws Exception {
    return new String(Base64.encode(bytes));
}

/**
 * <p>
 * 将文件编码为BASE64字符串
 * </p>
 * <p>
 * 大文件慎用,可能会导致内存溢出
 * </p>
 *
 * @param filePath
 *            文件绝对路径
 * @return
 * @throws Exception
 */
public static String encodeFile(String filePath) throws Exception {
    byte[] bytes = fileToByte(filePath);
    return encode(bytes);
}

/**
 * <p>
 * BASE64字符串转回文件
 * </p>
 *
 * @param filePath
 *            文件绝对路径
 * @param base64
 *            编码字符串
 * @throws Exception
 */
public static void decodeToFile(String filePath, String base64) throws Exception {
    byte[] bytes = decode(base64);
    byteArrayToFile(bytes, filePath);
}

/**
 * <p>
 * 文件转换为二进制数组
 * </p>
 *
 * @param filePath
 *            文件路径
 * @return
 * @throws Exception
 */
public static byte[] fileToByte(String filePath) throws Exception {
    byte[] data = new byte[0];
    File file = new File(filePath);
    if (file.exists()) {
        FileInputStream in = new FileInputStream(file);
        ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
        byte[] cache = new byte[CACHE_SIZE];
        int nRead = 0;
        while ((nRead = in.read(cache)) != -1) {
            out.write(cache, 0, nRead);
            out.flush();
        }
        out.close();
        in.close();
        data = out.toByteArray();
    }
    return data;
}

/**
 * <p>
 * 二进制数据写文件
 * </p>
 *
 * @param bytes
 *            二进制数据
 * @param filePath
 *            文件生成目录
 */
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
    InputStream in = new ByteArrayInputStream(bytes);
    File destFile = new File(filePath);
    if (!destFile.getParentFile().exists()) {
        destFile.getParentFile().mkdirs();
    }
    destFile.createNewFile();
    OutputStream out = new FileOutputStream(destFile);
    byte[] cache = new byte[CACHE_SIZE];
    int nRead = 0;
    while ((nRead = in.read(cache)) != -1) {
        out.write(cache, 0, nRead);
        out.flush();
    }
    out.close();
    in.close();
}

}

以上是关于区块链使用的加密和解密技术(JAVA版)的主要内容,如果未能解决你的问题,请参考以下文章

区块链中的非对称加密技术

区块链中的非对称加密技术

区块链的非对称加密是什么技术

技术解读区块链密码学的起源,了解多链与非对称加密

区块链的加密技术

区块链入门到实战之区块链 – 非对称加密