package minsecurity.crypto; import minsecurity.Common; import minsecurity.crypto.sm2.SM2PrivateKey; import minsecurity.crypto.sm2.SM2PublicKey; /* * @Author: hongyu guo * @Description: * @Version: 1.0.0 * @Date: 16:02 2021/03/06 * @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室 */ public class KeyUtils { /** * 可以理解为公钥的"构造函数" * 返回的数据类型为PublicKeyInterface接口, 必要时调用者需要手动将类型强制转化为需要的类型 * @param bytesOfPublicKey 公钥的bytes数组 * @param algorithm 公钥类型 * @return minsecurity.crypto.PublicKeyInterface * @author ghy * @date 2021/3/7 **/ public static PublicKeyInterface unMarshalPublicKey(byte[] bytesOfPublicKey, int algorithm) { if (bytesOfPublicKey == null || bytesOfPublicKey.length == 0) { return null; } switch (algorithm) { case Common.SM2: SM2PublicKey sm2PublicKey = new SM2PublicKey(); sm2PublicKey.setBytes(bytesOfPublicKey); return sm2PublicKey; default: return null; } } /** * 可以理解为私钥的"构造函数" * 返回的数据类型为PrivateKeyInterface接口, 必要时调用者需要手动将类型强制转化为需要的类型 * @param bytesOfPrivateKey 私钥的bytes数组 * @param algorithm 私钥类型 * @return minsecurity.crypto.PrivateKeyInterface * @throws * @author hongyu guo * @date 2021/3/15 **/ public static PrivateKeyInterface unMarshalPrivateKey(byte[] bytesOfPrivateKey, int algorithm){ if(bytesOfPrivateKey == null || bytesOfPrivateKey.length == 0){ return null; } switch (algorithm) { case Common.SM2: SM2PrivateKey sm2PrivateKey = new SM2PrivateKey(); sm2PrivateKey.setBytes(bytesOfPrivateKey); return sm2PrivateKey; default: return null; } } /** * 获取一个16字节的byte数组, 可用作sm4的key * @param passwd 密码 * @return byte[] * @throws * @author hongyu guo * @date 2021/3/15 **/ public static byte[] get16bytePasswd(byte[] passwd) { byte[] hashPasswd = HashAlgo.sm3(passwd); if( hashPasswd.length == 32){ for(int i = 0; i < 16; i++){ hashPasswd[i] += hashPasswd[i + 16]; } } byte[] sm4Key = new byte[16]; System.arraycopy(hashPasswd,0,sm4Key,0,16); return sm4Key; } }