Calculating distance between two vectors using Paillier homomorphic encryption I am basically trying to perform euclidean distance calculation in the encrypted domain (Paillier encryption). Using the homomorphic properties of Paillier, the squared euclidean distance formula can be written as (paper):

$\newcommand{\opn}{\operatorname}$
$$\underbrace{\opn{Enc}\left(\sum^d_{i=1}p_i^2\right)}_{\text{(I)}}\cdot \underbrace{\opn{Enc}\left(\sum^d_{i=1}q_i^2\right)}_{\text{(II)}}\cdot \underbrace{\prod^d_{i=1}\opn{Enc}(q_i)^{-2p_i}}_{\text{(III)}}$$

I tried implementing this in matlab using two sample vectors a and b but I seem to be getting a completely wrong distance when decrypted. The euclidean distance of the two vectors without encryption is 100.5883 but when applying the above formula and then decrypting the result I get 10118

%I'm using the variable precision integer toolbox (vpi) to handle large numbers in Matlab
a = [10, 58, 23, 59, 78, 11];
b = [87, 15, 12, 32, 41, 22];

p = 708481;
q = 708497;
r = 461563;

n = p * q;

% calculating (I) from above equation, i.e. a^2
encA =vpi(zeros(size(A))); %initialize vector for encrypted values
sumA = 0;

for i=1:length(A)
    encA(i) = PaillierEncrypt(A(i), p, q, random_r); %this will encrypt the value at index i in the vector
    sumA = sumA + (A(i))^2;
end

enc_sumA = PaillierEncrypt(sumA, p, q, random_r); %now encrypt the summed value



% below is for (II) and (III) in the equation i.e. b^2 -2ab
encB =vpi(zeros(size(B)));
sumB = 0;
enc_prodAB = vpi(1);

for i=1:length(B)
    encB(i) = PaillierEncrypt(B(i), p, q, random_r);
    sumB = sumB + (B(i))^2;

%the below block is to assist in determining the mod of a negative exponent, basically it allows for this to run without error: mod((encA)^(-2*vpi(B)), n*n);
    a2 = encA(i); %the encrypted base
    d2 = (-2)*vpi(B(i)); %the exponent that is a non encrypted scalar
    n3 = n*n;

    negpowermod = @(a,d,n2) minv(powermod(a,abs(d),n2),n2); 

    result = negpowermod(a2,d2,n3);

    enc_prodAB = enc_prodAB * result;
end

enc_sumB = PaillierEncrypt(sumB, p, q, random_r);

dist = enc_sumA * enc_sumB * enc_prodAB;


Ive commented the above code as best I could to explain what I am doing. I'm sure I messed up the implementation somehow. 

Some guidance would really be appreciated. Thanks
I don't see your problem.
10118 is indeed the square of the euclidian distance ~100.5883