Encode an EC Private key
@param oid - curve to use
@param keyBytes - bytes of the key
@param spki - optional SPKI
@return encoded private key
@throws CoseException - from lower level
497085
public static byte[] EncodeEcPrivateKey(byte[] oid, byte[] keyBytes, byte[] spki) throws CoseException
    {
        //  ECPrivateKey ::= SEQUENCE {
        //     version  INTEGER {1}
        //     privateKey OCTET STRING
        //     parameters [0] OBJECT IDENTIFIER = named curve
        //     public key [1] BIT STRING OPTIONAL
        //  }
        //

        ArrayList<byte[]> xxx = new ArrayList<byte[]>();
        xxx.add(new byte[]{2, 1, 1});
        xxx.add(OctetStringTag);
        xxx.add(ComputeLength(keyBytes.length));
        xxx.add(keyBytes);
        xxx.add(new byte[]{(byte)0xa0});
        xxx.add(ComputeLength(oid.length));
        xxx.add(oid);
        if (spki != null) {
            xxx.add(new byte[]{(byte)0xa1});
            xxx.add(ComputeLength(spki.length+1));
            xxx.add(new byte[]{0});
            xxx.add(spki);
        }
        
        byte[] ecPrivateKey = Sequence(xxx);
     
        return ecPrivateKey;
    }
590721
function encodePBES2(decoded){
  const epki = { encryptionAlgorithm: {} };

  // algorithm
  epki.encryptionAlgorithm.algorithm = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].oid;

  // kdf
  const kdf = decoded.encryptionAlgorithm.parameters.keyDerivationFunc;
  if(kdf.algorithm === 'pbkdf2') {
    kdf.parameters.prf.algorithm = params.pbkdf2Prfs[kdf.parameters.prf.algorithm].oid;
    kdf.parameters = PBKDF2Params.encode(kdf.parameters, 'der');
  } else throw new Error('UnsupportedKDF');
  kdf.algorithm = params.keyDerivationFunctions[kdf.algorithm].oid;

  // encryptionScheme
  const eS = decoded.encryptionAlgorithm.parameters.encryptionScheme;
  if(Object.keys(PBES2ESParams).indexOf(eS.algorithm) >= 0){
    eS.parameters = PBES2ESParams[eS.algorithm].encode(eS.parameters, 'der');
  } else throw new Error('UnsupportedCipher');
  eS.algorithm = params.encryptionSchemes[eS.algorithm].oid;

  // params
  epki.encryptionAlgorithm.parameters = PBES2Params.encode({ keyDerivationFunc: kdf, encryptionScheme: eS }, 'der');

  // encoded data
  epki.encryptedData = decoded.encryptedData;
  return EncryptedPrivateKeyInfo.encode(epki, 'der');
}
476573
public static ArrayList<TagValue> DecodeSubjectPublicKeyInfo(byte[] encoding) throws CoseException
    {
        TagValue spki = DecodeCompound(0, encoding);
        if (spki.tag != 0x30) throw new CoseException("Invalid SPKI");
        ArrayList<TagValue> tvl = spki.list;
        if (tvl.size() != 2) throw new CoseException("Invalid SPKI");
        
        if (tvl.get(0).tag != 0x30) throw new CoseException("Invalid SPKI");
        if (tvl.get(0).list.isEmpty() || tvl.get(0).list.size() > 2) {
            throw new CoseException("Invalid SPKI");
        }
        if (tvl.get(0).list.get(0).tag != 6) throw new CoseException("Invalid SPKI");
        //  tvl.get(0).list.get(1).tag is an ANY so needs to be checked elsewhere
        if (tvl.get(1).tag != 3) throw new CoseException("Invalid SPKI");
        
        return tvl;
    }
466335
public static PublicKey generatePublicKey(String algorithm, byte[] key) {
		if (null == key) {
			return null;
		}
		return generatePublicKey(algorithm, new X509EncodedKeySpec(key));
	}
895567
public static byte[] encrypt(byte[] contentByteArray, PublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(contentByteArray);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }
832429
public static String decryptByPrivateKey(String data, String privateKey) throws Exception {
		return decryptByPrivateKey(data, privateKey, "RSA/ECB/PKCS1Padding");
	}
728721
function _rsapem_privateKeyToPkcs8HexString(rsaKey) {
	var zeroInteger = "020100";
    var encodedIdentifier = "06092A864886F70D010101";
    var encodedNull = "0500";
    var headerSequence = "300D" + encodedIdentifier + encodedNull;
    var keySequence = _rsapem_privateKeyToPkcs1HexString(rsaKey);
    
    var keyOctetString = "04" + _rsapem_encodeLength(keySequence.length / 2) + keySequence;
    
    var mainSequence = zeroInteger + headerSequence + keyOctetString;
    return "30" + _rsapem_encodeLength(mainSequence.length / 2) + mainSequence;
}
721777
byte getKeyByte(int keyId, int byteId)
    {
        if (byteId >= _keys[keyId].length)
        {
            return 0;
        }
        return _keys[keyId][byteId];
    }
870689
public byte[] decryptSharedKey(byte[] sharedKey, Key pKey) throws java.io.IOException {
        byte[] decryptedSharedKey = null;
        if (sharedKey == null) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "ERROR!!! shared key is null!");
            }
            return null;
        }

        if (encryptor == null) {
            byte[] encodedPublicKey = pKey.getEncoded();
            encryptor = new AuditKeyEncryptor(encodedPublicKey);
        }

        byte[] encodedPublicKey = pKey.getEncoded();

        decryptedSharedKey = encryptor.decrypt(sharedKey);

        return decryptedSharedKey;
    }
532451
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed) {
        ECPoint point = publicPointFromPrivate(privKey);
        return point.getEncoded(compressed);
    }
1077500
private PrivateKey readEcPrivateKey(String fileName) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, NoSuchProviderException
    {
    	StringBuilder sb = new StringBuilder();
    	BufferedReader br = new BufferedReader(new FileReader(fileName));
    	try {
	    	char[] cbuf = new char[1024];
	    	for (int i=0; i <= 10*1024; i++) {
	    		if (!br.ready())
	    			break;
	    		int len = br.read(cbuf, i*1024, 1024);
	    		sb.append(cbuf, 0, len);
	    	}
	    	if (br.ready()) {
	    		throw new IndexOutOfBoundsException("JWK file larger than 10MB");
	    	}
	    	Type mapType = new TypeToken<Map<String, String>>(){}.getType();
	    	Map<String, String> son = new Gson().fromJson(sb.toString(), mapType);
	    	try {
				@SuppressWarnings({ "unchecked", "rawtypes" })
				EllipticCurveJsonWebKey jwk = new EllipticCurveJsonWebKey((Map<String, Object>)(Map)son);
				Base64Encoder enc = new Base64Encoder();
				ByteArrayOutputStream os = new ByteArrayOutputStream();
	        	enc.encode(jwk.getPrivateKey().getEncoded(), 0, jwk.getPrivateKey().getEncoded().length, os);
				return jwk.getPrivateKey();
			} catch (JoseException e1) {
				e1.printStackTrace();
			}
	        return null;
    	} finally {
    		br.close();
    	}
    }
1015511
@Override
    public String encryptAES(String value, String privateKey) {
        try {
            byte[] raw = privateKey.getBytes(UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, AES_ECB_ALGORITHM);
            Cipher cipher = Cipher.getInstance(AES_ECB_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            return hexToString(cipher.doFinal(value.getBytes(Charsets.UTF_8)));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException |
                InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
            throw new IllegalStateException(e);
        }
    }
932047
public static PrivateKey createPrivateKey(byte[] privateKey) {
    if (privateKey == null) {
      return null;
    }

    try {
      KeyFactory fac = KeyFactory.getInstance("RSA");
      EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
      return fac.generatePrivate(spec);
    }
    catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(e);
    }
    catch (InvalidKeySpecException e) {
      throw new IllegalStateException(e);
    }
  }
612141
public static byte[] keyGenPrivate(byte[] randomBytes) {

        if (randomBytes.length < 32) {
            throw new RuntimeException("Random bytes too small");
        }

        // Hashing Random Bytes instead of using random bytes directly
        // Just in case as reference ed255519 implementation do same
        byte[] privateKey = new byte[32];
        SHA256 sha256 = new SHA256();
        sha256.update(randomBytes, 0, randomBytes.length);
        sha256.doFinal(privateKey, 0);

        // Performing bit's flipping
        privateKey[0] &= 248;
        privateKey[31] &= 127;
        privateKey[31] |= 64;

        return privateKey;
    }
1242988
public static ArrayList<TagValue> DecodePKCS8(byte[] encodedData) throws CoseException 
    {
        TagValue pkcs8 = DecodeCompound(0, encodedData);
        if (pkcs8.tag != 0x30) throw new CoseException("Invalid PKCS8 structure");
        ArrayList<TagValue> retValue = pkcs8.list;
        if (retValue.size() != 3 && retValue.size() != 4) {
            throw new CoseException("Invalid PKCS8 structure");
        }

        // Version number - we currently only support one version
        if (retValue.get(0).tag != 2 && ((byte[]) retValue.get(0).value)[0] != 0) {
            throw new CoseException("Invalid PKCS8 structure");
        }

        // Algorithm identifier
        if (retValue.get(1).tag != 0x30) throw new CoseException("Invalid PKCS8 structure");
        if (retValue.get(1).list.isEmpty() || retValue.get(1).list.size() > 2) {
            throw new CoseException("Invalid PKCS8 structure");
        }
        if (retValue.get(1).list.get(0).tag != 6) throw new CoseException("Invalid PKCS8 structure");
        //  Dont check the next item as it is an ANY
        
        if (retValue.get(2).tag != 4) throw new CoseException("Invalid PKCS8 structure");
        
        // This is attributes, but we are not going to check for correctness.
        if (retValue.size() == 4 && retValue.get(3).tag != 0xa0) {
            throw new CoseException("Invalid PKCS8 structure");
        }
        
        //  Decode the contents of the octet string PrivateKey
        
        byte[] pk = (byte[]) retValue.get(2).value;
        TagValue pkd = DecodeCompound(0, pk);
        ArrayList<TagValue> pkdl = pkd.list;
        if (pkd.tag != 0x30) throw new CoseException("Invalid ECPrivateKey");
        if (pkdl.size() < 2 || pkdl.size() > 4) throw new CoseException("Invalid ECPrivateKey");
        
        if (pkdl.get(0).tag != 2 && ((byte[]) retValue.get(0).value)[0] != 1) {
            throw new CoseException("Invalid ECPrivateKey");
        }
        
        if (pkdl.get(1).tag != 4) throw new CoseException("Invalid ECPrivateKey");
        
        if (pkdl.size() > 2) {
            if ((pkdl.get(2).tag & 0xff) != 0xA0) {
                if (pkdl.size() != 3 || (pkdl.get(2).tag & 0xff) != 0xa1) {
                    throw new CoseException("Invalid ECPrivateKey");
                }
            } else {
                if (pkdl.size() == 4 && (pkdl.get(3).tag & 0xff) != 0xa1) throw new CoseException("Invalid ECPrivateKey");                
            }
        }
        
        retValue.get(2).list = pkdl;
        retValue.get(2).value = null;
        retValue.get(2).tag = 0x30;
        
        return retValue;
    }
640278
public byte[] createSecret (PublicKeyCredentials pkcred, PrivateKey key, int length)
    {
        _data = new AuthResponseData();
        byte[] clientSecret = pkcred.getSecret(key);
        if (clientSecret == null) {
            _data.code = FAILED_TO_SECURE;
            return null;
        }
        byte[] secret = SecureUtil.createRandomKey(length);
        _data.code = StringUtil.hexlate(SecureUtil.xorBytes(secret, clientSecret));
        return secret;
    }
904846
public static Curve25519KeyPair keyGen(byte[] randomBytes) throws NoSuchAlgorithmException, DigestException {
        byte[] privateKey = keyGenPrivate(randomBytes);
        byte[] publicKey = keyGenPublic(privateKey);
        return new Curve25519KeyPair(publicKey, privateKey);
    }