1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.conscrypt;
18
19import java.math.BigInteger;
20import java.security.spec.ECPoint;
21
22final class OpenSSLECPointContext {
23    private final OpenSSLECGroupContext group;
24    private final long pointCtx;
25
26    OpenSSLECPointContext(OpenSSLECGroupContext group, long pointCtx) {
27        this.group = group;
28        this.pointCtx = pointCtx;
29    }
30
31    @Override
32    protected void finalize() throws Throwable {
33        try {
34            if (pointCtx != 0) {
35                NativeCrypto.EC_POINT_clear_free(pointCtx);
36            }
37        } finally {
38            super.finalize();
39        }
40    }
41
42    @Override
43    public boolean equals(Object o) {
44        if (!(o instanceof OpenSSLECPointContext)) {
45            return false;
46        }
47
48        final OpenSSLECPointContext other = (OpenSSLECPointContext) o;
49        if (!NativeCrypto.EC_GROUP_cmp(group.getContext(), other.group.getContext())) {
50            return false;
51        }
52
53        return NativeCrypto.EC_POINT_cmp(group.getContext(), pointCtx, other.pointCtx);
54    }
55
56    public ECPoint getECPoint() {
57        final byte[][] generatorCoords = NativeCrypto.EC_POINT_get_affine_coordinates(
58                group.getContext(), pointCtx);
59        final BigInteger x = new BigInteger(generatorCoords[0]);
60        final BigInteger y = new BigInteger(generatorCoords[1]);
61        return new ECPoint(x, y);
62    }
63
64    @Override
65    public int hashCode() {
66        // TODO Auto-generated method stub
67        return super.hashCode();
68    }
69
70    public long getContext() {
71        return pointCtx;
72    }
73
74    public static OpenSSLECPointContext getInstance(int curveType, OpenSSLECGroupContext group,
75            ECPoint javaPoint) {
76        OpenSSLECPointContext point = new OpenSSLECPointContext(group,
77                NativeCrypto.EC_POINT_new(group.getContext()));
78        NativeCrypto.EC_POINT_set_affine_coordinates(group.getContext(),
79                point.getContext(), javaPoint.getAffineX().toByteArray(),
80                javaPoint.getAffineY().toByteArray());
81        return point;
82    }
83}
84