1 /* 2 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package sun.security.x509; 27 28 import java.io.BufferedReader; 29 import java.io.BufferedInputStream; 30 import java.io.ByteArrayOutputStream; 31 import java.io.IOException; 32 import java.io.InputStream; 33 import java.io.InputStreamReader; 34 import java.io.OutputStream; 35 import java.math.BigInteger; 36 import java.security.*; 37 import java.security.cert.*; 38 import java.security.cert.Certificate; 39 import java.util.*; 40 import java.util.concurrent.ConcurrentHashMap; 41 42 import javax.security.auth.x500.X500Principal; 43 44 import sun.misc.HexDumpEncoder; 45 import sun.misc.BASE64Decoder; 46 import sun.security.util.*; 47 import sun.security.provider.X509Factory; 48 49 /** 50 * The X509CertImpl class represents an X.509 certificate. These certificates 51 * are widely used to support authentication and other functionality in 52 * Internet security systems. Common applications include Privacy Enhanced 53 * Mail (PEM), Transport Layer Security (SSL), code signing for trusted 54 * software distribution, and Secure Electronic Transactions (SET). There 55 * is a commercial infrastructure ready to manage large scale deployments 56 * of X.509 identity certificates. 57 * 58 * <P>These certificates are managed and vouched for by <em>Certificate 59 * Authorities</em> (CAs). CAs are services which create certificates by 60 * placing data in the X.509 standard format and then digitally signing 61 * that data. Such signatures are quite difficult to forge. CAs act as 62 * trusted third parties, making introductions between agents who have no 63 * direct knowledge of each other. CA certificates are either signed by 64 * themselves, or by some other CA such as a "root" CA. 65 * 66 * <P>RFC 1422 is very informative, though it does not describe much 67 * of the recent work being done with X.509 certificates. That includes 68 * a 1996 version (X.509v3) and a variety of enhancements being made to 69 * facilitate an explosion of personal certificates used as "Internet 70 * Drivers' Licences", or with SET for credit card transactions. 71 * 72 * <P>More recent work includes the IETF PKIX Working Group efforts, 73 * especially RFC2459. 74 * 75 * @author Dave Brownell 76 * @author Amit Kapoor 77 * @author Hemma Prafullchandra 78 * @see X509CertInfo 79 */ 80 public class X509CertImpl extends X509Certificate implements DerEncoder { 81 82 private static final long serialVersionUID = -3457612960190864406L; 83 84 private static final String DOT = "."; 85 /** 86 * Public attribute names. 87 */ 88 public static final String NAME = "x509"; 89 public static final String INFO = X509CertInfo.NAME; 90 public static final String ALG_ID = "algorithm"; 91 public static final String SIGNATURE = "signature"; 92 public static final String SIGNED_CERT = "signed_cert"; 93 94 /** 95 * The following are defined for ease-of-use. These 96 * are the most frequently retrieved attributes. 97 */ 98 // x509.info.subject.dname 99 public static final String SUBJECT_DN = NAME + DOT + INFO + DOT + 100 X509CertInfo.SUBJECT + DOT + X509CertInfo.DN_NAME; 101 // x509.info.issuer.dname 102 public static final String ISSUER_DN = NAME + DOT + INFO + DOT + 103 X509CertInfo.ISSUER + DOT + X509CertInfo.DN_NAME; 104 // x509.info.serialNumber.number 105 public static final String SERIAL_ID = NAME + DOT + INFO + DOT + 106 X509CertInfo.SERIAL_NUMBER + DOT + 107 CertificateSerialNumber.NUMBER; 108 // x509.info.key.value 109 public static final String PUBLIC_KEY = NAME + DOT + INFO + DOT + 110 X509CertInfo.KEY + DOT + 111 CertificateX509Key.KEY; 112 113 // x509.info.version.value 114 public static final String VERSION = NAME + DOT + INFO + DOT + 115 X509CertInfo.VERSION + DOT + 116 CertificateVersion.VERSION; 117 118 // x509.algorithm 119 public static final String SIG_ALG = NAME + DOT + ALG_ID; 120 121 // x509.signature 122 public static final String SIG = NAME + DOT + SIGNATURE; 123 124 // when we sign and decode we set this to true 125 // this is our means to make certificates immutable 126 private boolean readOnly = false; 127 128 // Certificate data, and its envelope 129 private byte[] signedCert = null; 130 protected X509CertInfo info = null; 131 protected AlgorithmId algId = null; 132 protected byte[] signature = null; 133 134 // recognized extension OIDS 135 private static final String KEY_USAGE_OID = "2.5.29.15"; 136 private static final String EXTENDED_KEY_USAGE_OID = "2.5.29.37"; 137 private static final String BASIC_CONSTRAINT_OID = "2.5.29.19"; 138 private static final String SUBJECT_ALT_NAME_OID = "2.5.29.17"; 139 private static final String ISSUER_ALT_NAME_OID = "2.5.29.18"; 140 private static final String AUTH_INFO_ACCESS_OID = "1.3.6.1.5.5.7.1.1"; 141 142 // number of standard key usage bits. 143 private static final int NUM_STANDARD_KEY_USAGE = 9; 144 145 // SubjectAlterntativeNames cache 146 private Collection<List<?>> subjectAlternativeNames; 147 148 // IssuerAlternativeNames cache 149 private Collection<List<?>> issuerAlternativeNames; 150 151 // ExtendedKeyUsage cache 152 private List<String> extKeyUsage; 153 154 // AuthorityInformationAccess cache 155 private Set<AccessDescription> authInfoAccess; 156 157 /** 158 * PublicKey that has previously been used to verify 159 * the signature of this certificate. Null if the certificate has not 160 * yet been verified. 161 */ 162 private PublicKey verifiedPublicKey; 163 /** 164 * If verifiedPublicKey is not null, name of the provider used to 165 * successfully verify the signature of this certificate, or the 166 * empty String if no provider was explicitly specified. 167 */ 168 private String verifiedProvider; 169 /** 170 * If verifiedPublicKey is not null, result of the verification using 171 * verifiedPublicKey and verifiedProvider. If true, verification was 172 * successful, if false, it failed. 173 */ 174 private boolean verificationResult; 175 176 /** 177 * Default constructor. 178 */ 179 public X509CertImpl() { } 180 181 /** 182 * Unmarshals a certificate from its encoded form, parsing the 183 * encoded bytes. This form of constructor is used by agents which 184 * need to examine and use certificate contents. That is, this is 185 * one of the more commonly used constructors. Note that the buffer 186 * must include only a certificate, and no "garbage" may be left at 187 * the end. If you need to ignore data at the end of a certificate, 188 * use another constructor. 189 * 190 * @param certData the encoded bytes, with no trailing padding. 191 * @exception CertificateException on parsing and initialization errors. 192 */ 193 public X509CertImpl(byte[] certData) throws CertificateException { 194 try { 195 parse(new DerValue(certData)); 196 } catch (IOException e) { 197 signedCert = null; 198 throw new CertificateException("Unable to initialize, " + e, e); 199 } 200 } 201 202 /** 203 * unmarshals an X.509 certificate from an input stream. If the 204 * certificate is RFC1421 hex-encoded, then it must begin with 205 * the line X509Factory.BEGIN_CERT and end with the line 206 * X509Factory.END_CERT. 207 * 208 * @param in an input stream holding at least one certificate that may 209 * be either DER-encoded or RFC1421 hex-encoded version of the 210 * DER-encoded certificate. 211 * @exception CertificateException on parsing and initialization errors. 212 */ 213 public X509CertImpl(InputStream in) throws CertificateException { 214 215 DerValue der = null; 216 217 BufferedInputStream inBuffered = new BufferedInputStream(in); 218 219 // First try reading stream as HEX-encoded DER-encoded bytes, 220 // since not mistakable for raw DER 221 try { 222 inBuffered.mark(Integer.MAX_VALUE); 223 der = readRFC1421Cert(inBuffered); 224 } catch (IOException ioe) { 225 try { 226 // Next, try reading stream as raw DER-encoded bytes 227 inBuffered.reset(); 228 der = new DerValue(inBuffered); 229 } catch (IOException ioe1) { 230 throw new CertificateException("Input stream must be " + 231 "either DER-encoded bytes " + 232 "or RFC1421 hex-encoded " + 233 "DER-encoded bytes: " + 234 ioe1.getMessage(), ioe1); 235 } 236 } 237 try { 238 parse(der); 239 } catch (IOException ioe) { 240 signedCert = null; 241 throw new CertificateException("Unable to parse DER value of " + 242 "certificate, " + ioe, ioe); 243 } 244 } 245 246 /** 247 * read input stream as HEX-encoded DER-encoded bytes 248 * 249 * @param in InputStream to read 250 * @returns DerValue corresponding to decoded HEX-encoded bytes 251 * @throws IOException if stream can not be interpreted as RFC1421 252 * encoded bytes 253 */ 254 private DerValue readRFC1421Cert(InputStream in) throws IOException { 255 DerValue der = null; 256 String line = null; 257 BufferedReader certBufferedReader = 258 new BufferedReader(new InputStreamReader(in, "ASCII")); 259 try { 260 line = certBufferedReader.readLine(); 261 } catch (IOException ioe1) { 262 throw new IOException("Unable to read InputStream: " + 263 ioe1.getMessage()); 264 } 265 if (line.equals(X509Factory.BEGIN_CERT)) { 266 /* stream appears to be hex-encoded bytes */ 267 BASE64Decoder decoder = new BASE64Decoder(); 268 ByteArrayOutputStream decstream = new ByteArrayOutputStream(); 269 try { 270 while ((line = certBufferedReader.readLine()) != null) { 271 if (line.equals(X509Factory.END_CERT)) { 272 der = new DerValue(decstream.toByteArray()); 273 break; 274 } else { 275 decstream.write(decoder.decodeBuffer(line)); 276 } 277 } 278 } catch (IOException ioe2) { 279 throw new IOException("Unable to read InputStream: " 280 + ioe2.getMessage()); 281 } 282 } else { 283 throw new IOException("InputStream is not RFC1421 hex-encoded " + 284 "DER bytes"); 285 } 286 return der; 287 } 288 289 /** 290 * Construct an initialized X509 Certificate. The certificate is stored 291 * in raw form and has to be signed to be useful. 292 * 293 * @params info the X509CertificateInfo which the Certificate is to be 294 * created from. 295 */ 296 public X509CertImpl(X509CertInfo certInfo) { 297 this.info = certInfo; 298 } 299 300 /** 301 * Unmarshal a certificate from its encoded form, parsing a DER value. 302 * This form of constructor is used by agents which need to examine 303 * and use certificate contents. 304 * 305 * @param derVal the der value containing the encoded cert. 306 * @exception CertificateException on parsing and initialization errors. 307 */ 308 public X509CertImpl(DerValue derVal) throws CertificateException { 309 try { 310 parse(derVal); 311 } catch (IOException e) { 312 signedCert = null; 313 throw new CertificateException("Unable to initialize, " + e, e); 314 } 315 } 316 317 /** 318 * Unmarshal a certificate from its encoded form, parsing a DER value. 319 * This form of constructor is used by agents which need to examine 320 * and use certificate contents. 321 * 322 * @param derVal the der value containing the encoded cert. 323 * @exception CertificateException on parsing and initialization errors. 324 */ 325 public X509CertImpl(DerValue derVal, byte[] encoded) 326 throws CertificateException { 327 try { 328 parse(derVal, encoded); 329 } catch (IOException e) { 330 signedCert = null; 331 throw new CertificateException("Unable to initialize, " + e, e); 332 } 333 } 334 335 /** 336 * Appends the certificate to an output stream. 337 * 338 * @param out an input stream to which the certificate is appended. 339 * @exception CertificateEncodingException on encoding errors. 340 */ 341 public void encode(OutputStream out) 342 throws CertificateEncodingException { 343 if (signedCert == null) 344 throw new CertificateEncodingException( 345 "Null certificate to encode"); 346 try { 347 out.write(signedCert.clone()); 348 } catch (IOException e) { 349 throw new CertificateEncodingException(e.toString()); 350 } 351 } 352 353 /** 354 * DER encode this object onto an output stream. 355 * Implements the <code>DerEncoder</code> interface. 356 * 357 * @param out the output stream on which to write the DER encoding. 358 * 359 * @exception IOException on encoding error. 360 */ 361 public void derEncode(OutputStream out) throws IOException { 362 if (signedCert == null) 363 throw new IOException("Null certificate to encode"); 364 out.write(signedCert.clone()); 365 } 366 367 /** 368 * Returns the encoded form of this certificate. It is 369 * assumed that each certificate type would have only a single 370 * form of encoding; for example, X.509 certificates would 371 * be encoded as ASN.1 DER. 372 * 373 * @exception CertificateEncodingException if an encoding error occurs. 374 */ 375 public byte[] getEncoded() throws CertificateEncodingException { 376 return getEncodedInternal().clone(); 377 } 378 379 /** 380 * Returned the encoding as an uncloned byte array. Callers must 381 * guarantee that they neither modify it nor expose it to untrusted 382 * code. 383 */ 384 public byte[] getEncodedInternal() throws CertificateEncodingException { 385 if (signedCert == null) { 386 throw new CertificateEncodingException( 387 "Null certificate to encode"); 388 } 389 return signedCert; 390 } 391 392 /** 393 * Throws an exception if the certificate was not signed using the 394 * verification key provided. Successfully verifying a certificate 395 * does <em>not</em> indicate that one should trust the entity which 396 * it represents. 397 * 398 * @param key the public key used for verification. 399 * 400 * @exception InvalidKeyException on incorrect key. 401 * @exception NoSuchAlgorithmException on unsupported signature 402 * algorithms. 403 * @exception NoSuchProviderException if there's no default provider. 404 * @exception SignatureException on signature errors. 405 * @exception CertificateException on encoding errors. 406 */ 407 public void verify(PublicKey key) 408 throws CertificateException, NoSuchAlgorithmException, 409 InvalidKeyException, NoSuchProviderException, SignatureException { 410 411 verify(key, ""); 412 } 413 414 /** 415 * Throws an exception if the certificate was not signed using the 416 * verification key provided. Successfully verifying a certificate 417 * does <em>not</em> indicate that one should trust the entity which 418 * it represents. 419 * 420 * @param key the public key used for verification. 421 * @param sigProvider the name of the provider. 422 * 423 * @exception NoSuchAlgorithmException on unsupported signature 424 * algorithms. 425 * @exception InvalidKeyException on incorrect key. 426 * @exception NoSuchProviderException on incorrect provider. 427 * @exception SignatureException on signature errors. 428 * @exception CertificateException on encoding errors. 429 */ 430 public synchronized void verify(PublicKey key, String sigProvider) 431 throws CertificateException, NoSuchAlgorithmException, 432 InvalidKeyException, NoSuchProviderException, SignatureException { 433 if (sigProvider == null) { 434 sigProvider = ""; 435 } 436 if ((verifiedPublicKey != null) && verifiedPublicKey.equals(key)) { 437 // this certificate has already been verified using 438 // this public key. Make sure providers match, too. 439 if (sigProvider.equals(verifiedProvider)) { 440 if (verificationResult) { 441 return; 442 } else { 443 throw new SignatureException("Signature does not match."); 444 } 445 } 446 } 447 if (signedCert == null) { 448 throw new CertificateEncodingException("Uninitialized certificate"); 449 } 450 // Verify the signature ... 451 Signature sigVerf = null; 452 if (sigProvider.length() == 0) { 453 sigVerf = Signature.getInstance(algId.getName()); 454 } else { 455 sigVerf = Signature.getInstance(algId.getName(), sigProvider); 456 } 457 sigVerf.initVerify(key); 458 459 byte[] rawCert = info.getEncodedInfo(); 460 sigVerf.update(rawCert, 0, rawCert.length); 461 462 // verify may throw SignatureException for invalid encodings, etc. 463 verificationResult = sigVerf.verify(signature); 464 verifiedPublicKey = key; 465 verifiedProvider = sigProvider; 466 467 if (verificationResult == false) { 468 throw new SignatureException("Signature does not match."); 469 } 470 } 471 472 /** 473 * Throws an exception if the certificate was not signed using the 474 * verification key provided. This method uses the signature verification 475 * engine supplied by the specified provider. Note that the specified 476 * Provider object does not have to be registered in the provider list. 477 * Successfully verifying a certificate does <em>not</em> indicate that one 478 * should trust the entity which it represents. 479 * 480 * @param key the public key used for verification. 481 * @param sigProvider the provider. 482 * 483 * @exception NoSuchAlgorithmException on unsupported signature 484 * algorithms. 485 * @exception InvalidKeyException on incorrect key. 486 * @exception SignatureException on signature errors. 487 * @exception CertificateException on encoding errors. 488 */ 489 public synchronized void verify(PublicKey key, Provider sigProvider) 490 throws CertificateException, NoSuchAlgorithmException, 491 InvalidKeyException, SignatureException { 492 if (signedCert == null) { 493 throw new CertificateEncodingException("Uninitialized certificate"); 494 } 495 // Verify the signature ... 496 Signature sigVerf = null; 497 if (sigProvider == null) { 498 sigVerf = Signature.getInstance(algId.getName()); 499 } else { 500 sigVerf = Signature.getInstance(algId.getName(), sigProvider); 501 } 502 sigVerf.initVerify(key); 503 504 byte[] rawCert = info.getEncodedInfo(); 505 sigVerf.update(rawCert, 0, rawCert.length); 506 507 // verify may throw SignatureException for invalid encodings, etc. 508 verificationResult = sigVerf.verify(signature); 509 verifiedPublicKey = key; 510 511 if (verificationResult == false) { 512 throw new SignatureException("Signature does not match."); 513 } 514 } 515 516 /** 517 * This static method is the default implementation of the 518 * verify(PublicKey key, Provider sigProvider) method in X509Certificate. 519 * Called from java.security.cert.X509Certificate.verify(PublicKey key, 520 * Provider sigProvider) 521 */ 522 public static void verify(X509Certificate cert, PublicKey key, 523 Provider sigProvider) throws CertificateException, 524 NoSuchAlgorithmException, InvalidKeyException, SignatureException { 525 cert.verify(key, sigProvider); 526 } 527 528 /** 529 * Creates an X.509 certificate, and signs it using the given key 530 * (associating a signature algorithm and an X.500 name). 531 * This operation is used to implement the certificate generation 532 * functionality of a certificate authority. 533 * 534 * @param key the private key used for signing. 535 * @param algorithm the name of the signature algorithm used. 536 * 537 * @exception InvalidKeyException on incorrect key. 538 * @exception NoSuchAlgorithmException on unsupported signature 539 * algorithms. 540 * @exception NoSuchProviderException if there's no default provider. 541 * @exception SignatureException on signature errors. 542 * @exception CertificateException on encoding errors. 543 */ 544 public void sign(PrivateKey key, String algorithm) 545 throws CertificateException, NoSuchAlgorithmException, 546 InvalidKeyException, NoSuchProviderException, SignatureException { 547 sign(key, algorithm, null); 548 } 549 550 /** 551 * Creates an X.509 certificate, and signs it using the given key 552 * (associating a signature algorithm and an X.500 name). 553 * This operation is used to implement the certificate generation 554 * functionality of a certificate authority. 555 * 556 * @param key the private key used for signing. 557 * @param algorithm the name of the signature algorithm used. 558 * @param provider the name of the provider. 559 * 560 * @exception NoSuchAlgorithmException on unsupported signature 561 * algorithms. 562 * @exception InvalidKeyException on incorrect key. 563 * @exception NoSuchProviderException on incorrect provider. 564 * @exception SignatureException on signature errors. 565 * @exception CertificateException on encoding errors. 566 */ 567 public void sign(PrivateKey key, String algorithm, String provider) 568 throws CertificateException, NoSuchAlgorithmException, 569 InvalidKeyException, NoSuchProviderException, SignatureException { 570 try { 571 if (readOnly) 572 throw new CertificateEncodingException( 573 "cannot over-write existing certificate"); 574 Signature sigEngine = null; 575 if ((provider == null) || (provider.length() == 0)) 576 sigEngine = Signature.getInstance(algorithm); 577 else 578 sigEngine = Signature.getInstance(algorithm, provider); 579 580 sigEngine.initSign(key); 581 582 // in case the name is reset 583 algId = AlgorithmId.get(sigEngine.getAlgorithm()); 584 585 DerOutputStream out = new DerOutputStream(); 586 DerOutputStream tmp = new DerOutputStream(); 587 588 // encode certificate info 589 info.encode(tmp); 590 byte[] rawCert = tmp.toByteArray(); 591 592 // encode algorithm identifier 593 algId.encode(tmp); 594 595 // Create and encode the signature itself. 596 sigEngine.update(rawCert, 0, rawCert.length); 597 signature = sigEngine.sign(); 598 tmp.putBitString(signature); 599 600 // Wrap the signed data in a SEQUENCE { data, algorithm, sig } 601 out.write(DerValue.tag_Sequence, tmp); 602 signedCert = out.toByteArray(); 603 readOnly = true; 604 605 } catch (IOException e) { 606 throw new CertificateEncodingException(e.toString()); 607 } 608 } 609 610 /** 611 * Checks that the certificate is currently valid, i.e. the current 612 * time is within the specified validity period. 613 * 614 * @exception CertificateExpiredException if the certificate has expired. 615 * @exception CertificateNotYetValidException if the certificate is not 616 * yet valid. 617 */ 618 public void checkValidity() 619 throws CertificateExpiredException, CertificateNotYetValidException { 620 Date date = new Date(); 621 checkValidity(date); 622 } 623 624 /** 625 * Checks that the specified date is within the certificate's 626 * validity period, or basically if the certificate would be 627 * valid at the specified date/time. 628 * 629 * @param date the Date to check against to see if this certificate 630 * is valid at that date/time. 631 * 632 * @exception CertificateExpiredException if the certificate has expired 633 * with respect to the <code>date</code> supplied. 634 * @exception CertificateNotYetValidException if the certificate is not 635 * yet valid with respect to the <code>date</code> supplied. 636 */ 637 public void checkValidity(Date date) 638 throws CertificateExpiredException, CertificateNotYetValidException { 639 640 CertificateValidity interval = null; 641 try { 642 interval = (CertificateValidity)info.get(CertificateValidity.NAME); 643 } catch (Exception e) { 644 throw new CertificateNotYetValidException("Incorrect validity period"); 645 } 646 if (interval == null) 647 throw new CertificateNotYetValidException("Null validity period"); 648 interval.valid(date); 649 } 650 651 /** 652 * Return the requested attribute from the certificate. 653 * 654 * Note that the X509CertInfo is not cloned for performance reasons. 655 * Callers must ensure that they do not modify it. All other 656 * attributes are cloned. 657 * 658 * @param name the name of the attribute. 659 * @exception CertificateParsingException on invalid attribute identifier. 660 */ 661 public Object get(String name) 662 throws CertificateParsingException { 663 X509AttributeName attr = new X509AttributeName(name); 664 String id = attr.getPrefix(); 665 if (!(id.equalsIgnoreCase(NAME))) { 666 throw new CertificateParsingException("Invalid root of " 667 + "attribute name, expected [" + NAME + 668 "], received " + "[" + id + "]"); 669 } 670 attr = new X509AttributeName(attr.getSuffix()); 671 id = attr.getPrefix(); 672 673 if (id.equalsIgnoreCase(INFO)) { 674 if (info == null) { 675 return null; 676 } 677 if (attr.getSuffix() != null) { 678 try { 679 return info.get(attr.getSuffix()); 680 } catch (IOException e) { 681 throw new CertificateParsingException(e.toString()); 682 } catch (CertificateException e) { 683 throw new CertificateParsingException(e.toString()); 684 } 685 } else { 686 return info; 687 } 688 } else if (id.equalsIgnoreCase(ALG_ID)) { 689 return(algId); 690 } else if (id.equalsIgnoreCase(SIGNATURE)) { 691 if (signature != null) 692 return signature.clone(); 693 else 694 return null; 695 } else if (id.equalsIgnoreCase(SIGNED_CERT)) { 696 if (signedCert != null) 697 return signedCert.clone(); 698 else 699 return null; 700 } else { 701 throw new CertificateParsingException("Attribute name not " 702 + "recognized or get() not allowed for the same: " + id); 703 } 704 } 705 706 /** 707 * Set the requested attribute in the certificate. 708 * 709 * @param name the name of the attribute. 710 * @param obj the value of the attribute. 711 * @exception CertificateException on invalid attribute identifier. 712 * @exception IOException on encoding error of attribute. 713 */ 714 public void set(String name, Object obj) 715 throws CertificateException, IOException { 716 // check if immutable 717 if (readOnly) 718 throw new CertificateException("cannot over-write existing" 719 + " certificate"); 720 721 X509AttributeName attr = new X509AttributeName(name); 722 String id = attr.getPrefix(); 723 if (!(id.equalsIgnoreCase(NAME))) { 724 throw new CertificateException("Invalid root of attribute name," 725 + " expected [" + NAME + "], received " + id); 726 } 727 attr = new X509AttributeName(attr.getSuffix()); 728 id = attr.getPrefix(); 729 730 if (id.equalsIgnoreCase(INFO)) { 731 if (attr.getSuffix() == null) { 732 if (!(obj instanceof X509CertInfo)) { 733 throw new CertificateException("Attribute value should" 734 + " be of type X509CertInfo."); 735 } 736 info = (X509CertInfo)obj; 737 signedCert = null; //reset this as certificate data has changed 738 } else { 739 info.set(attr.getSuffix(), obj); 740 signedCert = null; //reset this as certificate data has changed 741 } 742 } else { 743 throw new CertificateException("Attribute name not recognized or " + 744 "set() not allowed for the same: " + id); 745 } 746 } 747 748 /** 749 * Delete the requested attribute from the certificate. 750 * 751 * @param name the name of the attribute. 752 * @exception CertificateException on invalid attribute identifier. 753 * @exception IOException on other errors. 754 */ 755 public void delete(String name) 756 throws CertificateException, IOException { 757 // check if immutable 758 if (readOnly) 759 throw new CertificateException("cannot over-write existing" 760 + " certificate"); 761 762 X509AttributeName attr = new X509AttributeName(name); 763 String id = attr.getPrefix(); 764 if (!(id.equalsIgnoreCase(NAME))) { 765 throw new CertificateException("Invalid root of attribute name," 766 + " expected [" 767 + NAME + "], received " + id); 768 } 769 attr = new X509AttributeName(attr.getSuffix()); 770 id = attr.getPrefix(); 771 772 if (id.equalsIgnoreCase(INFO)) { 773 if (attr.getSuffix() != null) { 774 info = null; 775 } else { 776 info.delete(attr.getSuffix()); 777 } 778 } else if (id.equalsIgnoreCase(ALG_ID)) { 779 algId = null; 780 } else if (id.equalsIgnoreCase(SIGNATURE)) { 781 signature = null; 782 } else if (id.equalsIgnoreCase(SIGNED_CERT)) { 783 signedCert = null; 784 } else { 785 throw new CertificateException("Attribute name not recognized or " + 786 "delete() not allowed for the same: " + id); 787 } 788 } 789 790 /** 791 * Return an enumeration of names of attributes existing within this 792 * attribute. 793 */ 794 public Enumeration<String> getElements() { 795 AttributeNameEnumeration elements = new AttributeNameEnumeration(); 796 elements.addElement(NAME + DOT + INFO); 797 elements.addElement(NAME + DOT + ALG_ID); 798 elements.addElement(NAME + DOT + SIGNATURE); 799 elements.addElement(NAME + DOT + SIGNED_CERT); 800 801 return elements.elements(); 802 } 803 804 /** 805 * Return the name of this attribute. 806 */ 807 public String getName() { 808 return(NAME); 809 } 810 811 /** 812 * Returns a printable representation of the certificate. This does not 813 * contain all the information available to distinguish this from any 814 * other certificate. The certificate must be fully constructed 815 * before this function may be called. 816 */ 817 public String toString() { 818 if (info == null || algId == null || signature == null) 819 return ""; 820 821 StringBuilder sb = new StringBuilder(); 822 823 sb.append("[\n"); 824 sb.append(info.toString() + "\n"); 825 sb.append(" Algorithm: [" + algId.toString() + "]\n"); 826 827 HexDumpEncoder encoder = new HexDumpEncoder(); 828 sb.append(" Signature:\n" + encoder.encodeBuffer(signature)); 829 sb.append("\n]"); 830 831 return sb.toString(); 832 } 833 834 // the strongly typed gets, as per java.security.cert.X509Certificate 835 836 /** 837 * Gets the publickey from this certificate. 838 * 839 * @return the publickey. 840 */ 841 public PublicKey getPublicKey() { 842 if (info == null) 843 return null; 844 try { 845 PublicKey key = (PublicKey)info.get(CertificateX509Key.NAME 846 + DOT + CertificateX509Key.KEY); 847 return key; 848 } catch (Exception e) { 849 return null; 850 } 851 } 852 853 /** 854 * Gets the version number from the certificate. 855 * 856 * @return the version number, i.e. 1, 2 or 3. 857 */ 858 public int getVersion() { 859 if (info == null) 860 return -1; 861 try { 862 int vers = ((Integer)info.get(CertificateVersion.NAME 863 + DOT + CertificateVersion.VERSION)).intValue(); 864 return vers+1; 865 } catch (Exception e) { 866 return -1; 867 } 868 } 869 870 /** 871 * Gets the serial number from the certificate. 872 * 873 * @return the serial number. 874 */ 875 public BigInteger getSerialNumber() { 876 SerialNumber ser = getSerialNumberObject(); 877 878 return ser != null ? ser.getNumber() : null; 879 } 880 881 /** 882 * Gets the serial number from the certificate as 883 * a SerialNumber object. 884 * 885 * @return the serial number. 886 */ 887 public SerialNumber getSerialNumberObject() { 888 if (info == null) 889 return null; 890 try { 891 SerialNumber ser = (SerialNumber)info.get( 892 CertificateSerialNumber.NAME + DOT + 893 CertificateSerialNumber.NUMBER); 894 return ser; 895 } catch (Exception e) { 896 return null; 897 } 898 } 899 900 901 /** 902 * Gets the subject distinguished name from the certificate. 903 * 904 * @return the subject name. 905 */ 906 public Principal getSubjectDN() { 907 if (info == null) 908 return null; 909 try { 910 Principal subject = (Principal)info.get(X509CertInfo.SUBJECT + DOT + 911 X509CertInfo.DN_NAME); 912 return subject; 913 } catch (Exception e) { 914 return null; 915 } 916 } 917 918 /** 919 * Get subject name as X500Principal. Overrides implementation in 920 * X509Certificate with a slightly more efficient version that is 921 * also aware of X509CertImpl mutability. 922 */ 923 public X500Principal getSubjectX500Principal() { 924 if (info == null) { 925 return null; 926 } 927 try { 928 X500Principal subject = (X500Principal)info.get( 929 X509CertInfo.SUBJECT + DOT + 930 "x500principal"); 931 return subject; 932 } catch (Exception e) { 933 return null; 934 } 935 } 936 937 /** 938 * Gets the issuer distinguished name from the certificate. 939 * 940 * @return the issuer name. 941 */ 942 public Principal getIssuerDN() { 943 if (info == null) 944 return null; 945 try { 946 Principal issuer = (Principal)info.get(X509CertInfo.ISSUER + DOT + 947 X509CertInfo.DN_NAME); 948 return issuer; 949 } catch (Exception e) { 950 return null; 951 } 952 } 953 954 /** 955 * Get issuer name as X500Principal. Overrides implementation in 956 * X509Certificate with a slightly more efficient version that is 957 * also aware of X509CertImpl mutability. 958 */ 959 public X500Principal getIssuerX500Principal() { 960 if (info == null) { 961 return null; 962 } 963 try { 964 X500Principal issuer = (X500Principal)info.get( 965 X509CertInfo.ISSUER + DOT + 966 "x500principal"); 967 return issuer; 968 } catch (Exception e) { 969 return null; 970 } 971 } 972 973 /** 974 * Gets the notBefore date from the validity period of the certificate. 975 * 976 * @return the start date of the validity period. 977 */ 978 public Date getNotBefore() { 979 if (info == null) 980 return null; 981 try { 982 Date d = (Date) info.get(CertificateValidity.NAME + DOT + 983 CertificateValidity.NOT_BEFORE); 984 return d; 985 } catch (Exception e) { 986 return null; 987 } 988 } 989 990 /** 991 * Gets the notAfter date from the validity period of the certificate. 992 * 993 * @return the end date of the validity period. 994 */ 995 public Date getNotAfter() { 996 if (info == null) 997 return null; 998 try { 999 Date d = (Date) info.get(CertificateValidity.NAME + DOT + 1000 CertificateValidity.NOT_AFTER); 1001 return d; 1002 } catch (Exception e) { 1003 return null; 1004 } 1005 } 1006 1007 /** 1008 * Gets the DER encoded certificate informations, the 1009 * <code>tbsCertificate</code> from this certificate. 1010 * This can be used to verify the signature independently. 1011 * 1012 * @return the DER encoded certificate information. 1013 * @exception CertificateEncodingException if an encoding error occurs. 1014 */ 1015 public byte[] getTBSCertificate() throws CertificateEncodingException { 1016 if (info != null) { 1017 return info.getEncodedInfo(); 1018 } else 1019 throw new CertificateEncodingException("Uninitialized certificate"); 1020 } 1021 1022 /** 1023 * Gets the raw Signature bits from the certificate. 1024 * 1025 * @return the signature. 1026 */ 1027 public byte[] getSignature() { 1028 if (signature == null) 1029 return null; 1030 byte[] dup = new byte[signature.length]; 1031 System.arraycopy(signature, 0, dup, 0, dup.length); 1032 return dup; 1033 } 1034 1035 /** 1036 * Gets the signature algorithm name for the certificate 1037 * signature algorithm. 1038 * For example, the string "SHA-1/DSA" or "DSS". 1039 * 1040 * @return the signature algorithm name. 1041 */ 1042 public String getSigAlgName() { 1043 if (algId == null) 1044 return null; 1045 return (algId.getName()); 1046 } 1047 1048 /** 1049 * Gets the signature algorithm OID string from the certificate. 1050 * For example, the string "1.2.840.10040.4.3" 1051 * 1052 * @return the signature algorithm oid string. 1053 */ 1054 public String getSigAlgOID() { 1055 if (algId == null) 1056 return null; 1057 ObjectIdentifier oid = algId.getOID(); 1058 return (oid.toString()); 1059 } 1060 1061 /** 1062 * Gets the DER encoded signature algorithm parameters from this 1063 * certificate's signature algorithm. 1064 * 1065 * @return the DER encoded signature algorithm parameters, or 1066 * null if no parameters are present. 1067 */ 1068 public byte[] getSigAlgParams() { 1069 if (algId == null) 1070 return null; 1071 try { 1072 return algId.getEncodedParams(); 1073 } catch (IOException e) { 1074 return null; 1075 } 1076 } 1077 1078 /** 1079 * Gets the Issuer Unique Identity from the certificate. 1080 * 1081 * @return the Issuer Unique Identity. 1082 */ 1083 public boolean[] getIssuerUniqueID() { 1084 if (info == null) 1085 return null; 1086 try { 1087 UniqueIdentity id = (UniqueIdentity)info.get( 1088 X509CertInfo.ISSUER_ID); 1089 if (id == null) 1090 return null; 1091 else 1092 return (id.getId()); 1093 } catch (Exception e) { 1094 return null; 1095 } 1096 } 1097 1098 /** 1099 * Gets the Subject Unique Identity from the certificate. 1100 * 1101 * @return the Subject Unique Identity. 1102 */ 1103 public boolean[] getSubjectUniqueID() { 1104 if (info == null) 1105 return null; 1106 try { 1107 UniqueIdentity id = (UniqueIdentity)info.get( 1108 X509CertInfo.SUBJECT_ID); 1109 if (id == null) 1110 return null; 1111 else 1112 return (id.getId()); 1113 } catch (Exception e) { 1114 return null; 1115 } 1116 } 1117 1118 public KeyIdentifier getAuthKeyId() { 1119 AuthorityKeyIdentifierExtension aki 1120 = getAuthorityKeyIdentifierExtension(); 1121 if (aki != null) { 1122 try { 1123 return (KeyIdentifier)aki.get( 1124 AuthorityKeyIdentifierExtension.KEY_ID); 1125 } catch (IOException ioe) {} // not possible 1126 } 1127 return null; 1128 } 1129 1130 /** 1131 * Returns the subject's key identifier, or null 1132 */ 1133 public KeyIdentifier getSubjectKeyId() { 1134 SubjectKeyIdentifierExtension ski = getSubjectKeyIdentifierExtension(); 1135 if (ski != null) { 1136 try { 1137 return (KeyIdentifier)ski.get( 1138 SubjectKeyIdentifierExtension.KEY_ID); 1139 } catch (IOException ioe) {} // not possible 1140 } 1141 return null; 1142 } 1143 1144 /** 1145 * Get AuthorityKeyIdentifier extension 1146 * @return AuthorityKeyIdentifier object or null (if no such object 1147 * in certificate) 1148 */ 1149 public AuthorityKeyIdentifierExtension getAuthorityKeyIdentifierExtension() 1150 { 1151 return (AuthorityKeyIdentifierExtension) 1152 getExtension(PKIXExtensions.AuthorityKey_Id); 1153 } 1154 1155 /** 1156 * Get BasicConstraints extension 1157 * @return BasicConstraints object or null (if no such object in 1158 * certificate) 1159 */ 1160 public BasicConstraintsExtension getBasicConstraintsExtension() { 1161 return (BasicConstraintsExtension) 1162 getExtension(PKIXExtensions.BasicConstraints_Id); 1163 } 1164 1165 /** 1166 * Get CertificatePoliciesExtension 1167 * @return CertificatePoliciesExtension or null (if no such object in 1168 * certificate) 1169 */ 1170 public CertificatePoliciesExtension getCertificatePoliciesExtension() { 1171 return (CertificatePoliciesExtension) 1172 getExtension(PKIXExtensions.CertificatePolicies_Id); 1173 } 1174 1175 /** 1176 * Get ExtendedKeyUsage extension 1177 * @return ExtendedKeyUsage extension object or null (if no such object 1178 * in certificate) 1179 */ 1180 public ExtendedKeyUsageExtension getExtendedKeyUsageExtension() { 1181 return (ExtendedKeyUsageExtension) 1182 getExtension(PKIXExtensions.ExtendedKeyUsage_Id); 1183 } 1184 1185 /** 1186 * Get IssuerAlternativeName extension 1187 * @return IssuerAlternativeName object or null (if no such object in 1188 * certificate) 1189 */ 1190 public IssuerAlternativeNameExtension getIssuerAlternativeNameExtension() { 1191 return (IssuerAlternativeNameExtension) 1192 getExtension(PKIXExtensions.IssuerAlternativeName_Id); 1193 } 1194 1195 /** 1196 * Get NameConstraints extension 1197 * @return NameConstraints object or null (if no such object in certificate) 1198 */ 1199 public NameConstraintsExtension getNameConstraintsExtension() { 1200 return (NameConstraintsExtension) 1201 getExtension(PKIXExtensions.NameConstraints_Id); 1202 } 1203 1204 /** 1205 * Get PolicyConstraints extension 1206 * @return PolicyConstraints object or null (if no such object in 1207 * certificate) 1208 */ 1209 public PolicyConstraintsExtension getPolicyConstraintsExtension() { 1210 return (PolicyConstraintsExtension) 1211 getExtension(PKIXExtensions.PolicyConstraints_Id); 1212 } 1213 1214 /** 1215 * Get PolicyMappingsExtension extension 1216 * @return PolicyMappingsExtension object or null (if no such object 1217 * in certificate) 1218 */ 1219 public PolicyMappingsExtension getPolicyMappingsExtension() { 1220 return (PolicyMappingsExtension) 1221 getExtension(PKIXExtensions.PolicyMappings_Id); 1222 } 1223 1224 /** 1225 * Get PrivateKeyUsage extension 1226 * @return PrivateKeyUsage object or null (if no such object in certificate) 1227 */ 1228 public PrivateKeyUsageExtension getPrivateKeyUsageExtension() { 1229 return (PrivateKeyUsageExtension) 1230 getExtension(PKIXExtensions.PrivateKeyUsage_Id); 1231 } 1232 1233 /** 1234 * Get SubjectAlternativeName extension 1235 * @return SubjectAlternativeName object or null (if no such object in 1236 * certificate) 1237 */ 1238 public SubjectAlternativeNameExtension getSubjectAlternativeNameExtension() 1239 { 1240 return (SubjectAlternativeNameExtension) 1241 getExtension(PKIXExtensions.SubjectAlternativeName_Id); 1242 } 1243 1244 /** 1245 * Get SubjectKeyIdentifier extension 1246 * @return SubjectKeyIdentifier object or null (if no such object in 1247 * certificate) 1248 */ 1249 public SubjectKeyIdentifierExtension getSubjectKeyIdentifierExtension() { 1250 return (SubjectKeyIdentifierExtension) 1251 getExtension(PKIXExtensions.SubjectKey_Id); 1252 } 1253 1254 /** 1255 * Get CRLDistributionPoints extension 1256 * @return CRLDistributionPoints object or null (if no such object in 1257 * certificate) 1258 */ 1259 public CRLDistributionPointsExtension getCRLDistributionPointsExtension() { 1260 return (CRLDistributionPointsExtension) 1261 getExtension(PKIXExtensions.CRLDistributionPoints_Id); 1262 } 1263 1264 /** 1265 * Return true if a critical extension is found that is 1266 * not supported, otherwise return false. 1267 */ 1268 public boolean hasUnsupportedCriticalExtension() { 1269 if (info == null) 1270 return false; 1271 try { 1272 CertificateExtensions exts = (CertificateExtensions)info.get( 1273 CertificateExtensions.NAME); 1274 if (exts == null) 1275 return false; 1276 return exts.hasUnsupportedCriticalExtension(); 1277 } catch (Exception e) { 1278 return false; 1279 } 1280 } 1281 1282 /** 1283 * Gets a Set of the extension(s) marked CRITICAL in the 1284 * certificate. In the returned set, each extension is 1285 * represented by its OID string. 1286 * 1287 * @return a set of the extension oid strings in the 1288 * certificate that are marked critical. 1289 */ 1290 public Set<String> getCriticalExtensionOIDs() { 1291 if (info == null) { 1292 return null; 1293 } 1294 try { 1295 CertificateExtensions exts = (CertificateExtensions)info.get( 1296 CertificateExtensions.NAME); 1297 if (exts == null) { 1298 return null; 1299 } 1300 Set<String> extSet = new TreeSet<>(); 1301 for (Extension ex : exts.getAllExtensions()) { 1302 if (ex.isCritical()) { 1303 extSet.add(ex.getExtensionId().toString()); 1304 } 1305 } 1306 return extSet; 1307 } catch (Exception e) { 1308 return null; 1309 } 1310 } 1311 1312 /** 1313 * Gets a Set of the extension(s) marked NON-CRITICAL in the 1314 * certificate. In the returned set, each extension is 1315 * represented by its OID string. 1316 * 1317 * @return a set of the extension oid strings in the 1318 * certificate that are NOT marked critical. 1319 */ 1320 public Set<String> getNonCriticalExtensionOIDs() { 1321 if (info == null) { 1322 return null; 1323 } 1324 try { 1325 CertificateExtensions exts = (CertificateExtensions)info.get( 1326 CertificateExtensions.NAME); 1327 if (exts == null) { 1328 return null; 1329 } 1330 Set<String> extSet = new TreeSet<>(); 1331 for (Extension ex : exts.getAllExtensions()) { 1332 if (!ex.isCritical()) { 1333 extSet.add(ex.getExtensionId().toString()); 1334 } 1335 } 1336 extSet.addAll(exts.getUnparseableExtensions().keySet()); 1337 return extSet; 1338 } catch (Exception e) { 1339 return null; 1340 } 1341 } 1342 1343 /** 1344 * Gets the extension identified by the given ObjectIdentifier 1345 * 1346 * @param oid the Object Identifier value for the extension. 1347 * @return Extension or null if certificate does not contain this 1348 * extension 1349 */ 1350 public Extension getExtension(ObjectIdentifier oid) { 1351 if (info == null) { 1352 return null; 1353 } 1354 try { 1355 CertificateExtensions extensions; 1356 try { 1357 extensions = (CertificateExtensions)info.get(CertificateExtensions.NAME); 1358 } catch (CertificateException ce) { 1359 return null; 1360 } 1361 if (extensions == null) { 1362 return null; 1363 } else { 1364 Extension ex = extensions.getExtension(oid.toString()); 1365 if (ex != null) { 1366 return ex; 1367 } 1368 for (Extension ex2: extensions.getAllExtensions()) { 1369 if (ex2.getExtensionId().equals((Object)oid)) { 1370 //XXXX May want to consider cloning this 1371 return ex2; 1372 } 1373 } 1374 /* no such extension in this certificate */ 1375 return null; 1376 } 1377 } catch (IOException ioe) { 1378 return null; 1379 } 1380 } 1381 1382 public Extension getUnparseableExtension(ObjectIdentifier oid) { 1383 if (info == null) { 1384 return null; 1385 } 1386 try { 1387 CertificateExtensions extensions; 1388 try { 1389 extensions = (CertificateExtensions)info.get(CertificateExtensions.NAME); 1390 } catch (CertificateException ce) { 1391 return null; 1392 } 1393 if (extensions == null) { 1394 return null; 1395 } else { 1396 return extensions.getUnparseableExtensions().get(oid.toString()); 1397 } 1398 } catch (IOException ioe) { 1399 return null; 1400 } 1401 } 1402 1403 /** 1404 * Gets the DER encoded extension identified by the given 1405 * oid String. 1406 * 1407 * @param oid the Object Identifier value for the extension. 1408 */ 1409 public byte[] getExtensionValue(String oid) { 1410 try { 1411 ObjectIdentifier findOID = new ObjectIdentifier(oid); 1412 String extAlias = OIDMap.getName(findOID); 1413 Extension certExt = null; 1414 CertificateExtensions exts = (CertificateExtensions)info.get( 1415 CertificateExtensions.NAME); 1416 1417 if (extAlias == null) { // may be unknown 1418 // get the extensions, search thru' for this oid 1419 if (exts == null) { 1420 return null; 1421 } 1422 1423 for (Extension ex : exts.getAllExtensions()) { 1424 ObjectIdentifier inCertOID = ex.getExtensionId(); 1425 if (inCertOID.equals((Object)findOID)) { 1426 certExt = ex; 1427 break; 1428 } 1429 } 1430 } else { // there's sub-class that can handle this extension 1431 try { 1432 certExt = (Extension)this.get(extAlias); 1433 } catch (CertificateException e) { 1434 // get() throws an Exception instead of returning null, ignore 1435 } 1436 } 1437 if (certExt == null) { 1438 if (exts != null) { 1439 certExt = exts.getUnparseableExtensions().get(oid); 1440 } 1441 if (certExt == null) { 1442 return null; 1443 } 1444 } 1445 byte[] extData = certExt.getExtensionValue(); 1446 if (extData == null) { 1447 return null; 1448 } 1449 DerOutputStream out = new DerOutputStream(); 1450 out.putOctetString(extData); 1451 return out.toByteArray(); 1452 } catch (Exception e) { 1453 return null; 1454 } 1455 } 1456 1457 /** 1458 * Get a boolean array representing the bits of the KeyUsage extension, 1459 * (oid = 2.5.29.15). 1460 * @return the bit values of this extension as an array of booleans. 1461 */ 1462 public boolean[] getKeyUsage() { 1463 try { 1464 String extAlias = OIDMap.getName(PKIXExtensions.KeyUsage_Id); 1465 if (extAlias == null) 1466 return null; 1467 1468 KeyUsageExtension certExt = (KeyUsageExtension)this.get(extAlias); 1469 if (certExt == null) 1470 return null; 1471 1472 boolean[] ret = certExt.getBits(); 1473 if (ret.length < NUM_STANDARD_KEY_USAGE) { 1474 boolean[] usageBits = new boolean[NUM_STANDARD_KEY_USAGE]; 1475 System.arraycopy(ret, 0, usageBits, 0, ret.length); 1476 ret = usageBits; 1477 } 1478 return ret; 1479 } catch (Exception e) { 1480 return null; 1481 } 1482 } 1483 1484 /** 1485 * This method are the overridden implementation of 1486 * getExtendedKeyUsage method in X509Certificate in the Sun 1487 * provider. It is better performance-wise since it returns cached 1488 * values. 1489 */ 1490 public synchronized List<String> getExtendedKeyUsage() 1491 throws CertificateParsingException { 1492 if (readOnly && extKeyUsage != null) { 1493 return extKeyUsage; 1494 } else { 1495 ExtendedKeyUsageExtension ext = getExtendedKeyUsageExtension(); 1496 if (ext == null) { 1497 return null; 1498 } 1499 extKeyUsage = 1500 Collections.unmodifiableList(ext.getExtendedKeyUsage()); 1501 return extKeyUsage; 1502 } 1503 } 1504 1505 /** 1506 * This static method is the default implementation of the 1507 * getExtendedKeyUsage method in X509Certificate. A 1508 * X509Certificate provider generally should overwrite this to 1509 * provide among other things caching for better performance. 1510 */ 1511 public static List<String> getExtendedKeyUsage(X509Certificate cert) 1512 throws CertificateParsingException { 1513 try { 1514 byte[] ext = cert.getExtensionValue(EXTENDED_KEY_USAGE_OID); 1515 if (ext == null) 1516 return null; 1517 DerValue val = new DerValue(ext); 1518 byte[] data = val.getOctetString(); 1519 1520 ExtendedKeyUsageExtension ekuExt = 1521 new ExtendedKeyUsageExtension(Boolean.FALSE, data); 1522 return Collections.unmodifiableList(ekuExt.getExtendedKeyUsage()); 1523 } catch (IOException ioe) { 1524 throw new CertificateParsingException(ioe); 1525 } 1526 } 1527 1528 /** 1529 * Get the certificate constraints path length from the 1530 * the critical BasicConstraints extension, (oid = 2.5.29.19). 1531 * @return the length of the constraint. 1532 */ 1533 public int getBasicConstraints() { 1534 try { 1535 String extAlias = OIDMap.getName(PKIXExtensions.BasicConstraints_Id); 1536 if (extAlias == null) 1537 return -1; 1538 BasicConstraintsExtension certExt = 1539 (BasicConstraintsExtension)this.get(extAlias); 1540 if (certExt == null) 1541 return -1; 1542 1543 if (((Boolean)certExt.get(BasicConstraintsExtension.IS_CA) 1544 ).booleanValue() == true) 1545 return ((Integer)certExt.get( 1546 BasicConstraintsExtension.PATH_LEN)).intValue(); 1547 else 1548 return -1; 1549 } catch (Exception e) { 1550 return -1; 1551 } 1552 } 1553 1554 /** 1555 * Converts a GeneralNames structure into an immutable Collection of 1556 * alternative names (subject or issuer) in the form required by 1557 * {@link #getSubjectAlternativeNames} or 1558 * {@link #getIssuerAlternativeNames}. 1559 * 1560 * @param names the GeneralNames to be converted 1561 * @return an immutable Collection of alternative names 1562 */ 1563 private static Collection<List<?>> makeAltNames(GeneralNames names) { 1564 if (names.isEmpty()) { 1565 return Collections.<List<?>>emptySet(); 1566 } 1567 List<List<?>> newNames = new ArrayList<>(); 1568 for (GeneralName gname : names.names()) { 1569 GeneralNameInterface name = gname.getName(); 1570 List<Object> nameEntry = new ArrayList<>(2); 1571 nameEntry.add(Integer.valueOf(name.getType())); 1572 switch (name.getType()) { 1573 case GeneralNameInterface.NAME_RFC822: 1574 nameEntry.add(((RFC822Name) name).getName()); 1575 break; 1576 case GeneralNameInterface.NAME_DNS: 1577 nameEntry.add(((DNSName) name).getName()); 1578 break; 1579 case GeneralNameInterface.NAME_DIRECTORY: 1580 nameEntry.add(((X500Name) name).getRFC2253Name()); 1581 break; 1582 case GeneralNameInterface.NAME_URI: 1583 nameEntry.add(((URIName) name).getName()); 1584 break; 1585 case GeneralNameInterface.NAME_IP: 1586 try { 1587 nameEntry.add(((IPAddressName) name).getName()); 1588 } catch (IOException ioe) { 1589 // IPAddressName in cert is bogus 1590 throw new RuntimeException("IPAddress cannot be parsed", 1591 ioe); 1592 } 1593 break; 1594 case GeneralNameInterface.NAME_OID: 1595 nameEntry.add(((OIDName) name).getOID().toString()); 1596 break; 1597 default: 1598 // add DER encoded form 1599 DerOutputStream derOut = new DerOutputStream(); 1600 try { 1601 name.encode(derOut); 1602 } catch (IOException ioe) { 1603 // should not occur since name has already been decoded 1604 // from cert (this would indicate a bug in our code) 1605 throw new RuntimeException("name cannot be encoded", ioe); 1606 } 1607 nameEntry.add(derOut.toByteArray()); 1608 break; 1609 } 1610 newNames.add(Collections.unmodifiableList(nameEntry)); 1611 } 1612 return Collections.unmodifiableCollection(newNames); 1613 } 1614 1615 /** 1616 * Checks a Collection of altNames and clones any name entries of type 1617 * byte []. 1618 */ // only partially generified due to javac bug 1619 private static Collection<List<?>> cloneAltNames(Collection<List<?>> altNames) { 1620 boolean mustClone = false; 1621 for (List<?> nameEntry : altNames) { 1622 if (nameEntry.get(1) instanceof byte[]) { 1623 // must clone names 1624 mustClone = true; 1625 } 1626 } 1627 if (mustClone) { 1628 List<List<?>> namesCopy = new ArrayList<>(); 1629 for (List<?> nameEntry : altNames) { 1630 Object nameObject = nameEntry.get(1); 1631 if (nameObject instanceof byte[]) { 1632 List<Object> nameEntryCopy = 1633 new ArrayList<>(nameEntry); 1634 nameEntryCopy.set(1, ((byte[])nameObject).clone()); 1635 namesCopy.add(Collections.unmodifiableList(nameEntryCopy)); 1636 } else { 1637 namesCopy.add(nameEntry); 1638 } 1639 } 1640 return Collections.unmodifiableCollection(namesCopy); 1641 } else { 1642 return altNames; 1643 } 1644 } 1645 1646 /** 1647 * This method are the overridden implementation of 1648 * getSubjectAlternativeNames method in X509Certificate in the Sun 1649 * provider. It is better performance-wise since it returns cached 1650 * values. 1651 */ 1652 public synchronized Collection<List<?>> getSubjectAlternativeNames() 1653 throws CertificateParsingException { 1654 // return cached value if we can 1655 if (readOnly && subjectAlternativeNames != null) { 1656 return cloneAltNames(subjectAlternativeNames); 1657 } 1658 SubjectAlternativeNameExtension subjectAltNameExt = 1659 getSubjectAlternativeNameExtension(); 1660 if (subjectAltNameExt == null) { 1661 return null; 1662 } 1663 GeneralNames names; 1664 try { 1665 names = subjectAltNameExt.get( 1666 SubjectAlternativeNameExtension.SUBJECT_NAME); 1667 } catch (IOException ioe) { 1668 // should not occur 1669 return Collections.<List<?>>emptySet(); 1670 } 1671 subjectAlternativeNames = makeAltNames(names); 1672 return subjectAlternativeNames; 1673 } 1674 1675 /** 1676 * This static method is the default implementation of the 1677 * getSubjectAlternaitveNames method in X509Certificate. A 1678 * X509Certificate provider generally should overwrite this to 1679 * provide among other things caching for better performance. 1680 */ 1681 public static Collection<List<?>> getSubjectAlternativeNames(X509Certificate cert) 1682 throws CertificateParsingException { 1683 try { 1684 byte[] ext = cert.getExtensionValue(SUBJECT_ALT_NAME_OID); 1685 if (ext == null) { 1686 return null; 1687 } 1688 DerValue val = new DerValue(ext); 1689 byte[] data = val.getOctetString(); 1690 1691 SubjectAlternativeNameExtension subjectAltNameExt = 1692 new SubjectAlternativeNameExtension(Boolean.FALSE, 1693 data); 1694 1695 GeneralNames names; 1696 try { 1697 names = subjectAltNameExt.get( 1698 SubjectAlternativeNameExtension.SUBJECT_NAME); 1699 } catch (IOException ioe) { 1700 // should not occur 1701 return Collections.<List<?>>emptySet(); 1702 } 1703 return makeAltNames(names); 1704 } catch (IOException ioe) { 1705 throw new CertificateParsingException(ioe); 1706 } 1707 } 1708 1709 /** 1710 * This method are the overridden implementation of 1711 * getIssuerAlternativeNames method in X509Certificate in the Sun 1712 * provider. It is better performance-wise since it returns cached 1713 * values. 1714 */ 1715 public synchronized Collection<List<?>> getIssuerAlternativeNames() 1716 throws CertificateParsingException { 1717 // return cached value if we can 1718 if (readOnly && issuerAlternativeNames != null) { 1719 return cloneAltNames(issuerAlternativeNames); 1720 } 1721 IssuerAlternativeNameExtension issuerAltNameExt = 1722 getIssuerAlternativeNameExtension(); 1723 if (issuerAltNameExt == null) { 1724 return null; 1725 } 1726 GeneralNames names; 1727 try { 1728 names = issuerAltNameExt.get( 1729 IssuerAlternativeNameExtension.ISSUER_NAME); 1730 } catch (IOException ioe) { 1731 // should not occur 1732 return Collections.<List<?>>emptySet(); 1733 } 1734 issuerAlternativeNames = makeAltNames(names); 1735 return issuerAlternativeNames; 1736 } 1737 1738 /** 1739 * This static method is the default implementation of the 1740 * getIssuerAlternaitveNames method in X509Certificate. A 1741 * X509Certificate provider generally should overwrite this to 1742 * provide among other things caching for better performance. 1743 */ 1744 public static Collection<List<?>> getIssuerAlternativeNames(X509Certificate cert) 1745 throws CertificateParsingException { 1746 try { 1747 byte[] ext = cert.getExtensionValue(ISSUER_ALT_NAME_OID); 1748 if (ext == null) { 1749 return null; 1750 } 1751 1752 DerValue val = new DerValue(ext); 1753 byte[] data = val.getOctetString(); 1754 1755 IssuerAlternativeNameExtension issuerAltNameExt = 1756 new IssuerAlternativeNameExtension(Boolean.FALSE, 1757 data); 1758 GeneralNames names; 1759 try { 1760 names = issuerAltNameExt.get( 1761 IssuerAlternativeNameExtension.ISSUER_NAME); 1762 } catch (IOException ioe) { 1763 // should not occur 1764 return Collections.<List<?>>emptySet(); 1765 } 1766 return makeAltNames(names); 1767 } catch (IOException ioe) { 1768 throw new CertificateParsingException(ioe); 1769 } 1770 } 1771 1772 public AuthorityInfoAccessExtension getAuthorityInfoAccessExtension() { 1773 return (AuthorityInfoAccessExtension) 1774 getExtension(PKIXExtensions.AuthInfoAccess_Id); 1775 } 1776 1777 /************************************************************/ 1778 1779 /* 1780 * Cert is a SIGNED ASN.1 macro, a three elment sequence: 1781 * 1782 * - Data to be signed (ToBeSigned) -- the "raw" cert 1783 * - Signature algorithm (SigAlgId) 1784 * - The signature bits 1785 * 1786 * This routine unmarshals the certificate, saving the signature 1787 * parts away for later verification. 1788 */ 1789 private void parse(DerValue val) 1790 throws CertificateException, IOException { 1791 parse( 1792 val, 1793 null // use re-encoded form of val as the encoded form 1794 ); 1795 } 1796 1797 /* 1798 * Cert is a SIGNED ASN.1 macro, a three elment sequence: 1799 * 1800 * - Data to be signed (ToBeSigned) -- the "raw" cert 1801 * - Signature algorithm (SigAlgId) 1802 * - The signature bits 1803 * 1804 * This routine unmarshals the certificate, saving the signature 1805 * parts away for later verification. 1806 */ 1807 private void parse(DerValue val, byte[] originalEncodedForm) 1808 throws CertificateException, IOException { 1809 // check if can over write the certificate 1810 if (readOnly) 1811 throw new CertificateParsingException( 1812 "cannot over-write existing certificate"); 1813 1814 if (val.data == null || val.tag != DerValue.tag_Sequence) 1815 throw new CertificateParsingException( 1816 "invalid DER-encoded certificate data"); 1817 1818 signedCert = 1819 (originalEncodedForm != null) 1820 ? originalEncodedForm : val.toByteArray(); 1821 DerValue[] seq = new DerValue[3]; 1822 1823 seq[0] = val.data.getDerValue(); 1824 seq[1] = val.data.getDerValue(); 1825 seq[2] = val.data.getDerValue(); 1826 1827 if (val.data.available() != 0) { 1828 throw new CertificateParsingException("signed overrun, bytes = " 1829 + val.data.available()); 1830 } 1831 if (seq[0].tag != DerValue.tag_Sequence) { 1832 throw new CertificateParsingException("signed fields invalid"); 1833 } 1834 1835 algId = AlgorithmId.parse(seq[1]); 1836 signature = seq[2].getBitString(); 1837 1838 if (seq[1].data.available() != 0) { 1839 throw new CertificateParsingException("algid field overrun"); 1840 } 1841 if (seq[2].data.available() != 0) 1842 throw new CertificateParsingException("signed fields overrun"); 1843 1844 // The CertificateInfo 1845 info = new X509CertInfo(seq[0]); 1846 1847 // the "inner" and "outer" signature algorithms must match 1848 AlgorithmId infoSigAlg = (AlgorithmId)info.get( 1849 CertificateAlgorithmId.NAME 1850 + DOT + 1851 CertificateAlgorithmId.ALGORITHM); 1852 if (! algId.equals(infoSigAlg)) 1853 throw new CertificateException("Signature algorithm mismatch"); 1854 readOnly = true; 1855 } 1856 1857 /** 1858 * Extract the subject or issuer X500Principal from an X509Certificate. 1859 * Parses the encoded form of the cert to preserve the principal's 1860 * ASN.1 encoding. 1861 */ 1862 private static X500Principal getX500Principal(X509Certificate cert, 1863 boolean getIssuer) throws Exception { 1864 byte[] encoded = cert.getEncoded(); 1865 DerInputStream derIn = new DerInputStream(encoded); 1866 DerValue tbsCert = derIn.getSequence(3)[0]; 1867 DerInputStream tbsIn = tbsCert.data; 1868 DerValue tmp; 1869 tmp = tbsIn.getDerValue(); 1870 // skip version number if present 1871 if (tmp.isContextSpecific((byte)0)) { 1872 tmp = tbsIn.getDerValue(); 1873 } 1874 // tmp always contains serial number now 1875 tmp = tbsIn.getDerValue(); // skip signature 1876 tmp = tbsIn.getDerValue(); // issuer 1877 if (getIssuer == false) { 1878 tmp = tbsIn.getDerValue(); // skip validity 1879 tmp = tbsIn.getDerValue(); // subject 1880 } 1881 byte[] principalBytes = tmp.toByteArray(); 1882 return new X500Principal(principalBytes); 1883 } 1884 1885 /** 1886 * Extract the subject X500Principal from an X509Certificate. 1887 * Called from java.security.cert.X509Certificate.getSubjectX500Principal(). 1888 */ 1889 public static X500Principal getSubjectX500Principal(X509Certificate cert) { 1890 try { 1891 return getX500Principal(cert, false); 1892 } catch (Exception e) { 1893 throw new RuntimeException("Could not parse subject", e); 1894 } 1895 } 1896 1897 /** 1898 * Extract the issuer X500Principal from an X509Certificate. 1899 * Called from java.security.cert.X509Certificate.getIssuerX500Principal(). 1900 */ 1901 public static X500Principal getIssuerX500Principal(X509Certificate cert) { 1902 try { 1903 return getX500Principal(cert, true); 1904 } catch (Exception e) { 1905 throw new RuntimeException("Could not parse issuer", e); 1906 } 1907 } 1908 1909 /** 1910 * Returned the encoding of the given certificate for internal use. 1911 * Callers must guarantee that they neither modify it nor expose it 1912 * to untrusted code. Uses getEncodedInternal() if the certificate 1913 * is instance of X509CertImpl, getEncoded() otherwise. 1914 */ 1915 public static byte[] getEncodedInternal(Certificate cert) 1916 throws CertificateEncodingException { 1917 if (cert instanceof X509CertImpl) { 1918 return ((X509CertImpl)cert).getEncodedInternal(); 1919 } else { 1920 return cert.getEncoded(); 1921 } 1922 } 1923 1924 /** 1925 * Utility method to convert an arbitrary instance of X509Certificate 1926 * to a X509CertImpl. Does a cast if possible, otherwise reparses 1927 * the encoding. 1928 */ 1929 public static X509CertImpl toImpl(X509Certificate cert) 1930 throws CertificateException { 1931 if (cert instanceof X509CertImpl) { 1932 return (X509CertImpl)cert; 1933 } else { 1934 return X509Factory.intern(cert); 1935 } 1936 } 1937 1938 /** 1939 * Utility method to test if a certificate is self-issued. This is 1940 * the case iff the subject and issuer X500Principals are equal. 1941 */ 1942 public static boolean isSelfIssued(X509Certificate cert) { 1943 X500Principal subject = cert.getSubjectX500Principal(); 1944 X500Principal issuer = cert.getIssuerX500Principal(); 1945 return subject.equals(issuer); 1946 } 1947 1948 /** 1949 * Utility method to test if a certificate is self-signed. This is 1950 * the case iff the subject and issuer X500Principals are equal 1951 * AND the certificate's subject public key can be used to verify 1952 * the certificate. In case of exception, returns false. 1953 */ 1954 public static boolean isSelfSigned(X509Certificate cert, 1955 String sigProvider) { 1956 if (isSelfIssued(cert)) { 1957 try { 1958 if (sigProvider == null) { 1959 cert.verify(cert.getPublicKey()); 1960 } else { 1961 cert.verify(cert.getPublicKey(), sigProvider); 1962 } 1963 return true; 1964 } catch (Exception e) { 1965 // In case of exception, return false 1966 } 1967 } 1968 return false; 1969 } 1970 1971 private ConcurrentHashMap<String,String> fingerprints = 1972 new ConcurrentHashMap<>(2); 1973 1974 public String getFingerprint(String algorithm) { 1975 if (!fingerprints.containsKey(algorithm)) { 1976 fingerprints.put(algorithm, getCertificateFingerPrint(algorithm)); 1977 } 1978 return fingerprints.get(algorithm); 1979 } 1980 1981 /** 1982 * Gets the requested finger print of the certificate. The result 1983 * only contains 0-9 and A-F. No small case, no colon. 1984 */ 1985 private String getCertificateFingerPrint(String mdAlg) { 1986 String fingerPrint = ""; 1987 try { 1988 byte[] encCertInfo = getEncoded(); 1989 MessageDigest md = MessageDigest.getInstance(mdAlg); 1990 byte[] digest = md.digest(encCertInfo); 1991 StringBuffer buf = new StringBuffer(); 1992 for (int i = 0; i < digest.length; i++) { 1993 byte2hex(digest[i], buf); 1994 } 1995 fingerPrint = buf.toString(); 1996 } catch (NoSuchAlgorithmException | CertificateEncodingException e) { 1997 // ignored 1998 } 1999 return fingerPrint; 2000 } 2001 2002 /** 2003 * Converts a byte to hex digit and writes to the supplied buffer 2004 */ 2005 private static void byte2hex(byte b, StringBuffer buf) { 2006 char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', 2007 '9', 'A', 'B', 'C', 'D', 'E', 'F' }; 2008 int high = ((b & 0xf0) >> 4); 2009 int low = (b & 0x0f); 2010 buf.append(hexChars[high]); 2011 buf.append(hexChars[low]); 2012 } 2013 } 2014