SM2公钥加密算法实现 包括 -签名,验签 -密钥交换 -公钥加密,私钥解密 @author SeanDragon
| 15 | * @author SeanDragon |
| 16 | */ |
| 17 | public class SM2 { |
| 18 | private static final int DIGEST_LENGTH = 32; |
| 19 | private static BigInteger n = new BigInteger( |
| 20 | "FFFFFFFE" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "7203DF6B" + "21C6052B" + "53BBF409" + "39D54123", 16); |
| 21 | private static BigInteger p = new BigInteger( |
| 22 | "FFFFFFFE" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "00000000" + "FFFFFFFF" + "FFFFFFFF", 16); |
| 23 | private static BigInteger a = new BigInteger( |
| 24 | "FFFFFFFE" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "00000000" + "FFFFFFFF" + "FFFFFFFC", 16); |
| 25 | private static BigInteger b = new BigInteger( |
| 26 | "28E9FA9E" + "9D9F5E34" + "4D5A9E4B" + "CF6509A7" + "F39789F5" + "15AB8F92" + "DDBCBD41" + "4D940E93", 16); |
| 27 | private static BigInteger gx = new BigInteger( |
| 28 | "32C4AE2C" + "1F198119" + "5F990446" + "6A39C994" + "8FE30BBF" + "F2660BE1" + "715A4589" + "334C74C7", 16); |
| 29 | private static BigInteger gy = new BigInteger( |
| 30 | "BC3736A2" + "F4F6779C" + "59BDCEE3" + "6B692153" + "D0A9877C" + "C62A4740" + "02DF32E5" + "2139F0A0", 16); |
| 31 | private static ECDomainParameters ecc_bc_spec; |
| 32 | private static int w = (int) Math.ceil(n.bitLength() * 1.0 / 2) - 1; |
| 33 | private static BigInteger _2w = new BigInteger("2").pow(w); |
| 34 | private static SecureRandom random = new SecureRandom(); |
| 35 | private static ECCurve.Fp curve; |
| 36 | private static ECPoint G; |
| 37 | |
| 38 | public SM2() { |
| 39 | curve = new ECCurve.Fp(p, // q |
| 40 | a, // a |
| 41 | b); // b |
| 42 | G = curve.createPoint(gx, gy); |
| 43 | ecc_bc_spec = new ECDomainParameters(curve, G, n); |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * 以16进制打印字节数组 |
| 48 | * |
| 49 | * @param bytes |
| 50 | */ |
| 51 | private static void printHexString(byte[] bytes) { |
| 52 | for (byte b : bytes) { |
| 53 | String hex = Integer.toHexString(b & 0xFF); |
| 54 | if (hex.length() == 1) { |
| 55 | hex = '0' + hex; |
| 56 | } |
| 57 | System.out.print(hex.toUpperCase()); |
| 58 | } |
| 59 | System.out.println(); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * 随机数生成器 |
| 64 | * |
| 65 | * @param max |
| 66 | * @return |
| 67 | */ |
| 68 | private static BigInteger random(BigInteger max) { |
| 69 | BigInteger r = new BigInteger(256, random); |
| 70 | while (r.compareTo(max) >= 0) { |
| 71 | r = new BigInteger(128, random); |
| 72 | } |
| 73 | return r; |
| 74 | } |