Example usage for org.bouncycastle.crypto.digests SHA1Digest doFinal

List of usage examples for org.bouncycastle.crypto.digests SHA1Digest doFinal

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.digests SHA1Digest doFinal.

Prototype

public int doFinal(byte[] out, int outOff) 

Source Link

Usage

From source file:VerifyDescriptors.java

License:Open Source License

private static void verifyConsensuses() throws Exception {
    File certsDirectory = new File("in/certs");
    File consensusDirectory = new File("in/consensuses");
    if (!certsDirectory.exists() || !consensusDirectory.exists()) {
        return;//from  w  ww  .ja  va  2s  .  c  o m
    }
    Map<String, String> signingKeys = new HashMap<String, String>();

    DescriptorReader certsReader = DescriptorSourceFactory.createDescriptorReader();
    certsReader.addDirectory(certsDirectory);
    Iterator<DescriptorFile> descriptorFiles = certsReader.readDescriptors();
    int processedCerts = 0, verifiedCerts = 0;
    while (descriptorFiles.hasNext()) {
        DescriptorFile descriptorFile = descriptorFiles.next();
        if (descriptorFile.getException() != null) {
            System.err.println("Could not read/parse descriptor file " + descriptorFile.getFileName() + ": "
                    + descriptorFile.getException().getMessage());
            continue;
        }
        if (descriptorFile.getDescriptors() == null) {
            continue;
        }
        for (Descriptor descriptor : descriptorFile.getDescriptors()) {
            if (!(descriptor instanceof DirectoryKeyCertificate)) {
                continue;
            }
            DirectoryKeyCertificate cert = (DirectoryKeyCertificate) descriptor;
            boolean isVerified = true;

            /* Verify that the contained fingerprint is a hash of the signing
             * key. */
            String dirIdentityKeyHashString = determineKeyHash(cert.getDirIdentityKey());
            String fingerprintString = cert.getFingerprint().toLowerCase();
            if (!dirIdentityKeyHashString.equals(fingerprintString)) {
                System.out.println("In " + descriptorFile.getFile()
                        + ", the calculated directory identity key hash " + dirIdentityKeyHashString
                        + " does not match the contained fingerprint " + fingerprintString + "!");
                isVerified = false;
            }

            /* Verify that the router signature was created using the signing
             * key. */
            if (!verifySignature(cert.getCertificateDigest(), cert.getDirKeyCertification(),
                    cert.getDirIdentityKey())) {
                System.out.println("In " + descriptorFile.getFile()
                        + ", the decrypted directory key certification does not "
                        + "match the certificate digest!");
                isVerified = false;
            }

            /* Determine the signing key digest and remember the signing key
             * to verify consensus signatures. */
            String dirSigningKeyString = cert.getDirSigningKey();
            PEMReader pemReader2 = new PEMReader(new StringReader(dirSigningKeyString));
            RSAPublicKey dirSigningKey = (RSAPublicKey) pemReader2.readObject();
            ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
            new ASN1OutputStream(baos2)
                    .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirSigningKey.getModulus(),
                            dirSigningKey.getPublicExponent()).toASN1Primitive());
            byte[] pkcs2 = baos2.toByteArray();
            byte[] dirSigningKeyHashBytes = new byte[20];
            SHA1Digest sha1_2 = new SHA1Digest();
            sha1_2.update(pkcs2, 0, pkcs2.length);
            sha1_2.doFinal(dirSigningKeyHashBytes, 0);
            String dirSigningKeyHashString = Hex.encodeHexString(dirSigningKeyHashBytes).toUpperCase();
            signingKeys.put(dirSigningKeyHashString, cert.getDirSigningKey());

            processedCerts++;
            if (isVerified) {
                verifiedCerts++;
            }
        }
    }
    System.out.println("Verified " + verifiedCerts + "/" + processedCerts + " certs.");

    DescriptorReader consensusReader = DescriptorSourceFactory.createDescriptorReader();
    consensusReader.addDirectory(consensusDirectory);
    Iterator<DescriptorFile> consensusFiles = consensusReader.readDescriptors();
    int processedConsensuses = 0, verifiedConsensuses = 0;
    while (consensusFiles.hasNext()) {
        DescriptorFile consensusFile = consensusFiles.next();
        if (consensusFile.getException() != null) {
            System.err.println("Could not read/parse descriptor file " + consensusFile.getFileName() + ": "
                    + consensusFile.getException().getMessage());
            continue;
        }
        if (consensusFile.getDescriptors() == null) {
            continue;
        }
        for (Descriptor descriptor : consensusFile.getDescriptors()) {
            if (!(descriptor instanceof RelayNetworkStatusConsensus)) {
                continue;
            }
            RelayNetworkStatusConsensus consensus = (RelayNetworkStatusConsensus) descriptor;
            boolean isVerified = true;

            /* Verify all signatures using the corresponding certificates. */
            if (consensus.getDirectorySignatures().isEmpty()) {
                System.out.println(consensusFile.getFile() + " does not contain any signatures.");
                continue;
            }
            for (DirectorySignature signature : consensus.getDirectorySignatures().values()) {
                String signingKeyDigest = signature.getSigningKeyDigest();
                if (!signingKeys.containsKey(signingKeyDigest)) {
                    System.out.println("Cannot find signing key with digest " + signingKeyDigest + "!");
                }
                if (!verifySignature(consensus.getConsensusDigest(), signature.getSignature(),
                        signingKeys.get(signingKeyDigest))) {
                    System.out.println("In " + consensusFile.getFile()
                            + ", the decrypted signature digest does not match the " + "consensus digest!");
                    isVerified = false;
                }
            }
            processedConsensuses++;
            if (isVerified) {
                verifiedConsensuses++;
            }
        }
    }
    System.out.println("Verified " + verifiedConsensuses + "/" + processedConsensuses + " consensuses.");
}

From source file:VerifyDescriptors.java

License:Open Source License

private static String determineKeyHash(String key) throws Exception {
    PEMReader pemReader = new PEMReader(new StringReader(key));
    RSAPublicKey dirIdentityKey = (RSAPublicKey) pemReader.readObject();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new ASN1OutputStream(baos)
            .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirIdentityKey.getModulus(),
                    dirIdentityKey.getPublicExponent()).toASN1Primitive());
    byte[] pkcs = baos.toByteArray();
    byte[] dirIdentityKeyHashBytes = new byte[20];
    SHA1Digest sha1 = new SHA1Digest();
    sha1.update(pkcs, 0, pkcs.length);//from w  ww  .  j  ava2s  .  co m
    sha1.doFinal(dirIdentityKeyHashBytes, 0);
    String keyHash = Hex.encodeHexString(dirIdentityKeyHashBytes);
    return keyHash;
}

From source file:ch.bfh.unicert.certimport.CertificateIssuer.java

License:GNU General Public License

public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity,
        String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL,
        String section) throws CertificateCreationException {

    X509Certificate caCert;/*from  ww  w.j  a v a  2s.  c  o m*/
    RSAPrivateCrtKey privKey;
    try {
        caCert = this.readIssuerCertificate(this.issuerId);
        privKey = this.readPrivateKey(this.issuerId, this.privKeyPass);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) {
        logger.log(Level.SEVERE, null, ex);
        throw new CertificateCreationException("230 Could not create client certificate. Key error");
    }

    RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey);

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(getExpiryDate(validity).getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(),
            id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(),
            id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles,
            id.getIdentityProvider(), extensionMap);

    //post message on UniBoard if corresponding JNDI parameter is defined
    postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(),
            privKey);

    return cert;

}

From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java

License:GNU General Public License

/**
 * Actually creates the requestor certificate.
 *
 * @param id requestor identity data//www  . j a  va 2  s.  c  o  m
 * @param caCert certificate of the certification authority
 * @param cipherParams issuer private key parameters used for signing
 * @param pk public key of the requestor to certify
 * @param expiry the expiry date
 * @param applicationIdentifier the application identifier for which te certificate is issued
 * @param role role for which the certificate is issued
 * @return the certificate object containing the X509 certificate
 * @throws CertificateCreationException if an error occurs
 */
private Certificate createClientCertificate(IdentityData id, X509Certificate caCert,
        CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier,
        String[] roles) throws CertificateCreationException {

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(expiry.getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException
            | NoSuchProviderException | InvalidCipherTextException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(),
            id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(),
            id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap);

}

From source file:com.identarian.infocard.opensso.rp.InfocardClaims.java

License:CDDL license

public static String friendlyPPID(String ppid) {
    // code map//from  w ww .  j  a va  2  s. c  om
    char[] ss = { 'Q', 'L', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
            'K', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

    // base 64 decoding
    byte[] b = Base64.decode(ppid.getBytes());

    // sha1 decoding
    SHA1Digest digEng = new SHA1Digest();
    digEng.update(b, 0, b.length);
    byte[] b1 = new byte[digEng.getDigestSize()];
    digEng.doFinal(b1, 0);

    // convert the bytes to ints
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 10; i++) {
        int ii = byte2int(b1[i]) % 32;
        if (i == 3 || i == 7) {
            sb.append("-");
        }
        // mapping of the int to mapping code
        sb.append(ss[ii]);
    }
    return sb.toString();
}

From source file:com.injoit.examplechat.util.Util.java

License:Open Source License

/**
 * Returns a SHA1 digest of the given string, in hex values lowercase.
 * @param _str/*from w ww .  ja  va  2  s.c  o m*/
 */
public static String sha1(String _str) {
    String res;
    SHA1Digest digest = new SHA1Digest();
    String tmp = _str;
    byte in[] = tmp.getBytes();
    digest.update(in, 0, in.length);
    byte out[] = new byte[20];
    digest.doFinal(out, 0);

    // builds the hex string (lowercase)
    res = "";
    tmp = ""; // tmp = two characters to append to the hex string
    for (int i = 0; i < 20; i++) {
        int unsigned = out[i];
        if (out[i] < 0) {
            unsigned += 256;
        }
        tmp = Integer.toHexString(unsigned);
        if (tmp.length() == 1) {
            tmp = "0" + tmp;
        }
        res = res + tmp;
    }

    return res;
}

From source file:com.injoit.examplechat.util.Util.java

License:Open Source License

/**
 * Returns a SHA1 digest of the given array of bytes, in hex values lowercase.
 * @param _str//from  www  .  j a  va2s. c o  m
 */
public static String sha1(byte[] in) {
    String res;
    SHA1Digest digest = new SHA1Digest();
    String tmp;

    digest.update(in, 0, in.length);
    byte out[] = new byte[20];
    digest.doFinal(out, 0);

    // builds the hex string (lowercase)
    res = "";
    tmp = ""; // tmp = two characters to append to the hex string
    for (int i = 0; i < 20; i++) {
        int unsigned = out[i];
        if (out[i] < 0) {
            unsigned += 256;
        }
        tmp = Integer.toHexString(unsigned);
        if (tmp.length() == 1) {
            tmp = "0" + tmp;
        }
        res = res + tmp;
    }

    return res;
}

From source file:com.jrdp.core.encryption.RC4Session.java

License:Apache License

/**
 * Generates a Salted MAC for the current packet
 * @see <a href=http://msdn.microsoft.com/en-us/library/cc240789(v=PROT.10).aspx>
 * 5.3.6.1.1 Salted MAC Generation</a>
 *//*from   www .  j  a va  2  s  . c  o  m*/
@Override
public byte[] createMac(byte[] data) {
    SHA1Digest sha1 = new SHA1Digest();
    sha1.update(macKey, 0, macKey.length);
    sha1.update(Constants.pad36, 0, Constants.pad36.length);
    byte[] length = new byte[4];
    BitManip.setLittleEndian(length, 0, data.length);
    sha1.update(length, 0, length.length);
    sha1.update(data, 0, data.length);
    byte[] sha1Digest = new byte[Constants.SHA1_DIGEST_LENGTH];
    sha1.doFinal(sha1Digest, 0);

    MD5Digest md5 = new MD5Digest();
    md5.update(macKey, 0, macKey.length);
    md5.update(Constants.pad5c, 0, Constants.pad5c.length);
    md5.update(sha1Digest, 0, sha1Digest.length);
    byte[] md5Digest = new byte[Constants.MD5_DIGEST_LENGTH];
    md5.doFinal(md5Digest, 0);

    byte[] mac = new byte[8];
    System.arraycopy(md5Digest, 0, mac, 0, 8);

    return mac;
}

From source file:com.jrdp.core.encryption.RC4Session.java

License:Apache License

private byte[] updateRc4Key(byte[] originalKey, byte[] currentKey) {
    int keySize = 0;
    switch (encryptionMethod) {
    case Constants.ENCRYPTION_128BIT:
        keySize = 16;/*from   w  ww. java2  s. c  om*/
        break;
    case Constants.ENCRYPTION_40BIT:
    case Constants.ENCRYPTION_56BIT:
        keySize = 8;
        break;
    case Constants.ENCRYPTION_NONE:
    case Constants.ENCRYPTION_FIPS:
        //Should never happen...
        return null;
    }

    SHA1Digest sha1 = new SHA1Digest();
    sha1.update(originalKey, 0, keySize);
    sha1.update(Constants.pad36, 0, Constants.pad36.length);
    sha1.update(currentKey, 0, currentKey.length);
    byte[] shaComponent = new byte[Rdp.SHA1_DIGEST_LENGTH];
    sha1.doFinal(shaComponent, 0);

    //StringManip.print(shaComponent, "SHA1:");

    MD5Digest md5 = new MD5Digest();
    md5.update(originalKey, 0, keySize);
    md5.update(Constants.pad5c, 0, Constants.pad5c.length);
    md5.update(shaComponent, 0, shaComponent.length);
    byte[] tempKey = new byte[Rdp.MD5_DIGEST_LENGTH];
    md5.doFinal(tempKey, 0);

    //StringManip.print(tempKey, "MD5:");

    RC4Engine rc4 = new RC4Engine();
    if (keySize == 16) {
        byte[] newKey = new byte[tempKey.length];
        rc4.init(true, new KeyParameter(tempKey));
        rc4.processBytes(tempKey, 0, tempKey.length, newKey, 0);
        return newKey;
    } else {
        byte[] newKey = new byte[8];
        byte[] smallerTmpKey = new byte[8];
        System.arraycopy(tempKey, 0, smallerTmpKey, 0, 8);
        rc4.init(true, new KeyParameter(smallerTmpKey));
        rc4.processBytes(smallerTmpKey, 0, 8, newKey, 0);
        newKey[0] = (byte) 0xd1;
        if (encryptionMethod == Constants.ENCRYPTION_40BIT) {
            newKey[1] = 0x26;
            newKey[2] = (byte) 0x9e;
        }
        return newKey;
    }
}

From source file:com.jrdp.core.remote.rdp.Secure.java

License:Apache License

private static byte[] saltedHash(byte[] clientRandom, byte[] serverRandom, byte[] salt, byte[][] in) {
    byte[] saltedHash = new byte[MD5_DIGEST_LENGTH * in.length];
    for (int i = 0; i < in.length; i++) {
        SHA1Digest sha1 = new SHA1Digest();
        sha1.update(in[i], 0, in[i].length);
        sha1.update(salt, 0, salt.length);
        sha1.update(clientRandom, 0, clientRandom.length);
        sha1.update(serverRandom, 0, serverRandom.length);
        byte[] sha1Digest = new byte[SHA1_DIGEST_LENGTH];
        sha1.doFinal(sha1Digest, 0);

        MD5Digest md5 = new MD5Digest();
        md5.update(salt, 0, salt.length);
        md5.update(sha1Digest, 0, sha1Digest.length);
        byte[] md5Digest = new byte[MD5_DIGEST_LENGTH];
        md5.doFinal(md5Digest, 0);/*from   ww w  . j  av  a 2s  .  c  o  m*/

        System.arraycopy(md5Digest, 0, saltedHash, i * MD5_DIGEST_LENGTH, MD5_DIGEST_LENGTH);
    }
    return saltedHash;
}