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