钱包地址生成

//自行定义方法

//BC库解密出现no such provider错误
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        MessageDigest sha = null;
        byte[] s1 = new byte[0];
        MessageDigest rmd = null;

        try {
            //生成RSA公钥和私钥
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");

            //使用指定的椭圆曲线生成
            ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1");
            keyGen.initialize(ecSpec);

            //创建KeyPair即密钥对,从中可以获取公钥和私钥
            KeyPair kp = keyGen.generateKeyPair();

            PublicKey pub = kp.getPublic(); //公钥
            PrivateKey pvt = kp.getPrivate(); //秘钥
            //可以只存储秘钥的私有部分,因为公钥可以从私钥中派生出来

            //ECDSA私钥
            ECPrivateKey epvt = (ECPrivateKey) pvt;
            String sepvt = adjustTo64(epvt.getS().toString(16)).toUpperCase();
            // System.out.println("私钥: s[" + sepvt.length() + "]: " + sepvt);

            //ECDSA公钥
            //密钥的公共部分被编码为比特币地址。首先,ECDSA密钥由椭圆曲线上的点表示。该点的X和Y坐标包括公钥。它们在开头与“04”连接在一起代表公钥。
            ECPublicKey epub = (ECPublicKey) pub;
            ECPoint pt = epub.getW();
            String sx = adjustTo64(pt.getAffineX().toString(16)).toUpperCase(); // x坐标
            String sy = adjustTo64(pt.getAffineY().toString(16)).toUpperCase(); // y坐标
            String bcPub = "04" + sx + sy;

            // System.out.println("公钥bcPub: " + bcPub);

            sha = MessageDigest.getInstance("SHA-256");
            s1 = sha.digest(bcPub.getBytes("UTF-8"));
            rmd = MessageDigest.getInstance("RipeMD160", "BC");

            //根据用户id保存公钥私钥
            apacheService.saveKey(sepvt, bcPub, userId);

        } catch (Exception e) {
            e.printStackTrace();
        }

        byte[] r1 = rmd.digest(s1);
        byte[] r2 = new byte[r1.length + 1];
        r2[0] = 0;
        for (int i = 0; i < r1.length; i++) r2[i + 1] = r1[i];

        //对上面的结果执行两次SHA-256哈希
        byte[] s2 = sha.digest(r2);
        byte[] s3 = sha.digest(s2);

        //第二次散列结果的前4个字节用作地址校验和。它附加到上面的RIPEMD160哈希。这是25字节的比特币地址
        byte[] a1 = new byte[25];
        for (int i = 0; i < r2.length; i++) a1[i] = r2[i];
        for (int i = 0; i < 5; i++) a1[20 + i] = s3[i];


        //使用Base58对地址进行编码 得到钱包地址
        String encode = Base58.encode(a1);

        // System.out.println("钱包地址 : " + encode);

        if (type == 1) {
            encode = Base58.encode(a1);
        }
        if (type == 2) {
            encode = Base58.encode(a1);
        }
        if (type == 3) {
            encode = Base58.encode(a1);
        }

        return ApiResult.ok(encode);
    }

    static private String adjustTo64(String s) {
        switch (s.length()) {

            case 62:
                return "00" + s;

            case 63:
                return "0" + s;

            case 64:
                return s;

            default:
                throw new IllegalArgumentException("not a valid key: " + s);

        }
    }
工具类
/*

 *
 * From https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/core/Base58.java
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.math.BigInteger;
import java.util.Arrays;

/**
 * Base58 is a way to encode Bitcoin addresses (or arbitrary data) as alphanumeric strings.
 * <p>
 * Note that this is not the same base58 as used by Flickr, which you may find referenced around the Internet.
 * <p>
 * Satoshi explains: why base-58 instead of standard base-64 encoding?
 * <ul>
 * <li>Don't want 0OIl characters that look the same in some fonts and
 *     could be used to create visually identical looking account numbers.</li>
 * <li>A string with non-alphanumeric characters is not as easily accepted as an account number.</li>
 * <li>E-mail usually won't line-break if there's no punctuation to break at.</li>
 * <li>Doubleclicking selects the whole number as one word if it's all alphanumeric.</li>
 * </ul>
 * <p>
 * However, note that the encoding/decoding runs in O(n&sup2;) time, so it is not useful for large data.
 * <p>
 * The basic idea of the encoding is to treat the data bytes as a large number represented using
 * base-256 digits, convert the number to be represented using base-58 digits, preserve the exact
 * number of leading zeros (which are otherwise lost during the mathematical operations on the
 * numbers), and finally represent the resulting base-58 digits as alphanumeric ASCII characters.
 */
public class Base58 {
    public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
    private static final char ENCODED_ZERO = ALPHABET[0];
    private static final int[] INDEXES = new int[128];
    static {
        Arrays.fill(INDEXES, -1);
        for (int i = 0; i < ALPHABET.length; i++) {
            INDEXES[ALPHABET[i]] = i;
        }
    }

    /**
     * Encodes the given bytes as a base58 string (no checksum is appended).
     *
     * @param input the bytes to encode
     * @return the base58-encoded string
     */
    public static String encode(byte[] input) {
        if (input.length == 0) {
            return "";
        }
        // Count leading zeros.
        int zeros = 0;
        while (zeros < input.length && input[zeros] == 0) {
            ++zeros;
        }
        // Convert base-256 digits to base-58 digits (plus conversion to ASCII characters)
        input = Arrays.copyOf(input, input.length); // since we modify it in-place
        char[] encoded = new char[input.length * 2]; // upper bound
        int outputStart = encoded.length;
        for (int inputStart = zeros; inputStart < input.length; ) {
            encoded[--outputStart] = ALPHABET[divmod(input, inputStart, 256, 58)];
            if (input[inputStart] == 0) {
                ++inputStart; // optimization - skip leading zeros
            }
        }
        // Preserve exactly as many leading encoded zeros in output as there were leading zeros in input.
        while (outputStart < encoded.length && encoded[outputStart] == ENCODED_ZERO) {
            ++outputStart;
        }
        while (--zeros >= 0) {
            encoded[--outputStart] = ENCODED_ZERO;
        }
        // Return encoded string (including encoded leading zeros).
        return new String(encoded, outputStart, encoded.length - outputStart);
    }

    /**
     * Decodes the given base58 string into the original data bytes.
     *
     * @param input the base58-encoded string to decode
     * @return the decoded data bytes
     */
    public static byte[] decode(String input) {
        if (input.length() == 0) {
            return new byte[0];
        }
        // Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits).
        byte[] input58 = new byte[input.length()];
        for (int i = 0; i < input.length(); ++i) {
            char c = input.charAt(i);
            int digit = c < 128 ? INDEXES[c] : -1;
            if (digit < 0) {
                throw new IllegalStateException("InvalidCharacter in base 58");
            }
            input58[i] = (byte) digit;
        }
        // Count leading zeros.
        int zeros = 0;
        while (zeros < input58.length && input58[zeros] == 0) {
            ++zeros;
        }
        // Convert base-58 digits to base-256 digits.
        byte[] decoded = new byte[input.length()];
        int outputStart = decoded.length;
        for (int inputStart = zeros; inputStart < input58.length; ) {
            decoded[--outputStart] = divmod(input58, inputStart, 58, 256);
            if (input58[inputStart] == 0) {
                ++inputStart; // optimization - skip leading zeros
            }
        }
        // Ignore extra leading zeroes that were added during the calculation.
        while (outputStart < decoded.length && decoded[outputStart] == 0) {
            ++outputStart;
        }
        // Return decoded data (including original number of leading zeros).
        return Arrays.copyOfRange(decoded, outputStart - zeros, decoded.length);
    }

    public static BigInteger decodeToBigInteger(String input) {
        return new BigInteger(1, decode(input));
    }

    /**
     * Divides a number, represented as an array of bytes each containing a single digit
     * in the specified base, by the given divisor. The given number is modified in-place
     * to contain the quotient, and the return value is the remainder.
     *
     * @param number the number to divide
     * @param firstDigit the index within the array of the first non-zero digit
     *        (this is used for optimization by skipping the leading zeros)
     * @param base the base in which the number's digits are represented (up to 256)
     * @param divisor the number to divide by (up to 256)
     * @return the remainder of the division operation
     */
    private static byte divmod(byte[] number, int firstDigit, int base, int divisor) {
        // this is just long division which accounts for the base of the input digits
        int remainder = 0;
        for (int i = firstDigit; i < number.length; i++) {
            int digit = (int) number[i] & 0xFF;
            int temp = remainder * base + digit;
            number[i] = (byte) (temp / divisor);
            remainder = temp % divisor;
        }
        return (byte) remainder;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值