1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| import com.sankuai.cx.etcp.code.util.HexUtil; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence;
import java.io.IOException; import java.math.BigInteger; import java.util.Arrays;
public class ASNUtil {
public static byte[] rsPlainByteArrayToAsn1(byte[] sign,int rsLen){ if(sign.length != rsLen * 2) { throw new RuntimeException("err rs. "); } BigInteger r = new BigInteger(1, Arrays.copyOfRange(sign, 0, rsLen)); BigInteger s = new BigInteger(1, Arrays.copyOfRange(sign, rsLen, rsLen * 2)); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1Integer(r)); v.add(new ASN1Integer(s)); try { return new DERSequence(v).getEncoded("DER"); } catch (IOException e) { throw new RuntimeException(e); } }
public static byte[] rsAsn1ToPlainByteArray(byte[] rsDer,int rsLen){ ASN1Sequence seq = ASN1Sequence.getInstance(rsDer); byte[] r = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(0)).getValue(),rsLen); byte[] s = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(1)).getValue(),rsLen); byte[] result = new byte[rsLen * 2]; System.arraycopy(r, 0, result, 0, r.length); System.arraycopy(s, 0, result, rsLen, s.length); return result; }
public static byte[] bigIntToFixexLengthBytes(BigInteger rOrS,int FixedLength){ byte[] rs = rOrS.toByteArray(); if(rs.length == FixedLength) { return rs; } else if(rs.length == FixedLength + 1 && rs[0] == 0){ return Arrays.copyOfRange(rs, 1, FixedLength + 1); } else if(rs.length < FixedLength) { byte[] result = new byte[FixedLength]; Arrays.fill(result, (byte)0); System.arraycopy(rs, 0, result, FixedLength - rs.length, rs.length); return result; } else { throw new RuntimeException("err rs: " + HexUtil.byteToHex(rs)); } } }
|