Example usage for java.math BigInteger toByteArray

List of usage examples for java.math BigInteger toByteArray

Introduction

In this page you can find the example usage for java.math BigInteger toByteArray.

Prototype

public byte[] toByteArray() 

Source Link

Document

Returns a byte array containing the two's-complement representation of this BigInteger.

Usage

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

public SmartcardStatusCode setAuthenticationKey(BigInteger pk, int keyID, RSAKeyPair rootKey) {
    byte[] pk_bytes = pk.toByteArray();
    pk_bytes = removeSignBit(pk_bytes);/*  w w  w. j a  va 2s  .  com*/
    ResponseAPDU response;
    try {
        int mode = this.getMode();
        if (mode == 1) {
            this.putData(pk_bytes);
        } else if (mode == 2) {
            System.out.println("Can only use setAuthenticationKey in root mode");
            return SmartcardStatusCode.UNAUTHORIZED;
        }
        System.out.println("Input for setAuthKey: " + Arrays.toString(
                new byte[] { (byte) this.ABC4TRUSTCMD, this.setAuthenticationKey, 0, 0, 1, (byte) keyID }));
        response = this.transmitCommand(new CommandAPDU(this.ABC4TRUSTCMD, this.setAuthenticationKey, 0, 0,
                new byte[] { (byte) keyID }));
        System.out.println("response from setAuthKey: " + response);
        return this.evaluateStatus(response);
    } catch (CardException e) {
        return SmartcardStatusCode.NOT_FOUND;
    }
}

From source file:org.plasma.sdo.helper.DataConverter.java

public Object fromInteger(Type targetType, BigInteger value) {
    DataType targetDataType = DataType.valueOf(targetType.getName());
    switch (targetDataType) {
    case Integer:
        return value;
    case Double:
        return new Double(value.doubleValue());
    case Float:
        return new Float(value.floatValue());
    case Int:/*from  w w  w  .  java 2  s.c  om*/
        return new Integer(value.intValue());
    case Long:
        return new Long(value.longValue());
    case Decimal:
        return new BigDecimal(value.doubleValue());
    case Bytes:
        return value.toByteArray();
    case String:
        //as per spec: ('+'|'-')? [0-9]+
        return value.toString();
    default:
        throw new InvalidDataConversionException(targetDataType, DataType.Integer, value);
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

@Override
public int init(int newPin, SystemParameters pseuParams, RSAKeyPair rootKey, short deviceId) {
    if (this.wasInit()) {
        return -1;
    }/*from w  w w  . java2  s. c o m*/
    try {

        byte[] deviceID = ByteBuffer.allocate(2).putShort(deviceId).array();
        this.setAuthenticationKey(rootKey.getN(), 0, null);
        byte[] deviceKeySize = this.intLengthToShortByteArr(pseuParams.deviceSecretSizeBytes);
        byte[] idAndDeviceKeySize = new byte[] { deviceID[0], deviceID[1], deviceKeySize[0], deviceKeySize[1] };
        ByteBuffer buf = ByteBuffer.allocate(13);
        buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.initializeDevice, 0, 0, 0, 0, 4 });
        buf.put(idAndDeviceKeySize);
        buf.put(new byte[] { 0, 0 });
        buf.position(0);
        if (printInput)
            System.out.println("Input to initialize device: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
            return -1;
        }
        byte[] pinAndPuk = SmartcardCrypto.decrypt(response.getData(), rootKey);
        byte[] pin = new byte[4];
        byte[] puk = new byte[8];
        System.arraycopy(pinAndPuk, 0, pin, 0, 4);
        System.arraycopy(pinAndPuk, 4, puk, 0, 8);
        String ipin = "", ipuk = "";
        for (int i = 0; i < 4; i++) {
            ipin += (char) (pin[i] & 0xFF);
        }
        for (int i = 0; i < 8; i++) {
            ipuk += (char) (puk[i] & 0xFF);
        }
        if (this.changePin(Integer.parseInt(ipin), newPin) != SmartcardStatusCode.OK) {
            System.out.println("Could not change pin.");
            return -1;
        }

        System.out.println("Now initializing group stuff");
        int mode = this.getMode();

        if (this.setGroupComponent(mode, pseuParams.p.toByteArray(), 0, 0, null) != SmartcardStatusCode.OK) {
            return -1;
        }
        if (this.setGroupComponent(mode, pseuParams.subgroupOrder.toByteArray(), 0, 1,
                null) != SmartcardStatusCode.OK) {
            return -1;
        }
        BigInteger f = pseuParams.p.subtract(BigInteger.ONE).divide(pseuParams.subgroupOrder); //cofactor
        this.setGroupComponent(mode, f.toByteArray(), 0, 2, null);

        //then add a generator of the subgroup q
        if (this.setGenerator(mode, pseuParams.g.toByteArray(), 0, 1, null) != SmartcardStatusCode.OK) {
            return -1;
        }

        //set prover
        byte[] data = new byte[5 + MAX_CREDENTIALS + 1];
        data[0] = 1; //id 1
        int ksize = pseuParams.zkChallengeSizeBytes * 2 + pseuParams.zkStatisticalHidingSizeBytes;
        byte[] ksize_bytes = this.intLengthToShortByteArr(ksize);
        data[1] = ksize_bytes[0];
        data[2] = ksize_bytes[1]; // as large as the subgroup order is -1 to prevent overflow.
        int csize = pseuParams.zkChallengeSizeBytes;
        byte[] csize_bytes = this.intLengthToShortByteArr(csize);
        data[3] = csize_bytes[0];
        data[4] = csize_bytes[1]; // challenge size: 256 bit = 32 bytes (as per default in SystemParameters)
        for (int i = 0; i <= MAX_CREDENTIALS; i++) {
            //0 means it accepts both credentials and scope-exclusive stuff.
            //1,2,3,... means it accepts credentials with id 1,2,3,...
            data[i + 5] = (byte) i;
        }
        buf = ByteBuffer.allocate(5 + data.length);
        buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.setProver, 0, 0, (byte) data.length });
        buf.put(data);
        buf.position(0);
        System.out.println("Input to prover: " + Arrays.toString(buf.array()));
        response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from setProver: " + response);
        if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
            return -1;
        }

        //After init, one should call setIssuer which creates a group and counter.
        return Integer.parseInt(ipuk);
    } catch (CardException e) {
        e.printStackTrace();
        return -1;
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

private static void writeBigInteger(BigInteger o, DataOutput out) throws IOException {
    InternalDataSerializer.checkOut(out);

    if (logger.isTraceEnabled(LogMarker.SERIALIZER)) {
        logger.trace(LogMarker.SERIALIZER, "Writing BigInteger: {}", o);
    }//ww  w  .j  a v  a 2 s.  c o m
    DataSerializer.writeByteArray(o.toByteArray(), out);
}

From source file:org.telegram.messenger.MessagesController.java

public void processAcceptedSecretChat(final TLRPC.EncryptedChat encryptedChat) {
    BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes);
    BigInteger i_authKey = new BigInteger(1, encryptedChat.g_a_or_b);

    if (!Utilities.isGoodGaAndGb(i_authKey, p)) {
        declineSecretChat(encryptedChat.id);
        return;/*from   w w w  .  j a va 2s .c om*/
    }

    i_authKey = i_authKey.modPow(new BigInteger(1, encryptedChat.a_or_b), p);

    byte[] authKey = i_authKey.toByteArray();
    if (authKey.length > 256) {
        byte[] correctedAuth = new byte[256];
        System.arraycopy(authKey, authKey.length - 256, correctedAuth, 0, 256);
        authKey = correctedAuth;
    } else if (authKey.length < 256) {
        byte[] correctedAuth = new byte[256];
        System.arraycopy(authKey, 0, correctedAuth, 256 - authKey.length, authKey.length);
        for (int a = 0; a < 256 - authKey.length; a++) {
            authKey[a] = 0;
        }
        authKey = correctedAuth;
    }
    byte[] authKeyHash = Utilities.computeSHA1(authKey);
    byte[] authKeyId = new byte[8];
    System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8);
    long fingerprint = Utilities.bytesToLong(authKeyId);
    if (encryptedChat.key_fingerprint == fingerprint) {
        encryptedChat.auth_key = authKey;
        MessagesStorage.Instance.updateEncryptedChat(encryptedChat);
        Utilities.RunOnUIThread(new Runnable() {
            @Override
            public void run() {
                encryptedChats.put(encryptedChat.id, encryptedChat);
                NotificationCenter.Instance.postNotificationName(encryptedChatUpdated, encryptedChat);
            }
        });
    } else {
        final TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded();
        newChat.id = encryptedChat.id;
        newChat.user_id = encryptedChat.user_id;
        newChat.auth_key = encryptedChat.auth_key;
        MessagesStorage.Instance.updateEncryptedChat(newChat);
        Utilities.RunOnUIThread(new Runnable() {
            @Override
            public void run() {
                encryptedChats.put(newChat.id, newChat);
                NotificationCenter.Instance.postNotificationName(encryptedChatUpdated, newChat);
            }
        });
        declineSecretChat(encryptedChat.id);
    }
}

From source file:org.telegram.messenger.MessagesController.java

public void startSecretChat(final Context context, final TLRPC.User user) {
    if (user == null) {
        return;//from  w ww.  ja v a2 s . c o m
    }
    final ProgressDialog progressDialog = new ProgressDialog(context);
    progressDialog.setMessage(context.getString(R.string.Loading));
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.setCancelable(false);
    progressDialog.show();
    TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
    req.random_length = 256;
    req.version = MessagesStorage.lastSecretVersion;
    ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() {
        @Override
        public void run(TLObject response, TLRPC.TL_error error) {
            if (error == null) {
                TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response;
                if (response instanceof TLRPC.TL_messages_dhConfig) {
                    if (!Utilities.isGoodPrime(res.p, res.g)) {
                        Utilities.RunOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        progressDialog.dismiss();
                                    }
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                            }
                        });
                        return;
                    }
                    MessagesStorage.secretPBytes = res.p;
                    MessagesStorage.secretG = res.g;
                    MessagesStorage.lastSecretVersion = res.version;
                    MessagesStorage.Instance.saveSecretParams(MessagesStorage.lastSecretVersion,
                            MessagesStorage.secretG, MessagesStorage.secretPBytes);
                }
                final byte[] salt = new byte[256];
                for (int a = 0; a < 256; a++) {
                    salt[a] = (byte) ((byte) (random.nextDouble() * 256) ^ res.random[a]);
                }

                BigInteger i_g_a = BigInteger.valueOf(MessagesStorage.secretG);
                i_g_a = i_g_a.modPow(new BigInteger(1, salt), new BigInteger(1, MessagesStorage.secretPBytes));
                byte[] g_a = i_g_a.toByteArray();
                if (g_a.length > 256) {
                    byte[] correctedAuth = new byte[256];
                    System.arraycopy(g_a, 1, correctedAuth, 0, 256);
                    g_a = correctedAuth;
                }

                TLRPC.TL_messages_requestEncryption req2 = new TLRPC.TL_messages_requestEncryption();
                req2.g_a = g_a;
                req2.user_id = getInputUser(user);
                req2.random_id = (int) (random.nextDouble() * Integer.MAX_VALUE);
                ConnectionsManager.Instance.performRpc(req2, new RPCRequest.RPCRequestDelegate() {
                    @Override
                    public void run(final TLObject response, TLRPC.TL_error error) {
                        if (error == null) {
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        try {
                                            progressDialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                    }
                                    TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) response;
                                    chat.user_id = chat.participant_id;
                                    encryptedChats.put(chat.id, chat);
                                    chat.a_or_b = salt;
                                    TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
                                    dialog.id = ((long) chat.id) << 32;
                                    dialog.unread_count = 0;
                                    dialog.top_message = 0;
                                    dialog.last_message_date = ConnectionsManager.Instance.getCurrentTime();
                                    dialogs_dict.put(dialog.id, dialog);
                                    dialogs.add(dialog);
                                    dialogsServerOnly.clear();
                                    Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {
                                        @Override
                                        public int compare(TLRPC.TL_dialog tl_dialog,
                                                TLRPC.TL_dialog tl_dialog2) {
                                            if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {
                                                return 0;
                                            } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {
                                                return 1;
                                            } else {
                                                return -1;
                                            }
                                        }
                                    });
                                    for (TLRPC.TL_dialog d : dialogs) {
                                        if ((int) d.id != 0) {
                                            dialogsServerOnly.add(d);
                                        }
                                    }
                                    NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                                    MessagesStorage.Instance.putEncryptedChat(chat, user, dialog);
                                    NotificationCenter.Instance.postNotificationName(encryptedChatCreated,
                                            chat);
                                }
                            });
                        } else {
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        try {
                                            progressDialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                        builder.setTitle(context.getString(R.string.AppName));
                                        builder.setMessage(String.format(
                                                context.getString(R.string.CreateEncryptedChatOutdatedError),
                                                user.first_name, user.first_name));
                                        builder.setPositiveButton(
                                                ApplicationLoader.applicationContext.getString(R.string.OK),
                                                null);
                                        builder.show().setCanceledOnTouchOutside(true);
                                    }
                                }
                            });
                        }
                    }
                }, null, true,
                        RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
            } else {
                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!((ActionBarActivity) context).isFinishing()) {
                            try {
                                progressDialog.dismiss();
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                        }
                    }
                });
            }
        }
    }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
}

From source file:org.telegram.messenger.MessagesController.java

public void acceptSecretChat(final TLRPC.EncryptedChat encryptedChat) {
    if (acceptingChats.get(encryptedChat.id) != null) {
        return;//ww  w  . j a  v a 2 s  .c  o m
    }
    acceptingChats.put(encryptedChat.id, encryptedChat);
    TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
    req.random_length = 256;
    req.version = MessagesStorage.lastSecretVersion;
    ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() {
        @Override
        public void run(TLObject response, TLRPC.TL_error error) {
            if (error == null) {
                TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response;
                if (response instanceof TLRPC.TL_messages_dhConfig) {
                    if (!Utilities.isGoodPrime(res.p, res.g)) {
                        acceptingChats.remove(encryptedChat.id);
                        declineSecretChat(encryptedChat.id);
                        return;
                    }

                    MessagesStorage.secretPBytes = res.p;
                    MessagesStorage.secretG = res.g;
                    MessagesStorage.lastSecretVersion = res.version;
                    MessagesStorage.Instance.saveSecretParams(MessagesStorage.lastSecretVersion,
                            MessagesStorage.secretG, MessagesStorage.secretPBytes);
                }
                byte[] salt = new byte[256];
                for (int a = 0; a < 256; a++) {
                    salt[a] = (byte) ((byte) (random.nextDouble() * 256) ^ res.random[a]);
                }
                encryptedChat.a_or_b = salt;
                BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes);
                BigInteger g_b = BigInteger.valueOf(MessagesStorage.secretG);
                g_b = g_b.modPow(new BigInteger(1, salt), p);
                BigInteger g_a = new BigInteger(1, encryptedChat.g_a);

                if (!Utilities.isGoodGaAndGb(g_a, p)) {
                    acceptingChats.remove(encryptedChat.id);
                    declineSecretChat(encryptedChat.id);
                    return;
                }

                byte[] g_b_bytes = g_b.toByteArray();
                if (g_b_bytes.length > 256) {
                    byte[] correctedAuth = new byte[256];
                    System.arraycopy(g_b_bytes, 1, correctedAuth, 0, 256);
                    g_b_bytes = correctedAuth;
                }

                g_a = g_a.modPow(new BigInteger(1, salt), p);

                byte[] authKey = g_a.toByteArray();
                if (authKey.length > 256) {
                    byte[] correctedAuth = new byte[256];
                    System.arraycopy(authKey, authKey.length - 256, correctedAuth, 0, 256);
                    authKey = correctedAuth;
                } else if (authKey.length < 256) {
                    byte[] correctedAuth = new byte[256];
                    System.arraycopy(authKey, 0, correctedAuth, 256 - authKey.length, authKey.length);
                    for (int a = 0; a < 256 - authKey.length; a++) {
                        authKey[a] = 0;
                    }
                    authKey = correctedAuth;
                }
                byte[] authKeyHash = Utilities.computeSHA1(authKey);
                byte[] authKeyId = new byte[8];
                System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8);
                encryptedChat.auth_key = authKey;

                TLRPC.TL_messages_acceptEncryption req2 = new TLRPC.TL_messages_acceptEncryption();
                req2.g_b = g_b_bytes;
                req2.peer = new TLRPC.TL_inputEncryptedChat();
                req2.peer.chat_id = encryptedChat.id;
                req2.peer.access_hash = encryptedChat.access_hash;
                req2.key_fingerprint = Utilities.bytesToLong(authKeyId);
                ConnectionsManager.Instance.performRpc(req2, new RPCRequest.RPCRequestDelegate() {
                    @Override
                    public void run(TLObject response, TLRPC.TL_error error) {
                        acceptingChats.remove(encryptedChat.id);
                        if (error == null) {
                            final TLRPC.EncryptedChat newChat = (TLRPC.EncryptedChat) response;
                            newChat.auth_key = encryptedChat.auth_key;
                            newChat.user_id = encryptedChat.user_id;
                            MessagesStorage.Instance.updateEncryptedChat(newChat);
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    encryptedChats.put(newChat.id, newChat);
                                    NotificationCenter.Instance.postNotificationName(encryptedChatUpdated,
                                            newChat);
                                }
                            });
                        }
                    }
                }, null, true, RPCRequest.RPCRequestClassGeneric);
            } else {
                acceptingChats.remove(encryptedChat.id);
            }
        }
    }, null, true, RPCRequest.RPCRequestClassGeneric);
}

From source file:io.warp10.continuum.gts.GTSHelper.java

/**
 * Convert a GTS Id packed as a BigInteger into an array of bytes
 * containing classId/labelsId in big endian representation
 * @param bi//from w ww  . ja v a  2s  .  c  o  m
 * @return
 */
public static byte[] unpackGTSId(BigInteger bi) {
    byte[] bytes = bi.toByteArray();

    if (bytes.length < 16) {
        byte[] tmp = new byte[16];
        if (bi.signum() < 0) {
            Arrays.fill(tmp, (byte) 0xff);
        }
        System.arraycopy(bytes, 0, tmp, tmp.length - bytes.length, bytes.length);
        return tmp;
    } else {
        return bytes;
    }
}

From source file:com.viettel.hqmc.DAO.FilesDAO.java

private static OCSPReq generateOCSPRequest2(X509Certificate issuerCert, BigInteger serialNumber)
        throws Exception {

    //TODO: Have to check if this is OK with synapse implementation.
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber);
    OCSPReqGenerator generator = new OCSPReqGenerator();
    generator.addRequest(id);/*from w  ww . j  av  a 2  s.c  om*/
    BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
    Vector<ASN1ObjectIdentifier> objectIdentifiers = new Vector<ASN1ObjectIdentifier>();
    Vector<X509Extension> values = new Vector<X509Extension>();
    objectIdentifiers.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
    values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
    generator.setRequestExtensions(new X509Extensions(objectIdentifiers, values));
    return generator.generate();
}