ulValueLen when attribute is not available.
42 | */
43 | public static final long UNAVAILABLE_INFORMATION = -1L;
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/org/pkcs11/jacknji11/CKZ.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
3 | * Permission is hereby granted, free of charge, to any person obtaining a copy
4 | * of this software and associated documentation files (the "Software"), to deal
5 | * in the Software without restriction, including without limitation the rights
6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | * copies of the Software, and to permit persons to whom the Software is
8 | * furnished to do so, subject to the following conditions:
9 | *
10 | * The above copyright notice and this permission notice shall be included in
11 | * all copies or substantial portions of the Software.
12 | *
13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | * THE SOFTWARE.
20 | */
21 |
22 | package org.pkcs11.jacknji11;
23 |
24 | import java.util.Map;
25 |
26 | /**
27 | * CKZ_? constants.
28 | * @author Joel Hockey (joel.hockey@gmail.com)
29 | */
30 | public class CKZ {
31 | public static final long DATA_SPECIFIED = 0x00000001;
32 |
33 | /** Maps from long value to String description (variable name). */
34 | private static final Map'C_*' functions. There is little
6 | reason why you would ever want to invoke it directly, but you can.
7 | 'C_' at the start of the
10 | function name is removed since the 'C.' when you call the
11 | static methods of this class looks similar. In addition to calling
12 | the native methods, {@link org.pkcs11.jacknji11.C} provides logging
13 | through apache commons logging. You can use this if you require fine-grain
14 | control over something such as checking
15 | {@link org.pkcs11.jacknji11.CKR} return codes.
16 | Example usage: 26 |
27 | int TESTSLOT = 0; 28 | byte[] USER_PIN = "userpin".getBytes(); 29 | int session = CE.OpenSession(TESTSLOT); 30 | CE.LoginUser(session, USER_PIN); 31 | 32 | int des3key = CE.GenerateKey(session, new CKM(CKM.DES3_KEY_GEN), 33 | new CKA(CKA.VALUE_LEN, 24), 34 | new CKA(CKA.LABEL, "label"), 35 | new CKA(CKA.SENSITIVE, false), 36 | new CKA(CKA.DERIVE, true)); 37 | 38 | CE.EncryptInit(session, new CKM(CKM.DES3_CBC_PAD), des3key); 39 | byte[] plaintext = new byte[10]; 40 | byte[] encrypted = CE.Encrypt(session, plaintext); 41 | 42 | CE.DecryptInit(session, new CKM(CKM.DES3_CBC_PAD), des3key); 43 | byte[] decrypted = CE.Decrypt(session, encrypted); 44 | assertTrue(Arrays.equals(plaintext, decrypted)); 45 |46 | -------------------------------------------------------------------------------- /src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_MECHANISM_INFO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved. 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy 4 | * of this software and associated documentation files (the "Software"), to deal 5 | * in the Software without restriction, including without limitation the rights 6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | * copies of the Software, and to permit persons to whom the Software is 8 | * furnished to do so, subject to the following conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in 11 | * all copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | * THE SOFTWARE. 20 | */ 21 | 22 | package org.pkcs11.jacknji11.jffi; 23 | 24 | import jnr.ffi.Struct; 25 | 26 | import org.pkcs11.jacknji11.CK_MECHANISM_INFO; 27 | 28 | /** 29 | * JFFI wrapper for PKCS#11 CK_MECHANSIM_INFO struct. 30 | * @author Joel Hockey (joel.hockey@gmail.com) 31 | */ 32 | public class JFFI_CK_MECHANISM_INFO extends Struct { 33 | public long ulMinKeySize; 34 | public long ulMaxKeySize; 35 | public long flags; 36 | 37 | public JFFI_CK_MECHANISM_INFO() { 38 | super(jnr.ffi.Runtime.getSystemRuntime()); 39 | } 40 | 41 | public JFFI_CK_MECHANISM_INFO readFrom(CK_MECHANISM_INFO info) { 42 | ulMinKeySize = info.ulMinKeySize; 43 | ulMaxKeySize = info.ulMaxKeySize; 44 | flags = info.flags; 45 | return this; 46 | } 47 | 48 | public CK_MECHANISM_INFO writeTo(CK_MECHANISM_INFO info) { 49 | info.ulMinKeySize = ulMinKeySize; 50 | info.ulMaxKeySize = ulMaxKeySize; 51 | info.flags = flags; 52 | return info; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/h/rsa/cryptoki.h: -------------------------------------------------------------------------------- 1 | /* cryptoki.h include file for PKCS #11. */ 2 | /* $Revision: 1.4 $ */ 3 | 4 | /* License to copy and use this software is granted provided that it is 5 | * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface 6 | * (Cryptoki)" in all material mentioning or referencing this software. 7 | 8 | * License is also granted to make and use derivative works provided that 9 | * such works are identified as "derived from the RSA Security Inc. PKCS #11 10 | * Cryptographic Token Interface (Cryptoki)" in all material mentioning or 11 | * referencing the derived work. 12 | 13 | * RSA Security Inc. makes no representations concerning either the 14 | * merchantability of this software or the suitability of this software for 15 | * any particular purpose. It is provided "as is" without express or implied 16 | * warranty of any kind. 17 | */ 18 | 19 | /* This is a sample file containing the top level include directives 20 | * for building Win32 Cryptoki libraries and applications. 21 | */ 22 | 23 | #ifndef ___CRYPTOKI_H_INC___ 24 | #define ___CRYPTOKI_H_INC___ 25 | 26 | #pragma pack(push, cryptoki, 1) 27 | 28 | /* Specifies that the function is a DLL entry point. */ 29 | #define CK_IMPORT_SPEC __declspec(dllimport) 30 | 31 | /* Define CRYPTOKI_EXPORTS during the build of cryptoki libraries. Do 32 | * not define it in applications. 33 | */ 34 | #ifdef CRYPTOKI_EXPORTS 35 | /* Specified that the function is an exported DLL entry point. */ 36 | #define CK_EXPORT_SPEC __declspec(dllexport) 37 | #else 38 | #define CK_EXPORT_SPEC CK_IMPORT_SPEC 39 | #endif 40 | 41 | /* Ensures the calling convention for Win32 builds */ 42 | #define CK_CALL_SPEC __cdecl 43 | 44 | #define CK_PTR * 45 | 46 | #define CK_DEFINE_FUNCTION(returnType, name) \ 47 | returnType CK_EXPORT_SPEC CK_CALL_SPEC name 48 | 49 | #define CK_DECLARE_FUNCTION(returnType, name) \ 50 | returnType CK_EXPORT_SPEC CK_CALL_SPEC name 51 | 52 | #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ 53 | returnType CK_IMPORT_SPEC (CK_CALL_SPEC CK_PTR name) 54 | 55 | #define CK_CALLBACK_FUNCTION(returnType, name) \ 56 | returnType (CK_CALL_SPEC CK_PTR name) 57 | 58 | #ifndef NULL_PTR 59 | #define NULL_PTR 0 60 | #endif 61 | 62 | #include "pkcs11.h" 63 | 64 | #pragma pack(pop, cryptoki) 65 | 66 | #endif /* ___CRYPTOKI_H_INC___ */ 67 | -------------------------------------------------------------------------------- /src/main/java/org/pkcs11/jacknji11/CKRException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved. 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy 4 | * of this software and associated documentation files (the "Software"), to deal 5 | * in the Software without restriction, including without limitation the rights 6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | * copies of the Software, and to permit persons to whom the Software is 8 | * furnished to do so, subject to the following conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in 11 | * all copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | * THE SOFTWARE. 20 | */ 21 | 22 | package org.pkcs11.jacknji11; 23 | 24 | /** 25 | * Exception for CKR values that are non-zero (CKR.OK). 26 | * Used in {@link CE} interface as alternative to returning 27 | * CKR for every function. 28 | * @author Joel Hockey (joel.hockey@gmail.com) 29 | */ 30 | public class CKRException extends RuntimeException { 31 | private static final long serialVersionUID = 0x2841de9d258bab8bL; 32 | private long ckr; 33 | 34 | /** 35 | * Constructor with CKR value. 36 | * @param ckr CKR value. 37 | */ 38 | public CKRException(long ckr) { 39 | super(String.format("0x%08x: %s", ckr, CKR.L2S(ckr))); 40 | this.ckr = ckr; 41 | } 42 | 43 | /** 44 | * Constructor with message and CKR value. 45 | * @param msg message 46 | * @param ckr CKR value 47 | */ 48 | public CKRException(String msg, long ckr) { 49 | super(String.format("0x%08x: %s : %s", ckr, CKR.L2S(ckr), msg)); 50 | this.ckr = ckr; 51 | } 52 | 53 | /** @return CKR value */ 54 | public long getCKR() { return ckr; } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_SESSION_INFO.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved. 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy 4 | * of this software and associated documentation files (the "Software"), to deal 5 | * in the Software without restriction, including without limitation the rights 6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | * copies of the Software, and to permit persons to whom the Software is 8 | * furnished to do so, subject to the following conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in 11 | * all copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | * THE SOFTWARE. 20 | */ 21 | 22 | package org.pkcs11.jacknji11.jffi; 23 | 24 | import jnr.ffi.Struct; 25 | 26 | import org.pkcs11.jacknji11.CK_SESSION_INFO; 27 | 28 | /** 29 | * JFFI wrapper for PKCS#11 CK_SESSION_INFO struct. 30 | * @author Joel Hockey (joel.hockey@gmail.com) 31 | */ 32 | public class JFFI_CK_SESSION_INFO extends Struct { 33 | public long slotID; 34 | public long state; 35 | public long flags; 36 | public long ulDeviceError; 37 | 38 | public JFFI_CK_SESSION_INFO() { 39 | super(jnr.ffi.Runtime.getSystemRuntime()); 40 | } 41 | 42 | 43 | public JFFI_CK_SESSION_INFO readFrom(CK_SESSION_INFO info) { 44 | slotID = info.slotID; 45 | state = info.state; 46 | flags = info.flags; 47 | ulDeviceError = info.ulDeviceError; 48 | return this; 49 | } 50 | 51 | public CK_SESSION_INFO writeTo(CK_SESSION_INFO info) { 52 | info.slotID = slotID; 53 | info.state = state; 54 | info.flags = flags; 55 | info.ulDeviceError = ulDeviceError; 56 | return info; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CKA.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved. 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy 4 | * of this software and associated documentation files (the "Software"), to deal 5 | * in the Software without restriction, including without limitation the rights 6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | * copies of the Software, and to permit persons to whom the Software is 8 | * furnished to do so, subject to the following conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in 11 | * all copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | * THE SOFTWARE. 20 | */ 21 | 22 | package org.pkcs11.jacknji11.jffi; 23 | 24 | import jnr.ffi.Memory; 25 | import jnr.ffi.Struct; 26 | 27 | import org.pkcs11.jacknji11.CKA; 28 | 29 | /** 30 | * JFFI CK_ATTRIBUTE wrapper. 31 | * @author Joel Hockey (joel.hockey@gmail.com) 32 | */ 33 | public class JFFI_CKA extends Struct { 34 | public long type; 35 | public jnr.ffi.Pointer pValue; 36 | public long ulValueLen; 37 | 38 | public JFFI_CKA() { 39 | super(jnr.ffi.Runtime.getSystemRuntime()); 40 | } 41 | 42 | public JFFI_CKA readFrom(CKA cka) { 43 | type = cka.type; 44 | int len = cka.pValue != null ? cka.pValue.length : 0; 45 | if (len > 0) { 46 | pValue = Memory.allocate(jnr.ffi.Runtime.getSystemRuntime(), len); 47 | pValue.put(0, cka.pValue, 0, len); 48 | } 49 | ulValueLen = len; 50 | return this; 51 | } 52 | 53 | public CKA writeTo(CKA cka) { 54 | cka.type = (int) type; 55 | cka.ulValueLen = (int) ulValueLen; 56 | if (cka.ulValueLen > 0) { 57 | pValue.get(0, cka.pValue, 0, (int) cka.ulValueLen); 58 | } 59 | return cka; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/org/pkcs11/jacknji11/jna/JNA_CKM.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved. 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy 4 | * of this software and associated documentation files (the "Software"), to deal 5 | * in the Software without restriction, including without limitation the rights 6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | * copies of the Software, and to permit persons to whom the Software is 8 | * furnished to do so, subject to the following conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in 11 | * all copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | * THE SOFTWARE. 20 | */ 21 | 22 | package org.pkcs11.jacknji11.jna; 23 | 24 | import org.pkcs11.jacknji11.CKM; 25 | 26 | import java.util.Arrays; 27 | import java.util.List; 28 | 29 | import com.sun.jna.NativeLong; 30 | import com.sun.jna.Pointer; 31 | import com.sun.jna.Structure; 32 | 33 | 34 | /** 35 | * CKM_? constants and CK_MECHANISM struct wrapper. 36 | * @author Joel Hockey (joel.hockey@gmail.com) 37 | */ 38 | public class JNA_CKM extends Structure { 39 | public NativeLong mechanism; 40 | public Pointer pParameter; 41 | public NativeLong ulParameterLen; 42 | 43 | public JNA_CKM() { 44 | // Need to set alignment to none since 'pParameter' is not 45 | // aligned to a 8 byte boundary on Win64 (long is 4 bytes there) 46 | super(ALIGN_NONE); 47 | } 48 | 49 | @Override 50 | protected List
29 | * Unsigned big integers are encoded as big-endian byte arrays without leading zero bytes.
30 | *
31 | * @author Tomasz Wysocki
32 | */
33 | public class UBigInt {
34 |
35 | private UBigInt() {
36 | // utility class
37 | }
38 |
39 | /**
40 | * Encode unsigned big integer to byte array.
41 | *
42 | * @param value unsigned big integer
43 | * @return byte array with big-endian encoding without leading zero bytes,
44 | * the size of the array is the minimum required to represent the value.
45 | */
46 | public static byte[] ubigint2b(BigInteger value) {
47 | byte[] bytes = value.toByteArray();
48 | // strip initial zero if present as we are operating on unsigned values
49 | if (bytes.length > 1 && bytes[0] == 0) {
50 | bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
51 | }
52 | return bytes;
53 | }
54 |
55 | /**
56 | * Decode unsigned big integer from byte array.
57 | *
58 | * @param bytes byte array with big-endian encoding of unsigned big integer (highest bit is not a sign bit)
59 | * @return unsigned big integer
60 | */
61 | public static BigInteger b2ubigint(byte[] bytes) {
62 | return new BigInteger(1, bytes);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CKM.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
3 | * Permission is hereby granted, free of charge, to any person obtaining a copy
4 | * of this software and associated documentation files (the "Software"), to deal
5 | * in the Software without restriction, including without limitation the rights
6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | * copies of the Software, and to permit persons to whom the Software is
8 | * furnished to do so, subject to the following conditions:
9 | *
10 | * The above copyright notice and this permission notice shall be included in
11 | * all copies or substantial portions of the Software.
12 | *
13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | * THE SOFTWARE.
20 | */
21 |
22 | package org.pkcs11.jacknji11.jffi;
23 |
24 | import jnr.ffi.Memory;
25 | import jnr.ffi.Struct;
26 |
27 | import com.sun.jna.Native;
28 |
29 | import org.pkcs11.jacknji11.CKM;
30 |
31 | /**
32 | * JFFI CK_MECHANISM struct wrapper.
33 | * @author Joel Hockey (joel.hockey@gmail.com)
34 | */
35 | public class JFFI_CKM extends Struct {
36 | public long mechanism;
37 | public jnr.ffi.Pointer pParameter;
38 | public long ulParameterLen;
39 |
40 | public JFFI_CKM() {
41 | super(jnr.ffi.Runtime.getSystemRuntime());
42 | }
43 |
44 | public JFFI_CKM readFrom(CKM ckm) {
45 | mechanism = ckm.mechanism;
46 | int len = ckm.bParameter != null ? ckm.bParameter.length : 0;
47 | if (len > 0) {
48 | pParameter = Memory.allocate(jnr.ffi.Runtime.getSystemRuntime(), len);
49 | pParameter.put(0, ckm.bParameter, 0, len);
50 | }
51 | ulParameterLen = len;
52 | return this;
53 | }
54 |
55 | public JFFI_CKM readFromPointer(CKM pMechanism) {
56 | mechanism = pMechanism.mechanism;
57 | int len = pMechanism.pParameter != null ? Native.POINTER_SIZE : 0;
58 | if (len > 0) {
59 | byte[] ckmParamBytes = pMechanism.pParameter.getByteArray(0, len);
60 | pParameter = Memory.allocate(jnr.ffi.Runtime.getSystemRuntime(), len);
61 | pParameter.put(0, ckmParamBytes, 0, len);
62 | }
63 | ulParameterLen = len;
64 | return this;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/org/pkcs11/jacknji11/CK_INFO.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
3 | * Permission is hereby granted, free of charge, to any person obtaining a copy
4 | * of this software and associated documentation files (the "Software"), to deal
5 | * in the Software without restriction, including without limitation the rights
6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | * copies of the Software, and to permit persons to whom the Software is
8 | * furnished to do so, subject to the following conditions:
9 | *
10 | * The above copyright notice and this permission notice shall be included in
11 | * all copies or substantial portions of the Software.
12 | *
13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | * THE SOFTWARE.
20 | */
21 |
22 | package org.pkcs11.jacknji11;
23 |
24 | import java.util.Map;
25 |
26 | /**
27 | * PKCS#11 CK_INFO struct.
28 | * @author Joel Hockey (joel.hockey@gmail.com)
29 | */
30 | public class CK_INFO {
31 |
32 | /** Maps from long value to String description (variable name). */
33 | private static final Map
42 | * Use to avoid querying length of attributes for every call to C_GetAttributeValue.
43 | *
44 | * Note that implementations need to adhere strictly to PKCS#11 for this strategy
45 | * to work robustly. One detail that this implementation relies on is that PKCS#11,
46 | * base specification section 5.7.5 C_GetAttributeValue,
47 | * specifies returning CKR_BUFFER_TOO_SMALL and setting uLValueLen to
48 | * CK_UNAVAILABLE_INFORMATION, if sent a pre-allocated buffer that is too small to hold the value.
49 | * There are multuple variations of implementation errors with either the wrong return value
50 | * or failing to set uLValueLen to the correct value.
51 | * Due to these common implementation issued, using this strategy requires careful testing
52 | * with your HSM, for your use case.
53 | */
54 | class MaxLengthStrategy implements AttributeLengthStrategy {
55 |
56 | /**
57 | * Default of 2KB has been established by following facts:
58 | * Modulus of 15Kb RSA (maximum) is around 2KB.
59 | * For 8192 bit RSA (which is a practical limit) public keys are less than 2K while certificates
60 | * are just above about 2K (with standard set of extensions), but those should be rare. There is
61 | * a balance and limits are configurable for your own use case.
62 | *
63 | * Note: CKA_VALUE is used for certificate objects, and PQC key values, so it is large value as well
64 | * which is shame since value is typically used for symmetric keys which are relatively small size.
65 | *
66 | * If set to 0 then max length strategy is not used for large attributes.
67 | */
68 | public static final int DEFAULT_LARGE_ATTRIBUTE_LENGTH = 2048;
69 |
70 | /**
71 | * Default 72 (divisible by 8) bytes should be sufficient for most attributes including custom labels and ids
72 | * as well as EC P-521 compressed public key ( 1B tag | 66B x )
73 | */
74 | public static final int DEFAULT_REGULAR_ATTRIBUTE_LENGTH = 72;
75 |
76 | /**
77 | * Set of large attributes types established to potentially contain large values.
78 | */
79 | public static final long[] DEFAULT_LARGE_ATTRIBUTES = new long[]{
80 | CKA.MODULUS,
81 | CKA.PRIME_1,
82 | CKA.PRIME_2,
83 | CKA.EXPONENT_1,
84 | CKA.EXPONENT_2,
85 | CKA.COEFFICIENT,
86 | CKA.PRIVATE_EXPONENT,
87 | CKA.VALUE,
88 | CKA.EC_POINT,
89 | };
90 |
91 | /**
92 | * Large attribute types.
93 | */
94 | private final long[] largeAttributes;
95 |
96 | /**
97 | * Length for large attributes, if 0 then max length strategy is not used for large attributes.
98 | */
99 | private final int largeAttributeLength;
100 |
101 | /**
102 | * Default length for attributes, if 0 then max length strategy is not used for regular attributes.
103 | */
104 | private final int regularAttributeLength;
105 |
106 | /**
107 | * Constructor with default values.
108 | */
109 | public MaxLengthStrategy() {
110 | this(DEFAULT_REGULAR_ATTRIBUTE_LENGTH, DEFAULT_LARGE_ATTRIBUTES, DEFAULT_LARGE_ATTRIBUTE_LENGTH);
111 | }
112 |
113 | /**
114 | * Constructor with custom values.
115 | *
116 | * @param regularAttributeLength length for regular attributes
117 | * @param largeAttributes set of large attributes
118 | * @param largeAttributeLength length for large attributes
119 | */
120 | public MaxLengthStrategy(int regularAttributeLength, long[] largeAttributes, int largeAttributeLength) {
121 | this.largeAttributes = largeAttributes;
122 | this.regularAttributeLength = regularAttributeLength;
123 | this.largeAttributeLength = largeAttributeLength;
124 | }
125 |
126 | @Override
127 | public int getAttributeLength(long cka) {
128 | if (contains(largeAttributes, cka)) {
129 | return largeAttributeLength;
130 | } else {
131 | return regularAttributeLength;
132 | }
133 | }
134 |
135 | // simple check if array contains value
136 | private static boolean contains(long[] array, long value) {
137 | for (long l : array) {
138 | if (l == value) {
139 | return true;
140 | }
141 | }
142 | return false;
143 | }
144 | }
145 |
146 | /**
147 | * Strategy for querying length of attribute value in C_GetAttributeValue request
148 | * for every attribute.
149 | */
150 | class IndefiniteLengthStrategy implements AttributeLengthStrategy {
151 | @Override
152 | public int getAttributeLength(long cka) {
153 | return 0;
154 | }
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/src/main/h/rsa/pkcs11.h:
--------------------------------------------------------------------------------
1 | /* Copyright (c) OASIS Open 2016-2019. All Rights Reserved.
2 | * Distributed under the terms of the OASIS IPR Policy,
3 | * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
4 | * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
5 | * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
6 | */
7 |
8 | #ifndef _PKCS11_H_
9 | #define _PKCS11_H_ 1
10 |
11 | #ifdef __cplusplus
12 | extern "C" {
13 | #endif
14 |
15 | /* Before including this file (pkcs11.h) (or pkcs11t.h by
16 | * itself), 5 platform-specific macros must be defined. These
17 | * macros are described below, and typical definitions for them
18 | * are also given. Be advised that these definitions can depend
19 | * on both the platform and the compiler used (and possibly also
20 | * on whether a Cryptoki library is linked statically or
21 | * dynamically).
22 | *
23 | * In addition to defining these 5 macros, the packing convention
24 | * for Cryptoki structures should be set. The Cryptoki
25 | * convention on packing is that structures should be 1-byte
26 | * aligned.
27 | *
28 | * If you're using Windows this might be done by using the following
29 | * preprocessor directive before including pkcs11.h or pkcs11t.h:
30 | *
31 | * #pragma pack(push, cryptoki, 1)
32 | *
33 | * and using the following preprocessor directive after including
34 | * pkcs11.h or pkcs11t.h:
35 | *
36 | * #pragma pack(pop, cryptoki)
37 | *
38 | * In a UNIX environment, you're on your own for this. You might
39 | * not need to do (or be able to do!) anything.
40 | *
41 | *
42 | * Now for the macros:
43 | *
44 | *
45 | * 1. CK_PTR: The indirection string for making a pointer to an
46 | * object. It can be used like this:
47 | *
48 | * typedef CK_BYTE CK_PTR CK_BYTE_PTR;
49 | *
50 | * If you're using windows, it might be defined by:
51 | *
52 | * #define CK_PTR *
53 | *
54 | * In a typical UNIX environment, it might be defined by:
55 | *
56 | * #define CK_PTR *
57 | *
58 | *
59 | * 2. CK_DECLARE_FUNCTION(returnType, name): A macro which makes
60 | * an importable Cryptoki library function declaration out of a
61 | * return type and a function name. It should be used in the
62 | * following fashion:
63 | *
64 | * extern CK_DECLARE_FUNCTION(CK_RV, C_Initialize)(
65 | * CK_VOID_PTR pReserved
66 | * );
67 | *
68 | * If you're using Windows to declare a function in a Win32 cryptoki .dll,
69 | * it might be defined by:
70 | *
71 | * #define CK_DECLARE_FUNCTION(returnType, name) \
72 | * returnType __declspec(dllimport) name
73 | *
74 | * In a UNIX environment, it might be defined by:
75 | *
76 | * #define CK_DECLARE_FUNCTION(returnType, name) \
77 | * returnType name
78 | *
79 | *
80 | * 3. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro
81 | * which makes a Cryptoki API function pointer declaration or
82 | * function pointer type declaration out of a return type and a
83 | * function name. It should be used in the following fashion:
84 | *
85 | * // Define funcPtr to be a pointer to a Cryptoki API function
86 | * // taking arguments args and returning CK_RV.
87 | * CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtr)(args);
88 | *
89 | * or
90 | *
91 | * // Define funcPtrType to be the type of a pointer to a
92 | * // Cryptoki API function taking arguments args and returning
93 | * // CK_RV, and then define funcPtr to be a variable of type
94 | * // funcPtrType.
95 | * typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtrType)(args);
96 | * funcPtrType funcPtr;
97 | *
98 | * If you're using Windows to access
99 | * functions in a Win32 Cryptoki .dll, in might be defined by:
100 | *
101 | * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
102 | * returnType __declspec(dllimport) (* name)
103 | *
104 | * In a UNIX environment, it might be defined by:
105 | *
106 | * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
107 | * returnType (* name)
108 | *
109 | *
110 | * 4. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes
111 | * a function pointer type for an application callback out of
112 | * a return type for the callback and a name for the callback.
113 | * It should be used in the following fashion:
114 | *
115 | * CK_CALLBACK_FUNCTION(CK_RV, myCallback)(args);
116 | *
117 | * to declare a function pointer, myCallback, to a callback
118 | * which takes arguments args and returns a CK_RV. It can also
119 | * be used like this:
120 | *
121 | * typedef CK_CALLBACK_FUNCTION(CK_RV, myCallbackType)(args);
122 | * myCallbackType myCallback;
123 | *
124 | * If you're using Windows, it might be defined by:
125 | *
126 | * #define CK_CALLBACK_FUNCTION(returnType, name) \
127 | * returnType (* name)
128 | *
129 | * In a UNIX environment, it might be defined by:
130 | *
131 | * #define CK_CALLBACK_FUNCTION(returnType, name) \
132 | * returnType (* name)
133 | *
134 | *
135 | * 5. NULL_PTR: This macro is the value of a NULL pointer.
136 | *
137 | * In any ANSI/ISO C environment (and in many others as well),
138 | * this should best be defined by
139 | *
140 | * #ifndef NULL_PTR
141 | * #define NULL_PTR 0
142 | * #endif
143 | */
144 |
145 |
146 | /* All the various Cryptoki types and #define'd values are in the
147 | * file pkcs11t.h.
148 | */
149 | #include "pkcs11t.h"
150 |
151 | #define __PASTE(x,y) x##y
152 |
153 |
154 | /* ==============================================================
155 | * Define the "extern" form of all the entry points.
156 | * ==============================================================
157 | */
158 |
159 | #define CK_NEED_ARG_LIST 1
160 | #define CK_PKCS11_FUNCTION_INFO(name) \
161 | extern CK_DECLARE_FUNCTION(CK_RV, name)
162 |
163 | /* pkcs11f.h has all the information about the Cryptoki
164 | * function prototypes.
165 | */
166 | #include "pkcs11f.h"
167 |
168 | #undef CK_NEED_ARG_LIST
169 | #undef CK_PKCS11_FUNCTION_INFO
170 |
171 |
172 | /* ==============================================================
173 | * Define the typedef form of all the entry points. That is, for
174 | * each Cryptoki function C_XXX, define a type CK_C_XXX which is
175 | * a pointer to that kind of function.
176 | * ==============================================================
177 | */
178 |
179 | #define CK_NEED_ARG_LIST 1
180 | #define CK_PKCS11_FUNCTION_INFO(name) \
181 | typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name))
182 |
183 | /* pkcs11f.h has all the information about the Cryptoki
184 | * function prototypes.
185 | */
186 | #include "pkcs11f.h"
187 |
188 | #undef CK_NEED_ARG_LIST
189 | #undef CK_PKCS11_FUNCTION_INFO
190 |
191 |
192 | /* ==============================================================
193 | * Define structed vector of entry points. A CK_FUNCTION_LIST
194 | * contains a CK_VERSION indicating a library's Cryptoki version
195 | * and then a whole slew of function pointers to the routines in
196 | * the library. This type was declared, but not defined, in
197 | * pkcs11t.h.
198 | * ==============================================================
199 | */
200 |
201 | #define CK_PKCS11_FUNCTION_INFO(name) \
202 | __PASTE(CK_,name) name;
203 |
204 | /* Create the 3.0 Function list */
205 | struct CK_FUNCTION_LIST_3_0 {
206 |
207 | CK_VERSION version; /* Cryptoki version */
208 |
209 | /* Pile all the function pointers into the CK_FUNCTION_LIST. */
210 | /* pkcs11f.h has all the information about the Cryptoki
211 | * function prototypes.
212 | */
213 | #include "pkcs11f.h"
214 |
215 | };
216 |
217 | #define CK_PKCS11_2_0_ONLY 1
218 |
219 | /* Continue to define the old CK_FUNCTION_LIST */
220 | struct CK_FUNCTION_LIST {
221 |
222 | CK_VERSION version; /* Cryptoki version */
223 |
224 | /* Pile all the function pointers into the CK_FUNCTION_LIST. */
225 | /* pkcs11f.h has all the information about the Cryptoki
226 | * function prototypes.
227 | */
228 | #include "pkcs11f.h"
229 |
230 | };
231 |
232 | #undef CK_PKCS11_FUNCTION_INFO
233 | #undef CK_PKCS11_2_0_ONLY
234 |
235 |
236 | #undef __PASTE
237 |
238 | #ifdef __cplusplus
239 | }
240 | #endif
241 |
242 | #endif /* _PKCS11_H_ */
243 |
244 |
--------------------------------------------------------------------------------
/src/main/java/org/pkcs11/jacknji11/Hex.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2008-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a copy
5 | * of this software and associated documentation files (the "Software"), to deal
6 | * in the Software without restriction, including without limitation the rights
7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | * copies of the Software, and to permit persons to whom the Software is
9 | * furnished to do so, subject to the following conditions:
10 | *
11 | * The above copyright notice and this permission notice shall be included in
12 | * all copies or substantial portions of the Software.
13 | *
14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | * THE SOFTWARE.
21 | */
22 |
23 | package org.pkcs11.jacknji11;
24 |
25 |
26 | /**
27 | * Hex encoder.
28 | * @author Joel Hockey (joel.hockey@gmail.com)
29 | */
30 | public class Hex {
31 | /** Hex digits. 0123456789abcdef */
32 | public static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
33 |
34 | /** Hex string to byte lookup. -1 if non-hex, else hex nibble value. */
35 | public static final int[] HEX_S2B = new int[256];
36 |
37 | /** Hex byte to string lookup. returns 2-char hex encoding */
38 | public static final char[][] HEX_B2S = new char[256][];
39 |
40 | static {
41 | // init lookup tables
42 | // Hex S2B
43 | for (int i = 0; i < HEX_S2B.length; i++) {
44 | HEX_S2B[i] = -1;
45 | }
46 | for (int i = '0'; i <= '9'; i++) {
47 | HEX_S2B[i] = i - '0';
48 | }
49 | for (int i = 'A'; i <= 'F'; i++) {
50 | HEX_S2B[i] = i - 'A' + 10;
51 | }
52 | for (int i = 'a'; i <= 'f'; i++) {
53 | HEX_S2B[i] = i - 'a' + 10;
54 | }
55 |
56 | // Hex B2S
57 | for (int i = 0; i < HEX_DIGITS.length; i++) {
58 | for (int j = 0; j < HEX_DIGITS.length; j++) {
59 | HEX_B2S[i * 16 + j] = new char[] { HEX_DIGITS[i], HEX_DIGITS[j] };
60 | }
61 | }
62 | }
63 |
64 | /**
65 | * Returns lower case hex string representation of byte[].
66 | * @param buf byte array
67 | * @return lower case hex encoded string
68 | */
69 | public static String b2s(byte[] buf) {
70 | if (buf == null) return null;
71 | return b2s(buf, 0, buf.length);
72 | }
73 |
74 | /**
75 | * Returns hex string representation of byte[].
76 | * @param buf byte array
77 | * @param start pos in buf to start at
78 | * @param len number of bytes to encode
79 | * @return hex encoded string
80 | */
81 | public static String b2s(byte[] buf, int start, int len) {
82 | if (buf == null) return null;
83 | if (start < 0 || start > buf.length) {
84 | throw new IllegalArgumentException("start index must be between 0 and buf.length [" + buf.length + "]. Got value" + start);
85 | }
86 |
87 | if (len < 0 || start + len > buf.length) {
88 | throw new IllegalArgumentException("len must be between 0 and (buf.length - start) ["
89 | + buf.length + " - " + start + " = " + (buf.length - start)+ "]. Got value " + len);
90 | }
91 |
92 | char[] cbuf = new char[len * 2];
93 | for (int i = 0; i < len; i++) {
94 | System.arraycopy(HEX_B2S[buf[start + i] & 0xff], 0, cbuf, i * 2, 2);
95 | }
96 | return new String(cbuf);
97 | }
98 |
99 | /**
100 | * Return 8 char (lower case) hex encoded 32-bit big-endian value
101 | * @param num number to encode
102 | * @return 8 char (lower case) hex encoded 32-bit big-endian value
103 | */
104 | public static String i2s(int num) {
105 | char[] cbuf = new char[8];
106 | // start at rhs
107 | for (int i = 3; i >= 0; i--) {
108 | System.arraycopy(Hex.HEX_B2S[num & 0xff] , 0, cbuf, i*2, 2);
109 | num >>>= 8;
110 | }
111 | return new String(cbuf);
112 | }
113 |
114 | /**
115 | * Returns byte[] from hex string.
116 | * Ignores any non-hex chars.
117 | * Pads extra 0 on end if odd number of hex chars.
118 | * @param hex hex string e.g. "01ff"
119 | * @return byte array. e.g. byte[] {1, 255}
120 | */
121 | public static byte[] s2b(String hex) {
122 | if (hex == null) return null;
123 |
124 | byte[] buf = new byte[(hex.length() + 1) / 2];
125 | int tmpbuf = 0; // stores nibble
126 | int bits = 0; // num of bits in tmpbuf
127 | int i = 0; // index into hex
128 | int j = 0; // index into result buf
129 | while (i < hex.length()) {
130 | int c = Hex.HEX_S2B[hex.charAt(i++) & 0xff];
131 | // skip non-hex chars
132 | if (c < 0) {
133 | continue;
134 | }
135 | tmpbuf = tmpbuf | c;
136 | bits += 4;
137 | if (bits == 8) {
138 | buf[j++] = (byte) tmpbuf;
139 | bits = 0;
140 | }
141 | tmpbuf <<= 4;
142 | }
143 | // add extra char if exists
144 | if (bits > 0) {
145 | buf[j++] = (byte) tmpbuf;
146 | }
147 |
148 | // return correctly sized byte[]
149 | if (j == buf.length) {
150 | return buf;
151 | } else {
152 | byte[] smallbuf = new byte[j];
153 | System.arraycopy(buf, 0, smallbuf, 0, j);
154 | return smallbuf;
155 | }
156 | }
157 |
158 | /**
159 | * Print hex dump of buf
160 | * @param buf buf
161 | * @return hex dump
162 | */
163 | public static String dump(byte[] buf) {
164 | if (buf == null) {
165 | return null;
166 | }
167 | StringBuilder sb = new StringBuilder();
168 | dump(sb, buf, 0, buf.length, "", 16, false);
169 |
170 | return sb.toString();
171 | }
172 |
173 | /**
174 | * Hex dump.
175 | * @param sb stringbuilder for result
176 | * @param buf buf to dump
177 | * @param start start index
178 | * @param len length
179 | * @param indent string for indent
180 | * @param lineLen number of bytes per line (16 or 32 are good choices)
181 | * @param lineNum if true, line numbers are shown in left col
182 | */
183 | public static void dump(StringBuilder sb, byte[] buf, int start, int len,
184 | String indent, int lineLen, boolean lineNum) {
185 | if (buf == null) {
186 | if (lineNum) {
187 | sb.append(i2s(0)).append(" - ");
188 | }
189 | sb.append(indent).append("null");
190 | return;
191 | }
192 |
193 | char[] ascii = new char[lineLen];
194 | int lineOffset = 0; // resets to zero for every line
195 |
196 | int i = start; // index into buf
197 | int end = start + len;
198 |
199 | while (i < end) {
200 | // put '\n' and indent to start each line
201 | if (lineOffset == 0) {
202 | if (i > start) {
203 | sb.append('\n');
204 | }
205 | if (lineNum) {
206 | sb.append(i2s(i - start)).append(" - ");
207 | }
208 | sb.append(indent);
209 |
210 | // put a '-' every 8 chars
211 | } else if ((lineOffset & 0x7) == 0) {
212 | sb.append("- ");
213 | }
214 |
215 | // put ascii into ascii buf
216 | ascii[lineOffset++] = (buf[i] >= 32 && buf[i] <= 126) ? (char) buf[i] : '.';
217 | // put hex into sb
218 | sb.append(HEX_B2S[(buf[(i++)] & 0xff)]).append(' ');
219 |
220 | // put ascii at end of each line
221 | if (lineOffset == ascii.length) {
222 | sb.append(" ").append(ascii);
223 | lineOffset = 0;
224 | }
225 | }
226 |
227 | if (lineOffset == 0) {
228 | return;
229 | }
230 |
231 | // put fill to line up ascii print
232 | int missingHex = ascii.length - lineOffset;
233 | // 3 for each hex, 2 for each '- ', 2 at end
234 | int fillLen = missingHex * 3 + missingHex / 8 * 2 + 2;
235 |
236 | while (fillLen-- > 0) {
237 | sb.append(' ');
238 | }
239 | sb.append(ascii, 0, lineOffset);
240 | }
241 | }
242 |
--------------------------------------------------------------------------------
/src/main/java/org/pkcs11/jacknji11/jni/JNI.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
3 | * Permission is hereby granted, free of charge, to any person obtaining a copy
4 | * of this software and associated documentation files (the "Software"), to deal
5 | * in the Software without restriction, including without limitation the rights
6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | * copies of the Software, and to permit persons to whom the Software is
8 | * furnished to do so, subject to the following conditions:
9 | *
10 | * The above copyright notice and this permission notice shall be included in
11 | * all copies or substantial portions of the Software.
12 | *
13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | * THE SOFTWARE.
20 | */
21 |
22 | package org.pkcs11.jacknji11.jni;
23 |
24 | import org.pkcs11.jacknji11.CKA;
25 | import org.pkcs11.jacknji11.CKM;
26 | import org.pkcs11.jacknji11.CK_C_INITIALIZE_ARGS;
27 | import org.pkcs11.jacknji11.CK_INFO;
28 | import org.pkcs11.jacknji11.CK_MECHANISM_INFO;
29 | import org.pkcs11.jacknji11.CK_NOTIFY;
30 | import org.pkcs11.jacknji11.CK_SESSION_INFO;
31 | import org.pkcs11.jacknji11.CK_SLOT_INFO;
32 | import org.pkcs11.jacknji11.CK_TOKEN_INFO;
33 | import org.pkcs11.jacknji11.LongRef;
34 | import org.pkcs11.jacknji11.NativePointer;
35 | import org.pkcs11.jacknji11.NativeProvider;
36 | import org.pkcs11.jacknji11.ULong;
37 |
38 | public class JNI implements NativeProvider {
39 | static {
40 | System.loadLibrary("jacknji11");
41 | init();
42 | ULong.ULONG_SIZE = ULongSize() == 4 ? ULong.ULongSize.ULONG4 : ULong.ULongSize.ULONG8;
43 | }
44 |
45 | public static native void init();
46 | public static native int ULongSize();
47 | public native long C_Initialize(CK_C_INITIALIZE_ARGS pInitArgs);
48 | public native long C_Finalize(NativePointer pReserved);
49 | public native long C_GetInfo(CK_INFO pInfo);
50 | public native long C_GetSlotList(boolean tokenPresent, long[] pSlotList, LongRef pulCount);
51 | public native long C_GetSlotInfo(long slotID, CK_SLOT_INFO pInfo);
52 | public native long C_GetTokenInfo(long slotID, CK_TOKEN_INFO pInfo);
53 | public native long C_WaitForSlotEvent(long flags, LongRef pSlot, NativePointer pReserved);
54 | public native long C_GetMechanismList(long slotID, long[] pMechanismList, LongRef pulCount);
55 | public native long C_GetMechanismInfo(long slotID, long type, CK_MECHANISM_INFO pInfo);
56 | public native long C_InitToken(long slotID, byte[] pPin, long ulPinLen, byte[] pLabel32);
57 | public native long C_InitPIN(long hSession, byte[] pPin, long ulPinLen);
58 | public native long C_SetPIN(long hSession, byte[] pOldPin, long ulOldLen, byte[] pNewPin, long ulNewLen);
59 | public native long C_OpenSession(long slotID, long flags, NativePointer application, CK_NOTIFY notify, LongRef phSession);
60 | public native long C_CloseSession(long hSession);
61 | public native long C_CloseAllSessions(long slotID);
62 | public native long C_GetSessionInfo(long hSession, CK_SESSION_INFO pInfo);
63 | public native long C_GetOperationState(long hSession, byte[] pOperationState, LongRef pulOperationStateLen);
64 | public native long C_SetOperationState(long hSession, byte[] pOperationState, long ulOperationStateLen, long hEncryptionKey, long hAuthenticationKey);
65 | public native long C_Login(long hSession, long userType, byte[] pPin, long ulPinLen);
66 | public native long C_Logout(long hSession);
67 | public native long C_CreateObject(long hSession, CKA[] pTemplate, long ulCount, LongRef phObject);
68 | public native long C_CopyObject(long hSession, long hObject, CKA[] pTemplate, long ulCount, LongRef phNewObject);
69 | public native long C_DestroyObject(long hSession, long hObject);
70 | public native long C_GetObjectSize(long hSession, long hObject, LongRef pulSize);
71 | public native long C_GetAttributeValue(long hSession, long hObject, CKA[] pTemplate, long ulCount);
72 | public native long C_SetAttributeValue(long hSession, long hObject, CKA[] pTemplate, long ulCount);
73 | public native long C_FindObjectsInit(long hSession, CKA[] pTemplate, long ulCount);
74 | public native long C_FindObjects(long hSession, long[] phObject, long ulMaxObjectCount, LongRef pulObjectCount);
75 | public native long C_FindObjectsFinal(long hSession);
76 | public native long C_EncryptInit(long hSession, CKM pMechanism, long hKey);
77 | public native long C_Encrypt(long hSession, byte[] pData, long ulDataLen, byte[] pEncryptedData, LongRef pulEncryptedDataLen);
78 | public native long C_EncryptUpdate(long hSession, byte[] pPart, long ulPartLen, byte[] pEncryptedPart, LongRef pulEncryptedPartLen);
79 | public native long C_EncryptFinal(long hSession, byte[] pLastEncryptedPart, LongRef pulLastEncryptedPartLen);
80 | public native long C_DecryptInit(long hSession, CKM pMechanism, long hKey);
81 | public native long C_Decrypt(long hSession, byte[] pEncryptedData, long ulEncryptedDataLen, byte[] pData, LongRef pulDataLen);
82 | public native long C_DecryptUpdate(long hSession, byte[] pEncryptedPart, long ulEncryptedPartLen, byte[] pData, LongRef pulDataLen);
83 | public native long C_DecryptFinal(long hSession, byte[] pLastPart, LongRef pulLastPartLen);
84 | public native long C_DigestInit(long hSession, CKM pMechanism);
85 | public native long C_Digest(long hSession, byte[] pData, long ulDataLen, byte[] pDigest, LongRef pulDigestLen);
86 | public native long C_DigestUpdate(long hSession, byte[] pPart, long ulPartLen);
87 | public native long C_DigestKey(long hSession, long hKey);
88 | public native long C_DigestFinal(long hSession, byte[] pDigest, LongRef pulDigestLen);
89 | public native long C_SignInit(long hSession, CKM pMechanism, long hKey);
90 | public native long C_Sign(long hSession, byte[] pData, long ulDataLen, byte[] pSignature, LongRef pulSignatureLen);
91 | public native long C_SignUpdate(long hSession, byte[] pPart, long ulPartLen);
92 | public native long C_SignFinal(long hSession, byte[] pSignature, LongRef pulSignatureLen);
93 | public native long C_SignRecoverInit(long hSession, CKM pMechanism, long hKey);
94 | public native long C_SignRecover(long hSession, byte[] pData, long ulDataLen, byte[] pSignature, LongRef pulSignatureLen);
95 | public native long C_VerifyInit(long hSession, CKM pMechanism, long hKey);
96 | public native long C_Verify(long hSession, byte[] pData, long ulDataLen, byte[] pSignature, long ulSignatureLen);
97 | public native long C_VerifyUpdate(long hSession, byte[] pPart, long ulPartLen);
98 | public native long C_VerifyFinal(long hSession, byte[] pSignature, long ulSignatureLen);
99 | public native long C_VerifyRecoverInit(long hSession, CKM pMechanism, long hKey);
100 | public native long C_VerifyRecover(long hSession, byte[] pSignature, long ulSignatureLen, byte[] pData, LongRef pulDataLen);
101 | public native long C_DigestEncryptUpdate(long hSession, byte[] pPart, long ulPartLen, byte[] pEncryptedPart, LongRef pulEncryptedPartLen);
102 | public native long C_DecryptDigestUpdate(long hSession, byte[] pEncryptedPart, long ulEncryptedPartLen, byte[] pPart, LongRef pulPartLen);
103 | public native long C_SignEncryptUpdate(long hSession, byte[] pPart, long ulPartLen, byte[] pEncryptedPart, LongRef pulEncryptedPartLen);
104 | public native long C_DecryptVerifyUpdate(long hSession, byte[] pEncryptedPart, long ulEncryptedPartLen, byte[] pPart, LongRef pulPartLen);
105 | public native long C_GenerateKey(long hSession, CKM pMechanism, CKA[] pTemplate, long ulCount, LongRef phKey);
106 | public native long C_GenerateKeyPair(long hSession, CKM pMechanism, CKA[] pPublicKeyTemplate, long ulPublicKeyAttributeCount, CKA[] pPrivateKeyTemplate, long ulPrivateKeyAttributeCount, LongRef phPublicKey, LongRef phPrivateKey);
107 | public native long C_WrapKey(long hSession, CKM pMechanism, long hWrappingKey, long hKey, byte[] pWrappedKey, LongRef pulWrappedKeyLen);
108 | public native long C_UnwrapKey(long hSession, CKM pMechanism, long hUnwrappingKey, byte[] pWrappedKey, long ulWrappedKeyLen, CKA[] pTemplate, long ulAttributeCount, LongRef phKey);
109 | public native long C_DeriveKey(long hSession, CKM pMechanism, long hBaseKey, CKA[] pTemplate, long ulAttributeCount, LongRef phKey);
110 | public native long C_SeedRandom(long hSession, byte[] pSeed, long ulSeedLen);
111 | public native long C_GenerateRandom(long hSession, byte[] pRandom, long ulRandomLen);
112 | public native long C_GetFunctionStatus(long hSession);
113 | public native long C_CancelFunction(long hSession);
114 | }
115 |
--------------------------------------------------------------------------------
/src/main/java/org/pkcs11/jacknji11/jna/JNANativeI.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
3 | * Permission is hereby granted, free of charge, to any person obtaining a copy
4 | * of this software and associated documentation files (the "Software"), to deal
5 | * in the Software without restriction, including without limitation the rights
6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | * copies of the Software, and to permit persons to whom the Software is
8 | * furnished to do so, subject to the following conditions:
9 | *
10 | * The above copyright notice and this permission notice shall be included in
11 | * all copies or substantial portions of the Software.
12 | *
13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | * THE SOFTWARE.
20 | */
21 |
22 | package org.pkcs11.jacknji11.jna;
23 |
24 | import com.sun.jna.NativeLong;
25 | import com.sun.jna.Pointer;
26 | import com.sun.jna.ptr.NativeLongByReference;
27 |
28 | /**
29 | * JNA Native class with direct mapped methods.
30 | * @author Joel Hockey (joel.hockey@gmail.com)
31 | */
32 | public interface JNANativeI extends com.sun.jna.Library {
33 |
34 | public int C_Initialize(JNA_CK_C_INITIALIZE_ARGS pInitArgs);
35 | public int C_Finalize(Pointer pReserved);
36 | public int C_GetInfo(JNA_CK_INFO pInfo);
37 | public int C_GetSlotList(byte tokenPresent, LongArray pSlotList, NativeLongByReference pulCount);
38 | public int C_GetSlotInfo(NativeLong slotID, JNA_CK_SLOT_INFO pInfo);
39 | public int C_GetTokenInfo(NativeLong slotID, JNA_CK_TOKEN_INFO pInfo);
40 | public int C_WaitForSlotEvent(NativeLong flags, NativeLongByReference pSlot, Pointer pReserved);
41 | public int C_GetMechanismList(NativeLong slotID, LongArray pMechanismList, NativeLongByReference pulCount);
42 | public int C_GetMechanismInfo(NativeLong slotID, NativeLong type, JNA_CK_MECHANISM_INFO pInfo);
43 | public int C_InitToken(NativeLong slotID, byte[] pPin, NativeLong ulPinLen, byte[] pLabel32);
44 | public int C_InitPIN(NativeLong hSession, byte[] pPin, NativeLong ulPinLen);
45 | public int C_SetPIN(NativeLong hSession, byte[] pOldPin, NativeLong ulOldLen, byte[] pNewPin, NativeLong ulNewLen);
46 | public int C_OpenSession(NativeLong slotID, NativeLong flags, Pointer application, JNA_CK_NOTIFY notify, NativeLongByReference phSession);
47 | public int C_CloseSession(NativeLong hSession);
48 | public int C_CloseAllSessions(NativeLong slotID);
49 | public int C_GetSessionInfo(NativeLong hSession, JNA_CK_SESSION_INFO pInfo);
50 | public int C_GetOperationState(NativeLong hSession, byte[] pOperationState, NativeLongByReference pulOperationStateLen);
51 | public int C_SetOperationState(NativeLong hSession, byte[] pOperationState, NativeLong ulOperationStateLen, NativeLong hEncryptionKey, NativeLong hAuthenticationKey);
52 | public int C_Login(NativeLong hSession, NativeLong userType, byte[] pPin, NativeLong ulPinLen);
53 | public int C_Logout(NativeLong hSession);
54 | public int C_CreateObject(NativeLong hSession, Template pTemplate, NativeLong ulCount, NativeLongByReference phObject);
55 | public int C_CopyObject(NativeLong hSession, NativeLong hObject, Template pTemplate, NativeLong ulCount, NativeLongByReference phNewObject);
56 | public int C_DestroyObject(NativeLong hSession, NativeLong hObject);
57 | public int C_GetObjectSize(NativeLong hSession, NativeLong hObject, NativeLongByReference pulSize);
58 | public int C_GetAttributeValue(NativeLong hSession, NativeLong hObject, Template pTemplate, NativeLong ulCount);
59 | public int C_SetAttributeValue(NativeLong hSession, NativeLong hObject, Template pTemplate, NativeLong ulCount);
60 | public int C_FindObjectsInit(NativeLong hSession, Template pTemplate, NativeLong ulCount);
61 | public int C_FindObjects(NativeLong hSession, LongArray phObject, NativeLong ulMaxObjectCount, NativeLongByReference pulObjectCount);
62 | public int C_FindObjectsFinal(NativeLong hSession);
63 | public int C_EncryptInit(NativeLong hSession, JNA_CKM pMechanism, NativeLong hKey);
64 | public int C_Encrypt(NativeLong hSession, byte[] pData, NativeLong ulDataLen, byte[] pEncryptedData, NativeLongByReference pulEncryptedDataLen);
65 | public int C_EncryptUpdate(NativeLong hSession, byte[] pPart, NativeLong ulPartLen, byte[] pEncryptedPart, NativeLongByReference pulEncryptedPartLen);
66 | public int C_EncryptFinal(NativeLong hSession, byte[] pLastEncryptedPart, NativeLongByReference pulLastEncryptedPartLen);
67 | public int C_DecryptInit(NativeLong hSession, JNA_CKM pMechanism, NativeLong hKey);
68 | public int C_Decrypt(NativeLong hSession, byte[] pEncryptedData, NativeLong ulEncryptedDataLen, byte[] pData, NativeLongByReference pulDataLen);
69 | public int C_DecryptUpdate(NativeLong hSession, byte[] pEncryptedPart, NativeLong ulEncryptedPartLen, byte[] pData, NativeLongByReference pulDataLen);
70 | public int C_DecryptFinal(NativeLong hSession, byte[] pLastPart, NativeLongByReference pulLastPartLen);
71 | public int C_DigestInit(NativeLong hSession, JNA_CKM pMechanism);
72 | public int C_Digest(NativeLong hSession, byte[] pData, NativeLong ulDataLen, byte[] pDigest, NativeLongByReference pulDigestLen);
73 | public int C_DigestUpdate(NativeLong hSession, byte[] pPart, NativeLong ulPartLen);
74 | public int C_DigestKey(NativeLong hSession, NativeLong hKey);
75 | public int C_DigestFinal(NativeLong hSession, byte[] pDigest, NativeLongByReference pulDigestLen);
76 | public int C_SignInit(NativeLong hSession, JNA_CKM pMechanism, NativeLong hKey);
77 | public int C_Sign(NativeLong hSession, byte[] pData, NativeLong ulDataLen, byte[] pSignature, NativeLongByReference pulSignatureLen);
78 | public int C_SignUpdate(NativeLong hSession, byte[] pPart, NativeLong ulPartLen);
79 | public int C_SignFinal(NativeLong hSession, byte[] pSignature, NativeLongByReference pulSignatureLen);
80 | public int C_SignRecoverInit(NativeLong hSession, JNA_CKM pMechanism, NativeLong hKey);
81 | public int C_SignRecover(NativeLong hSession, byte[] pData, NativeLong ulDataLen, byte[] pSignature, NativeLongByReference pulSignatureLen);
82 | public int C_VerifyInit(NativeLong hSession, JNA_CKM pMechanism, NativeLong hKey);
83 | public int C_Verify(NativeLong hSession, byte[] pData, NativeLong ulDataLen, byte[] pSignature, NativeLong ulSignatureLen);
84 | public int C_VerifyUpdate(NativeLong hSession, byte[] pPart, NativeLong ulPartLen);
85 | public int C_VerifyFinal(NativeLong hSession, byte[] pSignature, NativeLong ulSignatureLen);
86 | public int C_VerifyRecoverInit(NativeLong hSession, JNA_CKM pMechanism, NativeLong hKey);
87 | public int C_VerifyRecover(NativeLong hSession, byte[] pSignature, NativeLong ulSignatureLen, byte[] pData, NativeLongByReference pulDataLen);
88 | public int C_DigestEncryptUpdate(NativeLong hSession, byte[] pPart, NativeLong ulPartLen, byte[] pEncryptedPart, NativeLongByReference pulEncryptedPartLen);
89 | public int C_DecryptDigestUpdate(NativeLong hSession, byte[] pEncryptedPart, NativeLong ulEncryptedPartLen, byte[] pPart, NativeLongByReference pulPartLen);
90 | public int C_SignEncryptUpdate(NativeLong hSession, byte[] pPart, NativeLong ulPartLen, byte[] pEncryptedPart, NativeLongByReference pulEncryptedPartLen);
91 | public int C_DecryptVerifyUpdate(NativeLong hSession, byte[] pEncryptedPart, NativeLong ulEncryptedPartLen, byte[] pPart, NativeLongByReference pulPartLen);
92 | public int C_GenerateKey(NativeLong hSession, JNA_CKM pMechanism, Template pTemplate, NativeLong ulCount, NativeLongByReference phKey);
93 | public int C_GenerateKeyPair(NativeLong hSession, JNA_CKM pMechanism, Template pPublicKeyTemplate, NativeLong ulPublicKeyAttributeCount, Template pPrivateKeyTemplate, NativeLong ulPrivateKeyAttributeCount, NativeLongByReference phPublicKey, NativeLongByReference phPrivateKey);
94 | public int C_WrapKey(NativeLong hSession, JNA_CKM pMechanism, NativeLong hWrappingKey, NativeLong hKey, byte[] pWrappedKey, NativeLongByReference pulWrappedKeyLen);
95 | public int C_UnwrapKey(NativeLong hSession, JNA_CKM pMechanism, NativeLong hUnwrappingKey, byte[] pWrappedKey, NativeLong ulWrappedKeyLen, Template pTemplate, NativeLong ulAttributeCount, NativeLongByReference phKey);
96 | public int C_DeriveKey(NativeLong hSession, JNA_CKM pMechanism, NativeLong hBaseKey, Template pTemplate, NativeLong ulAttributeCount, NativeLongByReference phKey);
97 | public int C_SeedRandom(NativeLong hSession, byte[] pSeed, NativeLong ulSeedLen);
98 | public int C_GenerateRandom(NativeLong hSession, byte[] pRandom, NativeLong ulRandomLen);
99 | public int C_GetFunctionStatus(NativeLong hSession);
100 | public int C_CancelFunction(NativeLong hSession);
101 | }
102 |
--------------------------------------------------------------------------------
/src/main/java/org/pkcs11/jacknji11/jffi/JFFINative.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
3 | * Permission is hereby granted, free of charge, to any person obtaining a copy
4 | * of this software and associated documentation files (the "Software"), to deal
5 | * in the Software without restriction, including without limitation the rights
6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | * copies of the Software, and to permit persons to whom the Software is
8 | * furnished to do so, subject to the following conditions:
9 | *
10 | * The above copyright notice and this permission notice shall be included in
11 | * all copies or substantial portions of the Software.
12 | *
13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | * THE SOFTWARE.
20 | */
21 |
22 | package org.pkcs11.jacknji11.jffi;
23 |
24 | import jnr.ffi.Address;
25 | import jnr.ffi.Library;
26 | import jnr.ffi.Pointer;
27 | import jnr.ffi.annotations.In;
28 | import jnr.ffi.annotations.Out;
29 | import jnr.ffi.byref.NativeLongByReference;
30 |
31 | /**
32 | * JFFI Native class.
33 | * @author Joel Hockey (joel.hockey@gmail.com)
34 | */
35 | public class JFFINative {
36 | static {
37 | Library.loadLibrary(JFFINative.class, "cryptoki");
38 | }
39 |
40 | public static native int C_Initialize(@In JFFI_CK_C_INITIALIZE_ARGS pInitArgs);
41 | public static native int C_Finalize(@In Address pReserved);
42 | public static native int C_GetInfo(@Out JFFI_CK_INFO pInfo);
43 | public static native int C_GetSlotList(@In boolean tokenPresent, @Out long[] pSlotList, @In @Out NativeLongByReference pulCount);
44 | public static native int C_GetSlotInfo(@In long slotID, @Out JFFI_CK_SLOT_INFO pInfo);
45 | public static native int C_GetTokenInfo(@In long slotID, @Out JFFI_CK_TOKEN_INFO pInfo);
46 | public static native int C_WaitForSlotEvent(@In long flags, @Out NativeLongByReference pSlot, @In Address pReserved);
47 | public static native int C_GetMechanismList(@In long slotID, @Out long[] pMechanismList, @In @Out NativeLongByReference pulCount);
48 | public static native int C_GetMechanismInfo(@In long slotID, @In long type, @Out JFFI_CK_MECHANISM_INFO pInfo);
49 | public static native int C_InitToken(@In long slotID, @In byte[] pPin, @In long ulPinLen, @In byte[] pLabel32);
50 | public static native int C_InitPIN(@In long hSession, @In byte[] pPin, @In long ulPinLen);
51 | public static native int C_SetPIN(@In long hSession, @In byte[] pOldPin, @In long ulOldLen, @In byte[] pNewPin, @In long ulNewLen);
52 | public static native int C_OpenSession(@In long slotID, @In long flags, @In Address application, @In Address notify, @In @Out NativeLongByReference phSession);
53 | public static native int C_CloseSession(@In long hSession);
54 | public static native int C_CloseAllSessions(@In long slotID);
55 | public static native int C_GetSessionInfo(@In long hSession, @Out JFFI_CK_SESSION_INFO pInfo);
56 | public static native int C_GetOperationState(@In long hSession, @In byte[] pOperationState, @In @Out NativeLongByReference pulOperationStateLen);
57 | public static native int C_SetOperationState(@In long hSession, @In byte[] pOperationState, @In long ulOperationStateLen, @In long hEncryptionKey, @In long hAuthenticationKey);
58 | public static native int C_Login(@In long hSession, @In long userType, @In byte[] pPin, @In long ulPinLen);
59 | public static native int C_Logout(@In long hSession);
60 | public static native int C_CreateObject(@In long hSession, @In Pointer pTemplate, @In long ulCount, @In @Out NativeLongByReference phObject);
61 | public static native int C_CopyObject(@In long hSession, long hObject, @In Pointer pTemplate, @In long ulCount, @In @Out NativeLongByReference phNewObject);
62 | public static native int C_DestroyObject(@In long hSession, @In long hObject);
63 | public static native int C_GetObjectSize(@In long hSession, @In long hObject, @In @Out NativeLongByReference pulSize);
64 | public static native int C_GetAttributeValue(@In long hSession, @In long hObject, @In @Out Pointer pTemplate, @In long ulCount);
65 | public static native int C_SetAttributeValue(@In long hSession, @In long hObject, @In Pointer pTemplate, @In long ulCount);
66 | public static native int C_FindObjectsInit(@In long hSession, @In Pointer pTemplate, @In long ulCount);
67 | public static native int C_FindObjects(@In long hSession, @Out long[] phObject, @In long ulMaxObjectCount, @In @Out NativeLongByReference pulObjectCount);
68 | public static native int C_FindObjectsFinal(@In long hSession);
69 | public static native int C_EncryptInit(@In long hSession, @In JFFI_CKM pMechanism, @In long hKey);
70 | public static native int C_Encrypt(@In long hSession, @In byte[] pData, @In long ulDataLen, @In byte[] pEncryptedData, @In @Out NativeLongByReference pulEncryptedDataLen);
71 | public static native int C_EncryptUpdate(@In long hSession, @In byte[] pPart, @In long ulPartLen, @Out byte[] pEncryptedPart, @In @Out NativeLongByReference pulEncryptedPartLen);
72 | public static native int C_EncryptFinal(@In long hSession, @Out byte[] pLastEncryptedPart, @In @Out NativeLongByReference pulLastEncryptedPartLen);
73 | public static native int C_DecryptInit(@In long hSession, @In JFFI_CKM pMechanism, @In long hKey);
74 | public static native int C_Decrypt(@In long hSession, @In byte[] pEncryptedData, @In long ulEncryptedDataLen, @In byte[] pData, @In @Out NativeLongByReference pulDataLen);
75 | public static native int C_DecryptUpdate(@In long hSession, @In byte[] pEncryptedPart, @In long ulEncryptedPartLen, @Out byte[] pData, @In @Out NativeLongByReference pulDataLen);
76 | public static native int C_DecryptFinal(@In long hSession, @Out byte[] pLastPart, @In @Out NativeLongByReference pulLastPartLen);
77 | public static native int C_DigestInit(@In long hSession, @In JFFI_CKM pMechanism);
78 | public static native int C_Digest(@In long hSession, @In byte[] pData, @In long ulDataLen, @Out byte[] pDigest, @In @Out NativeLongByReference pulDigestLen);
79 | public static native int C_DigestUpdate(@In long hSession, @In byte[] pPart, @In long ulPartLen);
80 | public static native int C_DigestKey(@In long hSession, @In long hKey);
81 | public static native int C_DigestFinal(@In long hSession, @Out byte[] pDigest, @In @Out NativeLongByReference pulDigestLen);
82 | public static native int C_SignInit(@In long hSession, @In JFFI_CKM pMechanism, @In long hKey);
83 | public static native int C_Sign(@In long hSession, @In byte[] pData, @In long ulDataLen, @Out byte[] pSignature, @In @Out NativeLongByReference pulSignatureLen);
84 | public static native int C_SignUpdate(@In long hSession, @In byte[] pPart, @In long ulPartLen);
85 | public static native int C_SignFinal(@In long hSession, @Out byte[] pSignature, @In @Out NativeLongByReference pulSignatureLen);
86 | public static native int C_SignRecoverInit(@In long hSession, @In JFFI_CKM pMechanism, @In long hKey);
87 | public static native int C_SignRecover(@In long hSession, @In byte[] pData, @In long ulDataLen, @Out byte[] pSignature, @In @Out NativeLongByReference pulSignatureLen);
88 | public static native int C_VerifyInit(@In long hSession, @In JFFI_CKM pMechanism, @In long hKey);
89 | public static native int C_Verify(@In long hSession, @In byte[] pData, @In long ulDataLen, @In byte[] pSignature, @In long ulSignatureLen);
90 | public static native int C_VerifyUpdate(@In long hSession, @In byte[] pPart, @In long ulPartLen);
91 | public static native int C_VerifyFinal(@In long hSession, @In byte[] pSignature, @In long ulSignatureLen);
92 | public static native int C_VerifyRecoverInit(@In long hSession, @In JFFI_CKM pMechanism, @In long hKey);
93 | public static native int C_VerifyRecover(@In long hSession, @In byte[] pSignature, @In long ulSignatureLen, @In byte[] pData, @In @Out NativeLongByReference pulDataLen);
94 | public static native int C_DigestEncryptUpdate(@In long hSession, @In byte[] pPart, @In long ulPartLen, @Out byte[] pEncryptedPart, @In @Out NativeLongByReference pulEncryptedPartLen);
95 | public static native int C_DecryptDigestUpdate(@In long hSession, @In byte[] pEncryptedPart, @In long ulEncryptedPartLen, @Out byte[] pPart, @In @Out NativeLongByReference pulPartLen);
96 | public static native int C_SignEncryptUpdate(@In long hSession, @In byte[] pPart, @In long ulPartLen, @Out byte[] pEncryptedPart, @In @Out NativeLongByReference pulEncryptedPartLen);
97 | public static native int C_DecryptVerifyUpdate(@In long hSession, @In byte[] pEncryptedPart, @In long ulEncryptedPartLen, @Out byte[] pPart, @In @Out NativeLongByReference pulPartLen);
98 | public static native int C_GenerateKey(@In long hSession, @In JFFI_CKM pMechanism, @In Pointer pTemplate, @In long ulCount, @Out NativeLongByReference phKey);
99 | public static native int C_GenerateKeyPair(@In long hSession, @In JFFI_CKM pMechanism, @In Pointer pPublicKeyTemplate, @In long ulPublicKeyAttributeCount, @In Pointer pPrivateKeyTemplate, @In long ulPrivateKeyAttributeCount, @Out NativeLongByReference phPublicKey, @Out NativeLongByReference phPrivateKey);
100 | public static native int C_WrapKey(@In long hSession, @In JFFI_CKM pMechanism, @In long hWrappingKey, @In long hKey, @Out byte[] pWrappedKey, @In @Out NativeLongByReference pulWrappedKeyLen);
101 | public static native int C_UnwrapKey(@In long hSession, @In JFFI_CKM pMechanism, @In long hUnwrappingKey, @In byte[] pWrappedKey, @In long ulWrappedKeyLen, @In Pointer pTemplate, @In long ulAttributeCount, @Out NativeLongByReference phKey);
102 | public static native int C_DeriveKey(@In long hSession, @In JFFI_CKM pMechanism, @In long hBaseKey, @In Pointer pTemplate, @In long ulAttributeCount, @Out NativeLongByReference phKey);
103 | public static native int C_SeedRandom(@In long hSession, @In byte[] pSeed, @In long ulSeedLen);
104 | public static native int C_GenerateRandom(@In long hSession, @In byte[] pRandomData, @In long ulRandomLen);
105 | public static native int C_GetFunctionStatus(@In long hSession);
106 | public static native int C_CancelFunction(@In long hSession);
107 | }
108 |
--------------------------------------------------------------------------------
/src/test/java/org/pkcs11/jacknji11/CKATest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
3 | * Permission is hereby granted, free of charge, to any person obtaining a copy
4 | * of this software and associated documentation files (the "Software"), to deal
5 | * in the Software without restriction, including without limitation the rights
6 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | * copies of the Software, and to permit persons to whom the Software is
8 | * furnished to do so, subject to the following conditions:
9 | *
10 | * The above copyright notice and this permission notice shall be included in
11 | * all copies or substantial portions of the Software.
12 | *
13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | * THE SOFTWARE.
20 | */
21 | package org.pkcs11.jacknji11;
22 |
23 | import org.junit.Test;
24 |
25 | import java.math.BigInteger;
26 | import java.nio.charset.StandardCharsets;
27 |
28 | import static org.junit.Assert.assertArrayEquals;
29 | import static org.junit.Assert.assertEquals;
30 | import static org.junit.Assert.assertFalse;
31 | import static org.junit.Assert.assertNotNull;
32 | import static org.junit.Assert.assertNull;
33 | import static org.junit.Assert.assertTrue;
34 |
35 | public class CKATest {
36 |
37 |
38 | @Test
39 | public void testAllocate() {
40 | CKA cka = CKA.allocate(CKA.MODULUS, 100);
41 |
42 | // value is null because the buffer is not really set with anything
43 | assertNull(cka.getValue());
44 | assertEquals(100, cka.ulValueLen);
45 | // however the pValue points at a buffer
46 | assertNotNull(cka.pValue);
47 |
48 | // it can also be checked by hasValue
49 | assertFalse(cka.hasValue());
50 |
51 | // to string should not display any value, however it shall display its allocated state
52 | assertEquals(cka.toString(), "type=0x00000120{MODULUS} ALLOCATED [100B]");
53 |
54 | // now let's emulate setting the value (this happens when Cryptoki native structure is applied back onto CKA)
55 | cka.set();
56 |
57 | // value is no longer null
58 | assertNotNull(cka.getValue());
59 |
60 | // and value is set therfeore hasValue returns true
61 | assertTrue(cka.hasValue());
62 |
63 | // to string should now display the value and the BUFFERED state shall not be displayed
64 | assertTrue(cka.toString().contains("type=0x00000120{MODULUS} [100B]"));
65 |
66 | }
67 |
68 | @Test
69 | public void testIndefinite() {
70 | CKA cka = CKA.indefinite(CKA.VALUE);
71 |
72 | // the CKA has no value
73 | assertNull(cka.getValue());
74 | // it also does not have a buffer
75 | assertNull(cka.pValue);
76 | // and the length is 0
77 | assertEquals(0, cka.ulValueLen);
78 |
79 | // it can also be checked by hasValue
80 | assertFalse(cka.hasValue());
81 |
82 | // to string should not display any value, however it shall display its indefinite state
83 | assertEquals(cka.toString(), "type=0x00000011{VALUE} INDEFINITE");
84 |
85 | // let's emulate setting the value (this happens when Cryptoki native structure is applied back onto CKA)
86 | // in this case as buffer is null, only the length is set
87 | cka.set();
88 | cka.ulValueLen = 100;
89 |
90 | // value is still null
91 | assertNull(cka.getValue());
92 |
93 | // but the length is set
94 | assertEquals(100, cka.ulValueLen);
95 |
96 | // however hasValue still returns false (as there is actually no value set)
97 | assertFalse(cka.hasValue());
98 |
99 | // to string should now display the length and the INDEFINITE state shall not be displayed
100 | assertEquals(cka.toString(), cka.toString(), "type=0x00000011{VALUE} DEFINITE [100B]");
101 |
102 | }
103 |
104 | @Test
105 | public void testEmpty() {
106 | // lets create the empty attribute
107 | CKA cka = new CKA(CKA.VALUE, null);
108 |
109 | // the CKA has no value
110 | assertNull(cka.getValue());
111 | // it also does not have a buffer
112 | assertNull(cka.pValue);
113 | // and the length is 0
114 | assertEquals(0, cka.ulValueLen);
115 |
116 | // it can also be checked by hasValue
117 | assertFalse(cka.hasValue());
118 |
119 | // to string should not display any value, however it shall display its empty state
120 | assertEquals(cka.toString(), "type=0x00000011{VALUE} EMPTY");
121 |
122 | }
123 |
124 | @Test
125 | public void testEmptyFromQuery() {
126 | // lets create the buffered attribute
127 | CKA cka = CKA.allocate(CKA.VALUE, 100);
128 |
129 | // now let's set the empty state
130 | cka.ulValueLen = 0;
131 | cka.set();
132 |
133 | // the CKA has no value
134 | assertNull(cka.getValue());
135 |
136 | // and the length is 0
137 | assertEquals(0, cka.ulValueLen);
138 |
139 | // it can also be checked by hasValue
140 | assertFalse(cka.hasValue());
141 |
142 | // to string should not display any value, however it shall display its empty state
143 | assertEquals(cka.toString(), "type=0x00000011{VALUE} EMPTY");
144 |
145 | }
146 |
147 | @Test
148 | public void testBool() {
149 | CKA cka = new CKA(CKA.SENSITIVE, true);
150 |
151 | // we check the encoding
152 | byte[] bytes = cka.getValue();
153 | assertArrayEquals(new byte[]{1}, bytes);
154 |
155 | // and the value
156 | assertTrue(cka.getValueBool());
157 |
158 | // now let's create this attribute from the encoding of value
159 | CKA cka2 = new CKA(CKA.SENSITIVE, bytes);
160 |
161 | // and check the value
162 | assertTrue(cka2.getValueBool());
163 |
164 | // and the encoded bytes (should be the same)
165 | assertArrayEquals(new byte[]{1}, cka2.getValue());
166 |
167 | // also while we have the object let's check the toString
168 | assertTrue(cka.toString(), cka.toString().contains("type=0x00000103{SENSITIVE} [1B] value=TRUE"));
169 |
170 | assertEquals(cka, cka2);
171 | assertEquals(cka.hashCode(), cka2.hashCode());
172 | }
173 |
174 | @Test
175 | public void testULong() {
176 | CKA cka = new CKA(CKA.VALUE_LEN, 100L);
177 | byte[] expectedBytes = ULong.ulong2b(100L);
178 |
179 | // we check the encoding
180 | byte[] bytes = cka.getValue();
181 | assertArrayEquals(expectedBytes, bytes);
182 |
183 | // and the value
184 | assertEquals(100L, cka.getValueLong().longValue());
185 |
186 | // now let's create this attribute from the encoding of value
187 | CKA cka2 = new CKA(CKA.VALUE_LEN, bytes);
188 |
189 | // and check the value
190 | assertEquals(100L, cka2.getValueLong().longValue());
191 |
192 | // and the encoded bytes (should be the same)
193 | assertArrayEquals(expectedBytes, cka2.getValue());
194 |
195 | // also while we have the object let's check the toString
196 | assertTrue(cka.toString(), cka.toString().contains("type=0x00000161{VALUE_LEN} [4B] value=100"));
197 |
198 | assertEquals(cka, cka2);
199 | assertEquals(cka.hashCode(), cka2.hashCode());
200 | }
201 |
202 |
203 | @Test
204 | public void testString() {
205 | String expectedStr = "test";
206 | byte[] expectedBytes = expectedStr.getBytes(StandardCharsets.US_ASCII);
207 | CKA cka = new CKA(CKA.LABEL, expectedStr);
208 |
209 | // we check the encoding
210 | byte[] bytes = cka.getValue();
211 | assertArrayEquals(expectedBytes, bytes);
212 |
213 | // and the value
214 | assertEquals(expectedStr, cka.getValueStr());
215 |
216 | // now let's create this attribute from the encoding of value
217 | CKA cka2 = new CKA(CKA.LABEL, bytes);
218 |
219 | // and check the value
220 | assertEquals(expectedStr, cka2.getValueStr());
221 |
222 | // and the encoded bytes (should be the same)
223 | assertArrayEquals(expectedBytes, cka2.getValue());
224 |
225 | // also while we have the object let's check the toString
226 | assertTrue(cka.toString(), cka.toString().contains("type=0x00000003{LABEL} [4B] value=\"test\""));
227 |
228 | assertEquals(cka, cka2);
229 | assertEquals(cka.hashCode(), cka2.hashCode());
230 |
231 | }
232 |
233 | @Test
234 | public void testBigInt() {
235 |
236 | // the test value is taken directly from PKCS#11 spec
237 | // Big integer
238 | // a string of CK_BYTEs representing an unsigned integer of arbitrary size,
239 | // most-significant byte first (e.g., the integer 32768 is represented as the 2-byte string 0x80 0x00)
240 | // this encoding when using two-complement encoding in big endian is a negative number
241 | // therefore needs special handling
242 |
243 | BigInteger expectedBint = BigInteger.valueOf(32768L);
244 | byte[] expectedBytes = {(byte) 0x80, 0x00};
245 |
246 | // lets create the attribute from value
247 | CKA cka = new CKA(CKA.MODULUS, expectedBint);
248 |
249 | // we check the encoding
250 | byte[] bytes = cka.getValue();
251 | assertArrayEquals(expectedBytes, bytes);
252 |
253 | // and the value
254 | BigInteger bint = cka.getValueBigInt();
255 | assertEquals(expectedBint, bint);
256 |
257 | // now let's create this attribute from the encoding of value
258 | CKA cka2 = new CKA(CKA.MODULUS, bytes);
259 |
260 | // and check the value
261 | bint = cka2.getValueBigInt();
262 | assertEquals(expectedBint, bint);
263 |
264 | // and the encoded bytes (should be the same)
265 | assertArrayEquals(expectedBytes, cka2.getValue());
266 |
267 | // also while we have the object let's check the toString
268 | assertTrue(cka.toString().contains("type=0x00000120{MODULUS} [2B]"));
269 | assertTrue(cka.toString().contains("80 00"));
270 |
271 | assertEquals(cka, cka2);
272 | assertEquals(cka.hashCode(), cka2.hashCode());
273 | }
274 |
275 |
276 | }
277 |
--------------------------------------------------------------------------------