|
| 1 | +package org.bouncycastle.asn1; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +/** |
| 6 | + * A BIT STRING with DER encoding - the first byte contains the count of padding bits included in the byte array's last byte. |
| 7 | + */ |
| 8 | +public class DERBitString |
| 9 | + extends ASN1BitString |
| 10 | +{ |
| 11 | + public static DERBitString convert(ASN1BitString bitString) |
| 12 | + { |
| 13 | + return (DERBitString)bitString.toDERObject(); |
| 14 | + } |
| 15 | + |
| 16 | + public DERBitString(byte[] data) |
| 17 | + { |
| 18 | + this(data, 0); |
| 19 | + } |
| 20 | + |
| 21 | + public DERBitString(byte data, int padBits) |
| 22 | + { |
| 23 | + super(data, padBits); |
| 24 | + } |
| 25 | + |
| 26 | + public DERBitString(byte[] data, int padBits) |
| 27 | + { |
| 28 | + super(data, padBits); |
| 29 | + } |
| 30 | + |
| 31 | + public DERBitString(int value) |
| 32 | + { |
| 33 | + // TODO[asn1] Unify in single allocation of 'contents' |
| 34 | + super(getBytes(value), getPadBits(value)); |
| 35 | + } |
| 36 | + |
| 37 | + public DERBitString(ASN1Encodable obj) throws IOException |
| 38 | + { |
| 39 | + // TODO[asn1] Unify in single allocation of 'contents' |
| 40 | + super(obj.toASN1Primitive().getEncoded(ASN1Encoding.DER), 0); |
| 41 | + } |
| 42 | + |
| 43 | + DERBitString(byte[] contents, boolean check) |
| 44 | + { |
| 45 | + super(contents, check); |
| 46 | + } |
| 47 | + |
| 48 | + boolean encodeConstructed() |
| 49 | + { |
| 50 | + return false; |
| 51 | + } |
| 52 | + |
| 53 | + int encodedLength(boolean withTag) |
| 54 | + { |
| 55 | + return ASN1OutputStream.getLengthOfEncodingDL(withTag, contents.length); |
| 56 | + } |
| 57 | + |
| 58 | + void encode(ASN1OutputStream out, boolean withTag) throws IOException |
| 59 | + { |
| 60 | + int padBits = contents[0] & 0xFF; |
| 61 | + int length = contents.length; |
| 62 | + int last = length - 1; |
| 63 | + |
| 64 | + byte lastOctet = contents[last]; |
| 65 | + byte lastOctetDER = (byte)(contents[last] & (0xFF << padBits)); |
| 66 | + |
| 67 | + if (lastOctet == lastOctetDER) |
| 68 | + { |
| 69 | + out.writeEncodingDL(withTag, BERTags.BIT_STRING, contents); |
| 70 | + } |
| 71 | + else |
| 72 | + { |
| 73 | + out.writeEncodingDL(withTag, BERTags.BIT_STRING, contents, 0, last, lastOctetDER); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + ASN1Primitive toDERObject() |
| 78 | + { |
| 79 | + return this; |
| 80 | + } |
| 81 | + |
| 82 | + ASN1Primitive toDLObject() |
| 83 | + { |
| 84 | + return this; |
| 85 | + } |
| 86 | + |
| 87 | + static DERBitString fromOctetString(ASN1OctetString octetString) |
| 88 | + { |
| 89 | + return new DERBitString(octetString.getOctets(), true); |
| 90 | + } |
| 91 | +} |
0 commit comments