def _encode_bitstring(obj: univ.BitString) -> str: """ Encodes a PyASN1 bitstring object Args: obj: The PyASN1 bitstring object Returns: A string with the encoded value """ if str.find(repr(obj), 'BitString') == -1: raise ValueError('[PyASN1PEREncoder][ERROR]: Value sent to BitString encoder not a ' 'BitString - Expected [BitString] got: [' + str(type(obj)) + ']') dec_constraint = _extract_value_size_constraint(repr(obj)) obj = str(obj) obj = obj.replace(',', '') obj = obj.replace(' ', '') obj = obj.replace('(', '') obj = obj.replace(')', '') if dec_constraint == -1: return '' # No encoding required if length constrained to zero if len(obj) < dec_constraint[0] or len(obj) > dec_constraint[1]: raise OverflowError('[PyASN1PEREncoder][ERROR]: Value outside of constraint for field,' ' encoding cannot continue\nExpected [' + dec_constraint[0] + '<val<' + dec_constraint[1] + '] got [' + str(len(obj)) + ']') if dec_constraint[0] == dec_constraint[1]: return obj # If ub == lb, just append the BitString else: # if ub != lb offset_bitfield_range = len(str(bin(dec_constraint[1]-dec_constraint[0]))[2:]) str_len = len(str(obj)) size_str = _bit_str_pad(str(bin(str_len)), offset_bitfield_range, '0') return size_str + obj
def encode(dh_key: object): pub_bs = bin( Bytes(encoder.encode(Integer(dh_key.get_challenge()))).int())[2:] pub_bs = pub_bs.zfill(math.ceil(len(pub_bs) / 8) * 8) pub_bs = BitString(pub_bs) return pub_bs
class APReq(_K5Sequence): tagSet = _apptag(14) componentType = NamedTypes(_mfield('pvno', 0, Integer()), _mfield('msg-type', 1, Integer()), _mfield('ap-options', 2, BitString()), _mfield('ticket', 3, Ticket()), _mfield('authenticator', 4, EncryptedData()))
def sign(self, pki_obj, data): new_pki = deepcopy(pki_obj) new_pki.hash_obj = self.hash_obj r, s = new_pki.sign(data) seq = SequenceOf() seq.extend([Integer(r), Integer(s)]) return BitString(Bytes(encoder.encode(seq)).int())
class SubjectPublicKeyInfo(Sequence): """ SubjectPublicKeyInfo ::= SEQUENCE { algorithm AlgorithmIdentifier, subjectPublicKey BIT STRING } """ componentType = NamedTypes( NamedType('algorithm', AlgorithmIdentifier()), NamedType('subjectPublicKey', BitString()), )
def encode(rsa_key: object): param_seq = SequenceOf() param_seq.append(Integer(rsa_key.n)) param_seq.append(Integer(rsa_key.e)) param_bs = bin(Bytes(encoder.encode(param_seq)).int())[2:] param_bs = param_bs.zfill(math.ceil(len(param_bs) / 8) * 8) param_bs = BitString(param_bs) return param_bs
class EncKDCRepPart(_K5Sequence): componentType = NamedTypes(_mfield('key', 0, EncryptionKey()), _mfield('last-req', 1, LastReq()), _mfield('nonce', 2, Integer()), _ofield('key-expiration', 3, GeneralizedTime()), _mfield('flags', 4, BitString()), _mfield('authtime', 5, GeneralizedTime()), _ofield('starttime', 6, GeneralizedTime()), _mfield('endtime', 7, GeneralizedTime()), _ofield('renew-till', 8, GeneralizedTime()), _mfield('srealm', 9, GeneralString()), _mfield('sname', 10, PrincipalName()), _ofield('caddr', 11, HostAddresses()))
class KDCReqBody(_K5Sequence): componentType = NamedTypes( _mfield('kdc-options', 0, BitString()), _ofield('cname', 1, PrincipalName()), _mfield('realm', 2, GeneralString()), _ofield('sname', 3, PrincipalName()), _ofield('from', 4, GeneralizedTime()), _mfield('till', 5, GeneralizedTime()), _ofield('rtime', 6, GeneralizedTime()), _mfield('nonce', 7, Integer()), _mfield('etype', 8, SequenceOf(componentType=Integer())), _ofield('addresses', 9, HostAddresses()), _ofield('enc-authorization-data', 10, EncryptedData()), _ofield('additional-tickets', 11, SequenceOf(componentType=Ticket())))
def test_bitstring_empty(self): self.assertTrue(ASN1Tools.bitstring_is_empty(BitString([]))) self.assertTrue(ASN1Tools.bitstring_is_empty(BitString([0]))) self.assertTrue(ASN1Tools.bitstring_is_empty(BitString([0, 0, 0]))) self.assertFalse(ASN1Tools.bitstring_is_empty(BitString([1]))) self.assertFalse(ASN1Tools.bitstring_is_empty(BitString([0, 1]))) self.assertFalse(ASN1Tools.bitstring_is_empty(BitString([0, 0, 1, 0])))
class ECPrivateKey(Sequence): componentType = NamedTypes( NamedType( "version", Integer(namedValues=NamedValues(("ecPrivkeyVer1", 1))).subtype( subtypeSpec=Integer.subtypeSpec + SingleValueConstraint(1))), NamedType("privateKey", OctetString()), OptionalNamedType( "parameters", ObjectIdentifier().subtype( explicitTag=Tag(tagClassContext, tagFormatSimple, 0))), OptionalNamedType( "publicKey", BitString().subtype( explicitTag=Tag(tagClassContext, tagFormatSimple, 1))))
def test_bitstring_trailing_zero(self): self.assertTrue( ASN1Tools.bitstring_has_trailing_zeros(BitString([0, 1, 0]))) self.assertTrue(ASN1Tools.bitstring_has_trailing_zeros(BitString([0]))) self.assertTrue( ASN1Tools.bitstring_has_trailing_zeros( BitString([1, 1, 1, 1, 1, 1, 1, 0]))) self.assertTrue( ASN1Tools.bitstring_has_trailing_zeros( BitString([1, 1, 1, 1, 1, 1, 1, 1, 0]))) self.assertFalse( ASN1Tools.bitstring_has_trailing_zeros(BitString([0, 1]))) self.assertFalse(ASN1Tools.bitstring_has_trailing_zeros(BitString([]))) self.assertFalse( ASN1Tools.bitstring_has_trailing_zeros(BitString([0, 0, 0, 0, 1]))) self.assertFalse( ASN1Tools.bitstring_has_trailing_zeros( BitString([0, 0, 0, 0, 0, 0, 1]))) self.assertFalse( ASN1Tools.bitstring_has_trailing_zeros( BitString([0, 0, 0, 0, 0, 0, 0, 1])))
def makeRSAPublicKey(modulus, publicExponent): algorithm = AlgorithmIdentifier() algorithm['algorithm'] = '1.2.840.113549.1.1.1' # rsaEncription algorithm['parameters'] = Null('') subjectPublicKey = RSAPublicKey() subjectPublicKey['modulus'] = modulus subjectPublicKey['publicExponent'] = publicExponent subjectPublicKeyInfo = SubjectPublicKeyInfo() subjectPublicKeyInfo['algorithm'] = algorithm # int.from_bytes() subjectPublicKeyInfo['subjectPublicKey'] = BitString( hexValue=encode(subjectPublicKey).hex()) return b64encode(encode(subjectPublicKeyInfo))
def set_signature(self, signature: bytes): """ Modify the signature of a CSR. :param bytes signature: the new signature for a CSR. :rtype: None """ der_csr = self.public_bytes(serialization.Encoding.DER) asn1_csr, _ = asn1_decode( der_csr, asn1Spec=CertificationRequest(), ) asn1_csr.setComponentByName("signature", BitString.fromOctetString(signature)) self._x509_req = x509.load_der_x509_csr( asn1_encode(asn1_csr))._x509_req
def inject_rand_in_plain_prikey(prikey_b64: str, rand_num: bytes) -> str: """ Inject rand num for NPKI private key :param prikey_b64: decrypted NPKI private key in base64 form (e.g., "MII....") :param rand_num: (bytes) rand num for 1.2.410.200004.10.1.1.3 :return: base64 encoded private key without encryption """ private_key, rest_of_input = der_decoder.decode( base64.b64decode(prikey_b64)) rand_num_set = SeqNPKIPrivateKeyRandomNumberSet() rand_num_set['rand'] = BitString(hexValue=rand_num.hex()) rand_num_seq = SeqNPKIPrivateKeyRandomNumber() rand_num_seq['oid'] = ID_KISA_NPKI_RAND_NUM rand_num_seq['rand_set'] = rand_num_set rand_num_seqset = SeqNPKIPrivateKeyRandomNumberSeqSet().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)) rand_num_seqset['rand_seq'] = rand_num_seq prikey_plain = NPKIPlainPrivateKey() prikey_plain['version'] = private_key[0] prikey_plain['info'] = private_key[1] prikey_plain['private_key_octet'] = private_key[2] prikey_plain['rand'] = rand_num_seqset dump = base64.b64encode(encode(prikey_plain)) return dump.decode('latin1')
def encode(eddsa_key: object): pub_point = eddsa_key.encode_point(eddsa_key.A)[::-1].int() zero_fill = math.ceil(pub_point.bit_length() / 8) * 8 return BitString(bin(pub_point)[2:].zfill(zero_fill))
def test_bitstring_highest_set_bit(self): self.assertEqual(ASN1Tools.bitstring_highbit(BitString([])), None) self.assertEqual(ASN1Tools.bitstring_highbit(BitString([0])), None) self.assertEqual(ASN1Tools.bitstring_highbit(BitString([0, 0])), None) self.assertEqual(ASN1Tools.bitstring_highbit(BitString([1])), 0) self.assertEqual(ASN1Tools.bitstring_highbit(BitString([1, 1])), 1) self.assertEqual(ASN1Tools.bitstring_highbit(BitString([1, 1, 1])), 2) self.assertEqual(ASN1Tools.bitstring_highbit(BitString([1, 1, 1, 0])), 2) self.assertEqual( ASN1Tools.bitstring_highbit(BitString([1, 1, 1, 0, 0])), 2) self.assertEqual( ASN1Tools.bitstring_highbit(BitString([1, 1, 1, 0, 0, 1])), 5) self.assertEqual( ASN1Tools.bitstring_highbit(BitString([1, 1, 1, 0, 0, 1, 0])), 5) self.assertEqual( ASN1Tools.bitstring_highbit(BitString([1, 1, 1, 0, 0, 1, 0, 1])), 7)
class SeqNPKIPrivateKeyRandomNumberSet(Set): componentType = NamedTypes(NamedType('rand', BitString()))
def encode(ecdsa_key: object): return BitString(ecdsa_key.format_public_point())
stdin=subprocess.PIPE, stderr=subprocess.STDOUT) newSignature = pipe.communicate( input=binascii.a2b_base64(dilithium_substrate) + final_hash)[0] # Verify the signature was properly generated, if not, print the error if pipe.returncode != 0: print(newSignature.decode()) exit(-1) # Update the signature algorithm with the one placed inside of the TBS cert["signatureAlgorithm"]["algorithm"] = cert["tbsCertificate"][ "signature"]["algorithm"] # Load the signature into the certificate as a bitstring cert["signatureValue"] = BitString.fromOctetString(newSignature) elif sigAlg == 1: # RSA Signature > openssl call # Open a pipe to send the hash and get back the signature without going through the filesystem pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) newSignature = pipe.communicate(input=final_hash)[0] # Verify the signature was properly generated, if not, print the error if pipe.returncode != 0: print(newSignature.decode()) exit(-1) # Update the signature algorithm with the one placed inside of the TBS
def encode(dsa_key: object): y_bits = bin(Bytes(encoder.encode(Integer(dsa_key.y))).int())[2:] y_bits = y_bits.zfill(math.ceil(len(y_bits) / 8) * 8) y_bits = BitString(y_bits) return y_bits
def sign(self, pki_obj, data): from samson.protocols.pkcs1v15_rsa_signer import PKCS1v15RSASigner signed = PKCS1v15RSASigner(pki_obj, self.hash_obj).sign(data) return BitString(bin(signed.int())[2:].zfill(pki_obj.n.bit_length()))