public void processServerCertificate(Certificate serverCertificate) throws IOException {
    if (serverCertificate.isEmpty()) {
      throw new TlsFatalAlert(AlertDescription.bad_certificate);
    }

    org.ripple.bouncycastle.asn1.x509.Certificate x509Cert = serverCertificate.getCertificateAt(0);

    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
    try {
      this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    } catch (RuntimeException e) {
      throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
    }

    if (tlsSigner == null) {
      try {
        this.dhAgreePublicKey =
            TlsDHUtils.validateDHPublicKey((DHPublicKeyParameters) this.serverPublicKey);
        this.dhParameters = validateDHParameters(dhAgreePublicKey.getParameters());
      } catch (ClassCastException e) {
        throw new TlsFatalAlert(AlertDescription.certificate_unknown, e);
      }

      TlsUtils.validateKeyUsage(x509Cert, KeyUsage.keyAgreement);
    } else {
      if (!tlsSigner.isValidPublicKey(this.serverPublicKey)) {
        throw new TlsFatalAlert(AlertDescription.certificate_unknown);
      }

      TlsUtils.validateKeyUsage(x509Cert, KeyUsage.digitalSignature);
    }

    super.processServerCertificate(serverCertificate);
  }
Exemplo n.º 2
0
 public void verifySignature(Certificate caCert) throws SignatureException {
   String[] args;
   if (caCert != null) {
     try {
       Certificate.loadCertificateFromBuffer(caCert.getBlob());
     } catch (CertificateException e) {
       throw new SignatureException("Invalid certificate (" + e.getMessage() + ")");
     }
     args =
         new String[] {
           "python",
           "scripts/pkcs7_verifyier.py",
           "-in",
           getContentsFilename(),
           "-ca",
           caCert.getFilename()
         };
   } else {
     args = new String[] {"python", "scripts/pkcs7_verifyier.py", "-in", getContentsFilename()};
   }
   BashReader br = BashReader.read(args);
   if (br == null) {
     throw new SignatureException("Invalid command.");
   }
   if (br.getExitValue() == 0) {
     return;
   }
   throw new SignatureException("The signature verification has failed.");
 }
Exemplo n.º 3
0
  @Test
  void testNoSuccess() throws Exception {
    CreditMaster master = new CreditMaster("crm2.mas", true);
    IRGHConnection connection = new FakeConnection();
    CreditValidator validator = new CreditValidator(connection, master, "a");
    connection.setReport(new RFDIReport());

    Certificate result = validator.validateCustomer(new Customer());

    assertEquals(Certificate.VALID, result.getStatus());
  }
Exemplo n.º 4
0
  /**
   * Override the base class method to check that the name is a valid identity certificate name.
   *
   * @param name The identity certificate name which is copied.
   * @return This Data so that you can chain calls to update values.
   */
  public Data setName(Name name) {
    if (!isCorrectName(name)) throw new SecurityException("Wrong Identity Certificate Name!");

    super.setName(name);
    setPublicKeyName();
    return this;
  }
Exemplo n.º 5
0
 public void save(OutputStream outputStream, char[] password) throws Exception {
   KeyStore keyStore = KeyStore.getInstance("PKCS12");
   keyStore.load(null, null);
   X509Certificate[] certificateChain = {certificate.getX509Certificate()};
   keyStore.setKeyEntry(
       privateKey.getAlias(), privateKey.getPrivateKey(), password, certificateChain);
   keyStore.store(outputStream, password);
 }
Exemplo n.º 6
0
  protected void processClientCertificate(ServerHandshakeState state, byte[] body)
      throws IOException {
    ByteArrayInputStream buf = new ByteArrayInputStream(body);

    Certificate clientCertificate = Certificate.parse(buf);

    TlsProtocol.assertEmpty(buf);

    notifyClientCertificate(state, clientCertificate);
  }
Exemplo n.º 7
0
 /**
  * Adds a {@code Certificate} to this {@code Identity}.
  *
  * @param certificate the {@code Certificate} to be added to this {@code Identity}.
  * @throws KeyManagementException if the certificate is not valid.
  */
 public void addCertificate(Certificate certificate) throws KeyManagementException {
   PublicKey certPK = certificate.getPublicKey();
   if (publicKey != null) {
     if (!checkKeysEqual(publicKey, certPK)) {
       throw new KeyManagementException("Cert's public key does not match Identity's public key");
     }
   } else {
     publicKey = certPK;
   }
   if (certificates == null) {
     certificates = new Vector<Certificate>();
   }
   certificates.add(certificate);
 }
Exemplo n.º 8
0
 /**
  * Convert to AuthData.xml format
  *
  * @return String - auth config data
  */
 protected String toConfigXML() {
   StringBuffer buf = new StringBuffer();
   buf.append("<Identity name=\"...\" domain=\"...\">\n");
   buf.append(prvKey.toConfigXML());
   buf.append("\n");
   buf.append(cert.toConfigXML());
   buf.append("\n<Certificate name=\"${signer}\" ... />\n");
   buf.append("<DHparam>\n<Alpha>");
   buf.append(ContentHandler.toBase64(dhParam.alpha));
   buf.append("</Alpha>\n<P>");
   buf.append(ContentHandler.toBase64(dhParam.p));
   buf.append("</P>\n</DHparam>\n</Identity>\n");
   return buf.toString();
 }
Exemplo n.º 9
0
  private void sendClientCertificate(Certificate clientCert) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    TlsUtils.writeUint8(HandshakeType.certificate, bos);

    // Reserve space for length
    TlsUtils.writeUint24(0, bos);

    clientCert.encode(bos);
    byte[] message = bos.toByteArray();

    // Patch actual length back in
    TlsUtils.writeUint24(message.length - 4, message, 1);

    rs.writeMessage(ContentType.handshake, message, 0, message.length);
  }
  public DefaultTlsSignerCredentials(
      TlsContext context,
      Certificate certificate,
      AsymmetricKeyParameter privateKey,
      SignatureAndHashAlgorithm signatureAndHashAlgorithm) {
    if (certificate == null) {
      throw new IllegalArgumentException("'certificate' cannot be null");
    }
    if (certificate.isEmpty()) {
      throw new IllegalArgumentException("'certificate' cannot be empty");
    }
    if (privateKey == null) {
      throw new IllegalArgumentException("'privateKey' cannot be null");
    }
    if (!privateKey.isPrivate()) {
      throw new IllegalArgumentException("'privateKey' must be private");
    }
    if (TlsUtils.isTLSv12(context) && signatureAndHashAlgorithm == null) {
      throw new IllegalArgumentException(
          "'signatureAndHashAlgorithm' cannot be null for (D)TLS 1.2+");
    }

    if (privateKey instanceof RSAKeyParameters) {
      this.signer = new TlsRSASigner();
    } else if (privateKey instanceof DSAPrivateKeyParameters) {
      this.signer = new TlsDSSSigner();
    } else if (privateKey instanceof ECPrivateKeyParameters) {
      this.signer = new TlsECDSASigner();
    } else {
      throw new IllegalArgumentException(
          "'privateKey' type not supported: " + privateKey.getClass().getName());
    }

    this.signer.init(context);

    this.context = context;
    this.certificate = certificate;
    this.privateKey = privateKey;
    this.signatureAndHashAlgorithm = signatureAndHashAlgorithm;
  }
Exemplo n.º 11
0
  protected void notifyClientCertificate(ServerHandshakeState state, Certificate clientCertificate)
      throws IOException {
    if (state.certificateRequest == null) {
      throw new IllegalStateException();
    }

    if (state.clientCertificate != null) {
      throw new TlsFatalAlert(AlertDescription.unexpected_message);
    }

    state.clientCertificate = clientCertificate;

    if (clientCertificate.isEmpty()) {
      state.keyExchange.skipClientCredentials();
    } else {

      /*
       * TODO RFC 5246 7.4.6. If the certificate_authorities list in the certificate request
       * message was non-empty, one of the certificates in the certificate chain SHOULD be
       * issued by one of the listed CAs.
       */

      state.clientCertificateType =
          TlsUtils.getClientCertificateType(
              clientCertificate, state.serverCredentials.getCertificate());

      state.keyExchange.processClientCertificate(clientCertificate);
    }

    /*
     * RFC 5246 7.4.6. If the client does not send any certificates, the server MAY at its
     * discretion either continue the handshake without client authentication, or respond with a
     * fatal handshake_failure alert. Also, if some aspect of the certificate chain was
     * unacceptable (e.g., it was not signed by a known, trusted CA), the server MAY at its
     * discretion either continue the handshake (considering the client unauthenticated) or send
     * a fatal alert.
     */
    state.server.notifyClientCertificate(clientCertificate);
  }
Exemplo n.º 12
0
 public static CustomerVo fromFdo(OrderCustomFdo fdo) {
   CustomerVo vo = new CustomerVo();
   vo.amount = fdo.getMoneyOfExpense();
   vo.customerId = fdo.getOrderCustomId();
   vo.household = fdo.getCensusRegister();
   vo.memo = fdo.getMemo();
   vo.mobile = fdo.getMobile();
   vo.name = fdo.getName();
   vo.pinyin = fdo.getPinyin();
   vo.orderNum = fdo.getBizOrderId();
   vo.sex = fdo.getSex() ? "男" : "女";
   vo.status = fdo.getIsCanceled() ? "已取消" : "正常";
   vo.productName = fdo.getProductName();
   vo.orderId = fdo.getOrderId();
   Certificate certificate = new Certificate(fdo.getPid());
   certificate.birthday = fdo.getBirthday();
   certificate.certificateNumber = fdo.getPidNo();
   certificate.expiryDate = fdo.getGmtPidExpiration();
   certificate.issueDate = fdo.getGmtPidIssue();
   certificate.issuePlace = fdo.getPidIssuePlace();
   vo.setCertificate(certificate);
   return vo;
 }
Exemplo n.º 13
0
 public static boolean isIdentityCertificate(Certificate certificate) {
   return isCorrectName(certificate.getName());
 }
Exemplo n.º 14
0
 /**
  * Override to call the base class wireDecode then update the public key name.
  *
  * @param input The input byte array to be decoded as an immutable Blob.
  * @param wireFormat A WireFormat object used to decode the input.
  */
 public void wireDecode(Blob input, WireFormat wireFormat) throws EncodingException {
   super.wireDecode(input, wireFormat);
   setPublicKeyName();
 }
Exemplo n.º 15
0
  private void processHandshakeMessage(short type, byte[] buf) throws IOException {
    ByteArrayInputStream is = new ByteArrayInputStream(buf);

    switch (type) {
      case HandshakeType.certificate:
        {
          switch (connection_state) {
            case CS_SERVER_HELLO_RECEIVED:
              {
                // Parse the Certificate message and send to cipher suite

                Certificate serverCertificate = Certificate.parse(is);

                assertEmpty(is);

                this.keyExchange.processServerCertificate(serverCertificate);

                this.authentication = tlsClient.getAuthentication();
                this.authentication.notifyServerCertificate(serverCertificate);

                break;
              }
            default:
              this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
          }

          connection_state = CS_SERVER_CERTIFICATE_RECEIVED;
          break;
        }
      case HandshakeType.finished:
        switch (connection_state) {
          case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED:
            /*
             * Read the checksum from the finished message, it has always 12
             * bytes for TLS 1.0 and 36 for SSLv3.
             */
            boolean isTls =
                tlsClientContext.getServerVersion().getFullVersion()
                    >= ProtocolVersion.TLSv10.getFullVersion();

            int checksumLength = isTls ? 12 : 36;
            byte[] serverVerifyData = new byte[checksumLength];
            TlsUtils.readFully(serverVerifyData, is);

            assertEmpty(is);

            /*
             * Calculate our own checksum.
             */
            byte[] expectedServerVerifyData =
                TlsUtils.calculateVerifyData(
                    tlsClientContext, "server finished", rs.getCurrentHash(TlsUtils.SSL_SERVER));

            /*
             * Compare both checksums.
             */
            if (!Arrays.constantTimeAreEqual(expectedServerVerifyData, serverVerifyData)) {
              /*
               * Wrong checksum in the finished message.
               */
              this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
            }

            connection_state = CS_DONE;

            /*
             * We are now ready to receive application data.
             */
            this.appDataReady = true;
            break;
          default:
            this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
        }
        break;
      case HandshakeType.server_hello:
        switch (connection_state) {
          case CS_CLIENT_HELLO_SEND:
            /*
             * Read the server hello message
             */
            ProtocolVersion server_version = TlsUtils.readVersion(is);
            ProtocolVersion client_version = this.tlsClientContext.getClientVersion();
            if (server_version.getFullVersion() > client_version.getFullVersion()) {
              this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
            }

            this.tlsClientContext.setServerVersion(server_version);
            this.tlsClient.notifyServerVersion(server_version);

            /*
             * Read the server random
             */
            securityParameters.serverRandom = new byte[32];
            TlsUtils.readFully(securityParameters.serverRandom, is);

            byte[] sessionID = TlsUtils.readOpaque8(is);
            if (sessionID.length > 32) {
              this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
            }

            this.tlsClient.notifySessionID(sessionID);

            /*
             * Find out which CipherSuite the server has chosen and check that
             * it was one of the offered ones.
             */
            int selectedCipherSuite = TlsUtils.readUint16(is);
            if (!arrayContains(offeredCipherSuites, selectedCipherSuite)
                || selectedCipherSuite == CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
              this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
            }

            this.tlsClient.notifySelectedCipherSuite(selectedCipherSuite);

            /*
             * Find out which CompressionMethod the server has chosen and check that
             * it was one of the offered ones.
             */
            short selectedCompressionMethod = TlsUtils.readUint8(is);
            if (!arrayContains(offeredCompressionMethods, selectedCompressionMethod)) {
              this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
            }

            this.tlsClient.notifySelectedCompressionMethod(selectedCompressionMethod);

            /*
             * RFC3546 2.2 The extended server hello message format MAY be
             * sent in place of the server hello message when the client has
             * requested extended functionality via the extended client hello
             * message specified in Section 2.1. ... Note that the extended
             * server hello message is only sent in response to an extended
             * client hello message. This prevents the possibility that the
             * extended server hello message could "break" existing TLS 1.0
             * clients.
             */

            /*
             * TODO RFC 3546 2.3 If [...] the older session is resumed, then
             * the server MUST ignore extensions appearing in the client
             * hello, and send a server hello containing no extensions.
             */

            // Integer -> byte[]
            Hashtable serverExtensions = new Hashtable();

            if (is.available() > 0) {
              // Process extensions from extended server hello
              byte[] extBytes = TlsUtils.readOpaque16(is);

              ByteArrayInputStream ext = new ByteArrayInputStream(extBytes);
              while (ext.available() > 0) {
                Integer extType = Integers.valueOf(TlsUtils.readUint16(ext));
                byte[] extValue = TlsUtils.readOpaque16(ext);

                /*
                 * RFC 5746 Note that sending a "renegotiation_info"
                 * extension in response to a ClientHello containing only
                 * the SCSV is an explicit exception to the prohibition in
                 * RFC 5246, Section 7.4.1.4, on the server sending
                 * unsolicited extensions and is only allowed because the
                 * client is signaling its willingness to receive the
                 * extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV
                 * SCSV. TLS implementations MUST continue to comply with
                 * Section 7.4.1.4 for all other extensions.
                 */

                if (!extType.equals(EXT_RenegotiationInfo)
                    && clientExtensions.get(extType) == null) {
                  /*
                   * RFC 3546 2.3 Note that for all extension types
                   * (including those defined in future), the extension
                   * type MUST NOT appear in the extended server hello
                   * unless the same extension type appeared in the
                   * corresponding client hello. Thus clients MUST abort
                   * the handshake if they receive an extension type in
                   * the extended server hello that they did not request
                   * in the associated (extended) client hello.
                   */
                  this.failWithError(AlertLevel.fatal, AlertDescription.unsupported_extension);
                }

                if (serverExtensions.containsKey(extType)) {
                  /*
                   * RFC 3546 2.3 Also note that when multiple
                   * extensions of different types are present in the
                   * extended client hello or the extended server hello,
                   * the extensions may appear in any order. There MUST
                   * NOT be more than one extension of the same type.
                   */
                  this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                }

                serverExtensions.put(extType, extValue);
              }
            }

            assertEmpty(is);

            /*
             * RFC 5746 3.4. When a ServerHello is received, the client MUST
             * check if it includes the "renegotiation_info" extension:
             */
            {
              boolean secure_negotiation = serverExtensions.containsKey(EXT_RenegotiationInfo);

              /*
               * If the extension is present, set the secure_renegotiation
               * flag to TRUE. The client MUST then verify that the length
               * of the "renegotiated_connection" field is zero, and if it
               * is not, MUST abort the handshake (by sending a fatal
               * handshake_failure alert).
               */
              if (secure_negotiation) {
                byte[] renegExtValue = (byte[]) serverExtensions.get(EXT_RenegotiationInfo);

                if (!Arrays.constantTimeAreEqual(
                    renegExtValue, createRenegotiationInfo(emptybuf))) {
                  this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                }
              }

              tlsClient.notifySecureRenegotiation(secure_negotiation);
            }

            if (clientExtensions != null) {
              tlsClient.processServerExtensions(serverExtensions);
            }

            this.keyExchange = tlsClient.getKeyExchange();

            connection_state = CS_SERVER_HELLO_RECEIVED;
            break;
          default:
            this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
        }
        break;
      case HandshakeType.server_hello_done:
        switch (connection_state) {
          case CS_SERVER_HELLO_RECEIVED:

            // There was no server certificate message; check it's OK
            this.keyExchange.skipServerCertificate();
            this.authentication = null;

            // NB: Fall through to next case label

          case CS_SERVER_CERTIFICATE_RECEIVED:

            // There was no server key exchange message; check it's OK
            this.keyExchange.skipServerKeyExchange();

            // NB: Fall through to next case label

          case CS_SERVER_KEY_EXCHANGE_RECEIVED:
          case CS_CERTIFICATE_REQUEST_RECEIVED:
            assertEmpty(is);

            connection_state = CS_SERVER_HELLO_DONE_RECEIVED;

            TlsCredentials clientCreds = null;
            if (certificateRequest == null) {
              this.keyExchange.skipClientCredentials();
            } else {
              clientCreds = this.authentication.getClientCredentials(certificateRequest);

              if (clientCreds == null) {
                this.keyExchange.skipClientCredentials();

                boolean isTls =
                    tlsClientContext.getServerVersion().getFullVersion()
                        >= ProtocolVersion.TLSv10.getFullVersion();

                if (isTls) {
                  sendClientCertificate(Certificate.EMPTY_CHAIN);
                } else {
                  sendAlert(AlertLevel.warning, AlertDescription.no_certificate);
                }
              } else {
                this.keyExchange.processClientCredentials(clientCreds);

                sendClientCertificate(clientCreds.getCertificate());
              }
            }

            /*
             * Send the client key exchange message, depending on the key
             * exchange we are using in our CipherSuite.
             */
            sendClientKeyExchange();

            connection_state = CS_CLIENT_KEY_EXCHANGE_SEND;

            /*
             * Calculate the master_secret
             */
            byte[] pms = this.keyExchange.generatePremasterSecret();

            securityParameters.masterSecret =
                TlsUtils.calculateMasterSecret(this.tlsClientContext, pms);

            // TODO Is there a way to ensure the data is really overwritten?
            /*
             * RFC 2246 8.1. The pre_master_secret should be deleted from
             * memory once the master_secret has been computed.
             */
            Arrays.fill(pms, (byte) 0);

            if (clientCreds != null && clientCreds instanceof TlsSignerCredentials) {
              TlsSignerCredentials signerCreds = (TlsSignerCredentials) clientCreds;
              byte[] md5andsha1 = rs.getCurrentHash(null);
              byte[] clientCertificateSignature =
                  signerCreds.generateCertificateSignature(md5andsha1);
              sendCertificateVerify(clientCertificateSignature);

              connection_state = CS_CERTIFICATE_VERIFY_SEND;
            }

            /*
             * Now, we send change cipher state
             */
            byte[] cmessage = new byte[1];
            cmessage[0] = 1;
            rs.writeMessage(ContentType.change_cipher_spec, cmessage, 0, cmessage.length);

            connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND;

            /*
             * Initialize our cipher suite
             */
            rs.clientCipherSpecDecided(tlsClient.getCompression(), tlsClient.getCipher());

            /*
             * Send our finished message.
             */
            byte[] clientVerifyData =
                TlsUtils.calculateVerifyData(
                    tlsClientContext, "client finished", rs.getCurrentHash(TlsUtils.SSL_CLIENT));

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            TlsUtils.writeUint8(HandshakeType.finished, bos);
            TlsUtils.writeOpaque24(clientVerifyData, bos);
            byte[] message = bos.toByteArray();

            rs.writeMessage(ContentType.handshake, message, 0, message.length);

            this.connection_state = CS_CLIENT_FINISHED_SEND;
            break;
          default:
            this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
        }
        break;
      case HandshakeType.server_key_exchange:
        {
          switch (connection_state) {
            case CS_SERVER_HELLO_RECEIVED:

              // There was no server certificate message; check it's OK
              this.keyExchange.skipServerCertificate();
              this.authentication = null;

              // NB: Fall through to next case label

            case CS_SERVER_CERTIFICATE_RECEIVED:
              this.keyExchange.processServerKeyExchange(is);

              assertEmpty(is);
              break;

            default:
              this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
          }

          this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED;
          break;
        }
      case HandshakeType.certificate_request:
        {
          switch (connection_state) {
            case CS_SERVER_CERTIFICATE_RECEIVED:

              // There was no server key exchange message; check it's OK
              this.keyExchange.skipServerKeyExchange();

              // NB: Fall through to next case label

            case CS_SERVER_KEY_EXCHANGE_RECEIVED:
              {
                if (this.authentication == null) {
                  /*
                   * RFC 2246 7.4.4. It is a fatal handshake_failure alert
                   * for an anonymous server to request client identification.
                   */
                  this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                }

                int numTypes = TlsUtils.readUint8(is);
                short[] certificateTypes = new short[numTypes];
                for (int i = 0; i < numTypes; ++i) {
                  certificateTypes[i] = TlsUtils.readUint8(is);
                }

                byte[] authorities = TlsUtils.readOpaque16(is);

                assertEmpty(is);

                Vector authorityDNs = new Vector();

                ByteArrayInputStream bis = new ByteArrayInputStream(authorities);
                while (bis.available() > 0) {
                  byte[] dnBytes = TlsUtils.readOpaque16(bis);
                  authorityDNs.addElement(
                      X500Name.getInstance(ASN1Primitive.fromByteArray(dnBytes)));
                }

                this.certificateRequest = new CertificateRequest(certificateTypes, authorityDNs);
                this.keyExchange.validateCertificateRequest(this.certificateRequest);

                break;
              }
            default:
              this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
          }

          this.connection_state = CS_CERTIFICATE_REQUEST_RECEIVED;
          break;
        }
      case HandshakeType.hello_request:
        /*
         * RFC 2246 7.4.1.1 Hello request This message will be ignored by the
         * client if the client is currently negotiating a session. This message
         * may be ignored by the client if it does not wish to renegotiate a
         * session, or the client may, if it wishes, respond with a
         * no_renegotiation alert.
         */
        if (connection_state == CS_DONE) {
          // Renegotiation not supported yet
          sendAlert(AlertLevel.warning, AlertDescription.no_renegotiation);
        }
        break;
      case HandshakeType.client_key_exchange:
      case HandshakeType.certificate_verify:
      case HandshakeType.client_hello:
      default:
        // We do not support this!
        this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
        break;
    }
  }
Exemplo n.º 16
0
  public Reader(
      Long id,
      String cardNo,
      String password,
      String barCode,
      String readerName,
      Date birthday,
      String sex,
      Float leftMoney,
      String email,
      String contactTel,
      Date entyDate,
      Date effectiveDate,
      Integer borrowedQuantiy,
      Integer totalBQuantity,
      String readerPic,
      String spell,
      String readerDesc,
      Long unitId,
      String unitCode,
      String unitName,
      String unitShortName,
      String certificateId,
      String certificateCode,
      String certificateName,
      Long readerTypeId,
      String readerTypeCode,
      String readerTypeName,
      Integer maxBorrowDays,
      Integer maxBorrowedQuantity,
      Float rent,
      String cardStateId,
      String cardStateCode,
      String cardStateName) {
    this.id = id;
    this.readerName = readerName;
    this.birthday = birthday;
    this.sex = sex;
    this.email = email;
    this.contactTel = contactTel;
    this.leftMoney = leftMoney;
    this.spell = spell;
    this.cardNo = cardNo;
    this.password = password;
    this.barCode = barCode;
    this.entyDate = entyDate;
    this.effectiveDate = effectiveDate;
    this.borrowedQuantiy = borrowedQuantiy;
    this.totalBQuantity = totalBQuantity;
    this.readerPic = readerPic;
    this.readerDesc = readerDesc;

    ReaderUnits readerUnits = new ReaderUnits();
    readerUnits.setUnitId(unitId);
    readerUnits.setUnitcode(unitCode);
    readerUnits.setUnitName(unitName);
    readerUnits.setUnitShortName(unitShortName);
    this.setReaderUnits(readerUnits);

    Certificate certificate = new Certificate();
    certificate.setItemId(certificateId);
    certificate.setItemCode(certificateCode);
    certificate.setItemName(certificateName);
    this.setCertificate(certificate);

    ReaderType readerType = new ReaderType();
    readerType.setId(readerTypeId);
    readerType.setReaderCateCode(readerTypeCode);
    readerType.setReaderCateName(readerTypeName);
    readerType.setMaxBorrowDays(maxBorrowDays);
    readerType.setMaxBorrowedQuantity(maxBorrowedQuantity);
    readerType.setRent(rent);
    this.setReaderType(readerType);

    CardState cardState = new CardState();
    cardState.setItemId(cardStateId);
    cardState.setItemCode(cardStateCode);
    cardState.setItemName(cardStateName);
    this.setCardState(cardState);
  }
Exemplo n.º 17
0
 public Date getExpirationDate() {
   return certificate.getExpirationDate();
 }
Exemplo n.º 18
0
 public String getCommonName() {
   return certificate.getCommonName();
 }
Exemplo n.º 19
0
  protected DTLSTransport serverHandshake(ServerHandshakeState state, DTLSRecordLayer recordLayer)
      throws IOException {
    SecurityParameters securityParameters = state.serverContext.getSecurityParameters();
    DTLSReliableHandshake handshake = new DTLSReliableHandshake(state.serverContext, recordLayer);

    DTLSReliableHandshake.Message clientMessage = handshake.receiveMessage();

    {
      // NOTE: After receiving a record from the client, we discover the record layer version
      ProtocolVersion client_version = recordLayer.getDiscoveredPeerVersion();
      // TODO Read RFCs for guidance on the expected record layer version number
      state.serverContext.setClientVersion(client_version);
    }

    if (clientMessage.getType() == HandshakeType.client_hello) {
      processClientHello(state, clientMessage.getBody());
    } else {
      throw new TlsFatalAlert(AlertDescription.unexpected_message);
    }

    {
      byte[] serverHelloBody = generateServerHello(state);

      if (state.maxFragmentLength >= 0) {
        int plainTextLimit = 1 << (8 + state.maxFragmentLength);
        recordLayer.setPlaintextLimit(plainTextLimit);
      }

      securityParameters.cipherSuite = state.selectedCipherSuite;
      securityParameters.compressionAlgorithm = state.selectedCompressionMethod;
      securityParameters.prfAlgorithm =
          TlsProtocol.getPRFAlgorithm(state.serverContext, state.selectedCipherSuite);

      /*
       * RFC 5264 7.4.9. Any cipher suite which does not explicitly specify verify_data_length
       * has a verify_data_length equal to 12. This includes all existing cipher suites.
       */
      securityParameters.verifyDataLength = 12;

      handshake.sendMessage(HandshakeType.server_hello, serverHelloBody);
    }

    handshake.notifyHelloComplete();

    Vector serverSupplementalData = state.server.getServerSupplementalData();
    if (serverSupplementalData != null) {
      byte[] supplementalDataBody = generateSupplementalData(serverSupplementalData);
      handshake.sendMessage(HandshakeType.supplemental_data, supplementalDataBody);
    }

    state.keyExchange = state.server.getKeyExchange();
    state.keyExchange.init(state.serverContext);

    state.serverCredentials = state.server.getCredentials();

    Certificate serverCertificate = null;

    if (state.serverCredentials == null) {
      state.keyExchange.skipServerCredentials();
    } else {
      state.keyExchange.processServerCredentials(state.serverCredentials);

      serverCertificate = state.serverCredentials.getCertificate();
      byte[] certificateBody = generateCertificate(serverCertificate);
      handshake.sendMessage(HandshakeType.certificate, certificateBody);
    }

    // TODO[RFC 3546] Check whether empty certificates is possible, allowed, or excludes
    // CertificateStatus
    if (serverCertificate == null || serverCertificate.isEmpty()) {
      state.allowCertificateStatus = false;
    }

    if (state.allowCertificateStatus) {
      CertificateStatus certificateStatus = state.server.getCertificateStatus();
      if (certificateStatus != null) {
        byte[] certificateStatusBody = generateCertificateStatus(state, certificateStatus);
        handshake.sendMessage(HandshakeType.certificate_status, certificateStatusBody);
      }
    }

    byte[] serverKeyExchange = state.keyExchange.generateServerKeyExchange();
    if (serverKeyExchange != null) {
      handshake.sendMessage(HandshakeType.server_key_exchange, serverKeyExchange);
    }

    if (state.serverCredentials != null) {
      state.certificateRequest = state.server.getCertificateRequest();
      if (state.certificateRequest != null) {
        state.keyExchange.validateCertificateRequest(state.certificateRequest);

        byte[] certificateRequestBody = generateCertificateRequest(state, state.certificateRequest);
        handshake.sendMessage(HandshakeType.certificate_request, certificateRequestBody);

        TlsUtils.trackHashAlgorithms(
            handshake.getHandshakeHash(),
            state.certificateRequest.getSupportedSignatureAlgorithms());
      }
    }

    handshake.sendMessage(HandshakeType.server_hello_done, TlsUtils.EMPTY_BYTES);

    handshake.getHandshakeHash().sealHashAlgorithms();

    clientMessage = handshake.receiveMessage();

    if (clientMessage.getType() == HandshakeType.supplemental_data) {
      processClientSupplementalData(state, clientMessage.getBody());
      clientMessage = handshake.receiveMessage();
    } else {
      state.server.processClientSupplementalData(null);
    }

    if (state.certificateRequest == null) {
      state.keyExchange.skipClientCredentials();
    } else {
      if (clientMessage.getType() == HandshakeType.certificate) {
        processClientCertificate(state, clientMessage.getBody());
        clientMessage = handshake.receiveMessage();
      } else {
        if (TlsUtils.isTLSv12(state.serverContext)) {
          /*
           * RFC 5246 If no suitable certificate is available, the client MUST send a
           * certificate message containing no certificates.
           *
           * NOTE: In previous RFCs, this was SHOULD instead of MUST.
           */
          throw new TlsFatalAlert(AlertDescription.unexpected_message);
        }

        notifyClientCertificate(state, Certificate.EMPTY_CHAIN);
      }
    }

    if (clientMessage.getType() == HandshakeType.client_key_exchange) {
      processClientKeyExchange(state, clientMessage.getBody());
    } else {
      throw new TlsFatalAlert(AlertDescription.unexpected_message);
    }

    TlsProtocol.establishMasterSecret(state.serverContext, state.keyExchange);
    recordLayer.initPendingEpoch(state.server.getCipher());

    TlsHandshakeHash prepareFinishHash = handshake.prepareToFinish();

    /*
     * RFC 5246 7.4.8 This message is only sent following a client certificate that has signing
     * capability (i.e., all certificates except those containing fixed Diffie-Hellman
     * parameters).
     */
    if (expectCertificateVerifyMessage(state)) {
      byte[] certificateVerifyBody = handshake.receiveMessageBody(HandshakeType.certificate_verify);
      processCertificateVerify(state, certificateVerifyBody, prepareFinishHash);
    }

    // NOTE: Calculated exclusive of the actual Finished message from the client
    byte[] expectedClientVerifyData =
        TlsUtils.calculateVerifyData(
            state.serverContext,
            ExporterLabel.client_finished,
            TlsProtocol.getCurrentPRFHash(state.serverContext, handshake.getHandshakeHash(), null));
    processFinished(handshake.receiveMessageBody(HandshakeType.finished), expectedClientVerifyData);

    if (state.expectSessionTicket) {
      NewSessionTicket newSessionTicket = state.server.getNewSessionTicket();
      byte[] newSessionTicketBody = generateNewSessionTicket(state, newSessionTicket);
      handshake.sendMessage(HandshakeType.session_ticket, newSessionTicketBody);
    }

    // NOTE: Calculated exclusive of the Finished message itself
    byte[] serverVerifyData =
        TlsUtils.calculateVerifyData(
            state.serverContext,
            ExporterLabel.server_finished,
            TlsProtocol.getCurrentPRFHash(state.serverContext, handshake.getHandshakeHash(), null));
    handshake.sendMessage(HandshakeType.finished, serverVerifyData);

    handshake.finish();

    state.server.notifyHandshakeComplete();

    return new DTLSTransport(recordLayer);
  }
Exemplo n.º 20
0
 public void setCertificate(String buff) throws CertificateException {
   this.certificate = Certificate.loadCertificateFromBuffer(buff);
 }
Exemplo n.º 21
0
  public static void main(String[] args) {

    try {

      // Read arguments
      if (args.length != 3) {
        System.out.println("Usage: PFX <dbdir> <infile> <outfile>");
        System.exit(-1);
      }

      // open input file for reading
      FileInputStream infile = null;
      try {
        infile = new FileInputStream(args[1]);
      } catch (FileNotFoundException f) {
        System.out.println("Cannot open file " + args[1] + " for reading: " + f.getMessage());
        return;
      }
      int certfile = 0;

      // initialize CryptoManager. This is necessary because there is
      // crypto involved with decoding a PKCS #12 file
      CryptoManager.initialize(args[0]);
      CryptoManager manager = CryptoManager.getInstance();

      // Decode the P12 file
      PFX.Template pfxt = new PFX.Template();
      PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(infile, 2048));
      System.out.println("Decoded PFX");

      // print out information about the top-level PFX structure
      System.out.println("Version: " + pfx.getVersion());
      AuthenticatedSafes authSafes = pfx.getAuthSafes();
      SEQUENCE safeContentsSequence = authSafes.getSequence();
      System.out.println("AuthSafes has " + safeContentsSequence.size() + " SafeContents");

      // Get the password for the old file
      System.out.println("Enter password: "******"Enter new password:"******"AuthSafes verifies correctly.");
      } else {
        System.out.println("AuthSafes failed to verify because: " + sb);
      }

      // Create a new AuthenticatedSafes. As we read the contents of the
      // old authSafes, we will store them into the new one.  After we have
      // cycled through all the contents, they will all have been copied into
      // the new authSafes.
      AuthenticatedSafes newAuthSafes = new AuthenticatedSafes();

      // Loop over contents of the old authenticated safes
      // for(int i=0; i < asSeq.size(); i++) {
      for (int i = 0; i < safeContentsSequence.size(); i++) {

        // The safeContents may or may not be encrypted.  We always send
        // the password in.  It will get used if it is needed.  If the
        // decryption of the safeContents fails for some reason (like
        // a bad password), then this method will throw an exception
        SEQUENCE safeContents = authSafes.getSafeContentsAt(pass, i);

        System.out.println("\n\nSafeContents #" + i + " has " + safeContents.size() + " bags");

        // Go through all the bags in this SafeContents
        for (int j = 0; j < safeContents.size(); j++) {
          SafeBag safeBag = (SafeBag) safeContents.elementAt(j);

          // The type of the bag is an OID
          System.out.println("\nBag " + j + " has type " + safeBag.getBagType());

          // look for bag attributes
          SET attribs = safeBag.getBagAttributes();
          if (attribs == null) {
            System.out.println("Bag has no attributes");
          } else {
            for (int b = 0; b < attribs.size(); b++) {
              Attribute a = (Attribute) attribs.elementAt(b);
              if (a.getType().equals(SafeBag.FRIENDLY_NAME)) {
                // the friendly name attribute is a nickname
                BMPString bs =
                    (BMPString)
                        ((ANY) a.getValues().elementAt(0)).decodeWith(BMPString.getTemplate());
                System.out.println("Friendly Name: " + bs);
              } else if (a.getType().equals(SafeBag.LOCAL_KEY_ID)) {
                // the local key id is used to match a key
                // to its cert.  The key id is the SHA-1 hash of
                // the DER-encoded cert.
                OCTET_STRING os =
                    (OCTET_STRING)
                        ((ANY) a.getValues().elementAt(0)).decodeWith(OCTET_STRING.getTemplate());
                System.out.println("LocalKeyID:");
                /*
                                     AuthenticatedSafes.
                                         print_byte_array(os.toByteArray());
                */
              } else {
                System.out.println("Unknown attribute type: " + a.getType().toString());
              }
            }
          }

          // now look at the contents of the bag
          ASN1Value val = safeBag.getInterpretedBagContent();

          if (val instanceof PrivateKeyInfo) {
            // A PrivateKeyInfo contains an unencrypted private key
            System.out.println("content is PrivateKeyInfo");
          } else if (val instanceof EncryptedPrivateKeyInfo) {
            // An EncryptedPrivateKeyInfo is, well, an encrypted
            // PrivateKeyInfo. Usually, strong crypto is used in
            // an EncryptedPrivateKeyInfo.
            EncryptedPrivateKeyInfo epki = ((EncryptedPrivateKeyInfo) val);
            System.out.println(
                "content is EncryptedPrivateKeyInfo, algoid:"
                    + epki.getEncryptionAlgorithm().getOID());

            // Because we are in a PKCS #12 file, the passwords are
            // char-to-byte converted in a special way.  We have to
            // use the special converter class instead of the default.
            PrivateKeyInfo pki = epki.decrypt(pass, new org.mozilla.jss.pkcs12.PasswordConverter());

            // import the key into the key3.db
            CryptoToken tok = manager.getTokenByName("Internal Key Storage Token");
            CryptoStore store = tok.getCryptoStore();
            tok.login(new ConsolePasswordCallback());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            pki.encode(baos);
            store.importPrivateKey(baos.toByteArray(), PrivateKey.RSA);

            // re-encrypt the PrivateKeyInfo with the new password
            // and random salt
            byte[] salt = new byte[PBEAlgorithm.PBE_SHA1_DES3_CBC.getSaltLength()];
            JSSSecureRandom rand = CryptoManager.getInstance().getSecureRNG();
            rand.nextBytes(salt);
            epki =
                EncryptedPrivateKeyInfo.createPBE(
                    PBEAlgorithm.PBE_SHA1_DES3_CBC, newPass, salt, 1, new PasswordConverter(), pki);

            // Overwrite the previous EncryptedPrivateKeyInfo with
            // this new one we just created using the new password.
            // This is what will get put in the new PKCS #12 file
            // we are creating.
            safeContents.insertElementAt(
                new SafeBag(safeBag.getBagType(), epki, safeBag.getBagAttributes()), i);
            safeContents.removeElementAt(i + 1);

          } else if (val instanceof CertBag) {
            System.out.println("content is CertBag");
            CertBag cb = (CertBag) val;
            if (cb.getCertType().equals(CertBag.X509_CERT_TYPE)) {
              // this is an X.509 certificate
              OCTET_STRING os = (OCTET_STRING) cb.getInterpretedCert();
              Certificate cert =
                  (Certificate) ASN1Util.decode(Certificate.getTemplate(), os.toByteArray());
              cert.getInfo().print(System.out);
            } else {
              System.out.println("Unrecognized cert type");
            }
          } else {
            System.out.println("content is ANY");
          }
        }

        // Add the new safe contents to the new authsafes
        if (authSafes.safeContentsIsEncrypted(i)) {
          newAuthSafes.addEncryptedSafeContents(
              authSafes.DEFAULT_KEY_GEN_ALG,
              newPass,
              null,
              authSafes.DEFAULT_ITERATIONS,
              safeContents);
        } else {
          newAuthSafes.addSafeContents(safeContents);
        }
      }

      // Create new PFX from the new authsafes
      PFX newPfx = new PFX(newAuthSafes);

      // Add a MAC to the new PFX
      newPfx.computeMacData(newPass, null, PFX.DEFAULT_ITERATIONS);

      // write the new PFX out to a file
      FileOutputStream fos = new FileOutputStream(args[2]);
      newPfx.encode(fos);
      fos.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }