OpenSSLDSAPublicKey.java revision 91bb5fbe55b854df891ff7720e30d42081dbcd58
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.apache.harmony.xnet.provider.jsse; 18 19import java.math.BigInteger; 20import java.security.InvalidKeyException; 21import java.security.interfaces.DSAParams; 22import java.security.interfaces.DSAPublicKey; 23import java.security.spec.DSAPublicKeySpec; 24import java.security.spec.InvalidKeySpecException; 25 26public class OpenSSLDSAPublicKey implements DSAPublicKey { 27 private final OpenSSLKey key; 28 29 private OpenSSLDSAParams params; 30 31 OpenSSLDSAPublicKey(OpenSSLKey key) { 32 this.key = key; 33 } 34 35 OpenSSLKey getOpenSSLKey() { 36 return key; 37 } 38 39 OpenSSLDSAPublicKey(DSAPublicKeySpec dsaKeySpec) throws InvalidKeySpecException { 40 try { 41 key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_DSA( 42 dsaKeySpec.getP().toByteArray(), 43 dsaKeySpec.getQ().toByteArray(), 44 dsaKeySpec.getG().toByteArray(), 45 dsaKeySpec.getY().toByteArray(), 46 null)); 47 } catch (Exception e) { 48 throw new InvalidKeySpecException(e); 49 } 50 } 51 52 private void ensureReadParams() { 53 if (params == null) { 54 params = new OpenSSLDSAParams(key); 55 } 56 } 57 58 static OpenSSLKey getInstance(DSAPublicKey dsaPublicKey) throws InvalidKeyException { 59 try { 60 final DSAParams dsaParams = dsaPublicKey.getParams(); 61 return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_DSA( 62 dsaParams.getP().toByteArray(), 63 dsaParams.getQ().toByteArray(), 64 dsaParams.getG().toByteArray(), 65 dsaPublicKey.getY().toByteArray(), 66 null)); 67 } catch (Exception e) { 68 throw new InvalidKeyException(e); 69 } 70 } 71 72 @Override 73 public DSAParams getParams() { 74 ensureReadParams(); 75 return params; 76 } 77 78 @Override 79 public String getAlgorithm() { 80 return "DSA"; 81 } 82 83 @Override 84 public String getFormat() { 85 return "X.509"; 86 } 87 88 @Override 89 public byte[] getEncoded() { 90 return NativeCrypto.i2d_PUBKEY(key.getPkeyContext()); 91 } 92 93 @Override 94 public BigInteger getY() { 95 ensureReadParams(); 96 return params.getY(); 97 } 98} 99