import * as b64 from 'base64-url' ; import { num2hexstring , StringReader } from '../utils' ; import { SignatureScheme } from './SignatureScheme' ; /**
 * Signature generated by signing data with Private Key.
 */ export class Signature { static deserializeJWT ( encoded , algorithm , publicKeyId ) { let decoded = b64 . decode ( encoded , 'hex' ) ; if ( decoded . startsWith ( '01' ) ) { decoded = decoded . substring ( 2 ) ; } return new Signature ( algorithm , decoded , publicKeyId ) ; } param pgpSignature static deserializePgp ( pgpSignature ) { const value = new Buffer ( pgpSignature . Value , 'base64' ) . toString ( 'hex' ) ; const deserialzedValue = Signature . deserializeHex ( value ) . value ; return new Signature ( SignatureScheme . fromLabel ( pgpSignature . Algorithm ) , deserialzedValue ) ; } param data static deserializeHex ( data ) { if ( data . length < 4 ) { throw new Error ( 'Invalid params.' ) ; } if ( data . length === 130 ) { try { const sr = new StringReader ( data ) ; const scheme = parseInt ( sr . read ( 1 ) , 16 ) ; const sigScheme = SignatureScheme . fromHex ( scheme ) ; const value = data . substr ( 2 ) ; return new Signature ( sigScheme , value ) ; } catch ( error ) { throw new Error ( 'Signature error, incorrect format' ) ; } } else { if ( data . length !== 128 ) { throw new Error ( 'Signature error, invalid signature data length' ) ; } const sigScheme = SignatureScheme . fromHex ( 1 ) ; const value = data . substr ( 2 ) ; return new Signature ( sigScheme , value ) ; } } algorithm : SignatureScheme ; value : string ; /**
     * Public key Id used for create this signature.
     *
     */ publicKeyId ? : string ; constructor ( algorithm , value , publicKeyId ? ) { this . algorithm = algorithm ; this . value = value ; this . publicKeyId = publicKeyId ; } /**
     * Serializes signature to Hex representation.
     * For transfer to java backend and verify it.
     */ serializeHex ( ) { let result = '' ; result += num2hexstring ( this . algorithm . hex ) ; result += this . value ; return result ; } param keyId serializePgp ( keyId ? ) { const encoded = new Buffer ( this . serializeHex ( ) , 'hex' ) . toString ( 'base64' ) ; return { PublicKeyId : keyId , Format : 'pgp' , Value : encoded , Algorithm : this . algorithm . label } ; } /**
     * Serializes signature to base64url format.
     */ serializeJWT ( ) { return new Buffer ( this . serializeHex ( ) , 'hex' ) . toString ( 'base64' ) ; } } /**
 * PGP representation of the signature with embedded KeyId
 */ export interface PgpSignature { PublicKeyId ? : string ; Format : 'pgp' ; Algorithm : string ; Value : string ; }